Definition

drupal_build_css_cache($types, $filename)
drupal-5/includes/common.inc, line 1513

Description

Aggregate and optimize CSS files, putting them in the files directory.

Parameters

$types An array of types of CSS files (e.g., screen, print) to aggregate and compress into one file.

$filename The name of the aggregate CSS file.

Return value

The name of the CSS file.

Related topics

Namesort iconDescription
Input validationFunctions to validate user input.

Code

<?php
function drupal_build_css_cache($types, $filename) {
  $data = '';

  // Create the css/ within the files folder.
  $csspath = file_create_path('css');
  file_check_directory($csspath, FILE_CREATE_DIRECTORY);

  if (!file_exists($csspath .'/'. $filename)) {
    // Build aggregate CSS file.
    foreach ($types as $type) {
      foreach ($type as $file => $cache) {
        if ($cache) {
          $contents = file_get_contents($file);
          // Remove multiple charset declarations for standards compliance (and fixing Safari problems)
          $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
          // Return the path to where this CSS file originated from, stripping off the name of the file at the end of the path.
          $path = base_path() . substr($file, 0, strrpos($file, '/')) .'/';
          // Wraps all @import arguments in url().
          $contents = preg_replace('/@import\s+(?!url)[\'"]?(\S*)\b[\'"]?/i', '@import url("\1")', $contents);
          // Fix all paths within this CSS file, ignoring absolute paths.
          $data .= preg_replace('/url\(([\'"]?)(?![a-z]+:)/i', 'url(\1'. $path . '\2', $contents);
        }
      }
    }

    // @import rules must proceed any other style, so we move those to the top.
    $regexp = '/@import[^;]+;/i';
    preg_match_all($regexp, $data, $matches);
    $data = preg_replace($regexp, '', $data);
    $data = implode('', $matches[0]) . $data;

    // Perform some safe CSS optimizations.
    $data = preg_replace('<
      \s*([@{}:;,]|\)\s|\s\()\s* |  # Remove whitespace around separators, but keep space around parentheses.
      /\*([^*\\\\]|\*(?!/))+\*/ |   # Remove comments that are not CSS hacks.
      [\n\r]                        # Remove line breaks.
      >x', '\1', $data);

    // Create the CSS file.
    file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
  }
  return $csspath .'/'. $filename;
}
?>