You are here

function cdn_update_file in CDN 5

Updates the contents of the file for CDN compatibility: it searches all relative URLs and replaces it with absolute URLs to files hosted on the CDN, if they're available on the CDN already, otherwise they are replaced with absolute URLs to the files hosted on the local server.

Parameters

$file_path: The path to the file, relative to the Drupal root directory.

$files_synced: (optional) An array of synced files, with the keys the source file paths and the values the file paths on the server. This parameter is used by to be able to update files while the synchronization is still running, to get the new files on the CDN.

Return value

Path to the updated file (the original file will never be changed).

1 call to cdn_update_file()
_cdn_cron_update_files_wrapper in ./cdn_cron.inc
Wrapper of cdn_update_file() for use only within cron mode. This function simply calls cdn_update_file(), but also sets the $files_synced parameter.

File

./cdn.inc, line 173
Basic functions for CDN integration and synchronization.

Code

function cdn_update_file($file_path, $files_synced = array()) {
  $contents = file_get_contents($file_path);

  // Strip surrounding apostrophes or quotes.
  $contents = preg_replace('/(?<=url\\()([\'"]{1})(.*)\\1{1}/', '\\2', $contents);

  // Remove the leading base path.
  $contents = preg_replace('/url\\(' . preg_quote(base_path(), '/.') . '([\\d\\w-_\\.\\/]+)/i', 'url(\\1', $contents);

  // Route all paths through the relative path resolving function, ignoring
  // absolute URLs.
  $contents = preg_replace_callback('/(?<=url\\()[\\d\\w-_\\.\\/]+(?=\\))/i', create_function('$matches', 'return _cdn_file_path_resolve_relative_paths($matches[0]);'), $contents);

  // Create the function body of the anonymous function.
  if (empty($files_synced)) {
    $function_body = 'return cdn_file_url($matches[0]);';
  }
  else {
    $function_body = 'return cdn_file_url($matches[0], ' . var_export($files_synced, TRUE) . ');';
  }

  // Route all paths through cdn_file_url(), ignoring absolute URLs.
  $contents = preg_replace_callback('/(?<=url\\()[\\d\\w-_\\.\\/]+(?=\\))/i', create_function('$matches', $function_body), $contents);

  // Create the CDN directory if it does not yet exist.
  file_check_directory(file_create_path('cdn'), FILE_CREATE_DIRECTORY);
  return file_save_data($contents, 'cdn/' . md5($file_path), FILE_EXISTS_REPLACE);
}