You are here

function _css_emimage_process in CSS Embedded Images 6

Same name and namespace in other branches
  1. 6.2 css_emimage.module \_css_emimage_process()
  2. 7 css_emimage.module \_css_emimage_process()

Helper function to replace URLs with data URIs.

1 call to _css_emimage_process()
css_emimage_preprocess_page in ./css_emimage.module
Implementation of hook_preprocess_hook().

File

./css_emimage.module, line 65

Code

function _css_emimage_process($styles) {
  $path_to_files_directory = base_path() . file_directory_path();
  $pattern = '/href=".*?' . preg_quote($path_to_files_directory, '/') . '(.*?)(\\?|")/';
  if (preg_match_all($pattern, $styles, $matches) > 0) {
    foreach ($matches[1] as $aggregated_file_name) {
      $datauri_file_name = str_replace('.css', '.emimage.css', $aggregated_file_name);
      $datauri_file_path = file_directory_path() . $datauri_file_name;

      // Save the processed CSS file if it doesn't exist yet.
      if (!file_exists($datauri_file_path)) {
        $contents = file_get_contents(file_directory_path() . $aggregated_file_name);
        $datauri_contents = preg_replace_callback('/[^}]+{[^{}]+(url\\([\'"]?' . preg_quote(base_path(), '/') . '([^\'")]+)[\'"]?\\))[^{}]*}/i', '_css_emimage_replace', $contents);

        // Check if an error occurred parsing the CSS.
        if (is_null($datauri_contents)) {
          $error_code = preg_last_error();
          $error_messages = array(
            PREG_NO_ERROR => 'NO_ERROR',
            PREG_INTERNAL_ERROR => 'INTERNAL_ERROR',
            PREG_BACKTRACK_LIMIT_ERROR => 'BACKTRACK_LIMIT_ERROR',
            PREG_RECURSION_LIMIT_ERROR => 'RECURSION_LIMIT_ERROR',
            PREG_BAD_UTF8_ERROR => 'BAD_UTF8_ERROR',
            PREG_BAD_UTF8_OFFSET_ERROR => 'BAD_UTF8_OFFSET_ERROR',
          );
          watchdog('css_emimage', 'Error while trying to embed images in your CSS, falling back to unmodified CSS. PCRE error was: !error.', array(
            '!error' => array_key_exists($error_code, $error_messages) ? $error_messages[$error_code] : $error_code,
          ), WATCHDOG_ERROR);
          $datauri_contents = $contents;
        }

        // Save the contents to the new CSS file.
        file_save_data($datauri_contents, $datauri_file_path, FILE_EXISTS_REPLACE);
      }

      // Replace the aggregated file with the processed CSS file.
      $styles = str_replace($aggregated_file_name, $datauri_file_name, $styles);
    }
  }
  return $styles;
}