You are here

function _googleanalytics_cache in Google Analytics 7

Same name and namespace in other branches
  1. 5 googleanalytics.module \_googleanalytics_cache()
  2. 6.4 googleanalytics.module \_googleanalytics_cache()
  3. 6 googleanalytics.module \_googleanalytics_cache()
  4. 6.2 googleanalytics.module \_googleanalytics_cache()
  5. 6.3 googleanalytics.module \_googleanalytics_cache()
  6. 7.2 googleanalytics.module \_googleanalytics_cache()

Download/Synchronize/Cache tracking code file locally.

Parameters

$location: The full URL to the external javascript file.

$sync_cached_file: Synchronize tracking code and update if remote file have changed.

Return value

mixed The path to the local javascript file on success, boolean FALSE on failure.

2 calls to _googleanalytics_cache()
googleanalytics_cron in ./googleanalytics.module
Implements hook_cron().
googleanalytics_page_alter in ./googleanalytics.module
Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.

File

./googleanalytics.module, line 469
Drupal Module: Google Analytics

Code

function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
  $path = 'public://googleanalytics';
  $file_destination = $path . '/' . basename($location);
  if (!file_exists($file_destination) || $sync_cached_file) {

    // Download the latest tracking code.
    $result = drupal_http_request($location);
    if ($result->code == 200) {
      if (file_exists($file_destination)) {

        // Synchronize tracking code and and replace local file if outdated.
        $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
        $data_hash_remote = drupal_hash_base64($result->data);

        // Check that the files directory is writable.
        if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {

          // Save updated tracking code file to disk.
          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
          watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);

          // Change query-strings on css/js files to enforce reload for all users.
          _drupal_flush_css_js();
        }
      }
      else {

        // Check that the files directory is writable.
        if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {

          // There is no need to flush JS here as core refreshes JS caches
          // automatically, if new files are added.
          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
          watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);

          // Return the local JS file path.
          return file_create_url($file_destination);
        }
      }
    }
  }
  else {

    // Return the local JS file path.
    return file_create_url($file_destination);
  }
}