You are here

function _piwik_cache in Piwik Web Analytics 6

Same name and namespace in other branches
  1. 8 piwik.module \_piwik_cache()
  2. 5 piwik.module \_piwik_cache()
  3. 6.2 piwik.module \_piwik_cache()
  4. 7.2 piwik.module \_piwik_cache()
  5. 7 piwik.module \_piwik_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 _piwik_cache()
piwik_cron in ./piwik.module
Implementation of hook_cron().
piwik_init in ./piwik.module

File

./piwik.module, line 214
Drupal Module: Piwik Adds the required Javascript to the bottom of all your Drupal pages to allow tracking by the Piwik statistics package.

Code

function _piwik_cache($location, $sync_cached_file = FALSE) {
  $path = file_create_path('piwik');
  $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 = md5(file_get_contents($file_destination));
        $data_hash_remote = md5($result->data);

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

          // Save updated tracking code file to disk.
          file_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
          watchdog('piwik', '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_check_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_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
          watchdog('piwik', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);

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

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