You are here

function ad_cache_file_close in Advertisement 5.2

Same name and namespace in other branches
  1. 6.3 cache/file/ad_cache_file.inc \ad_cache_file_close()
  2. 6.2 cache/file/ad_cache_file.inc \ad_cache_file_close()
  3. 7 cache/file/ad_cache_file.inc \ad_cache_file_close()

Close the cache file and write updated cache to disk.

File

cache/file/ad_cache_file.inc, line 190
A plug in for the ad.module, providing a file cache mechanism for improved performance when displaying ads.

Code

function ad_cache_file_close() {
  static $written = FALSE;

  // prevent accidentally writing one version of the cache to a different file
  if ($written) {
    _debug_echo('File cache: unable to write cache file, already closed.');
    return 1;
  }
  $written = TRUE;
  $cache_file = ad_cache_file_get_lock();
  _debug_echo("File cache: writing cache back to file '{$cache_file}'.");

  // gather data to determine if we should flush the cache
  $cache = ad_cache_file_cache();
  $last_sync = $cache['last_sync'];
  $lifetime = $cache['lifetime'];

  // serialize the array to write it to disk
  $cache = serialize($cache);

  // write updated cache back to file and release the lock
  if (rewind(adserve_variable('fd')) == TRUE) {
    if (ftruncate(adserve_variable('fd'), 0) == TRUE) {
      $bytes = fwrite(adserve_variable('fd'), $cache, strlen($cache));
      if ($bytes) {
        _debug_echo("File cache: wrote {$bytes} bytes to '{$cache_file}'.");
      }
      else {
        _debug_echo("File cache: failed to write to '{$cache_file}'.");
      }
      flock(adserve_variable('fd'), LOCK_UN);
      if (fclose(adserve_variable('fd')) == TRUE) {
        _debug_echo("File cache: successfully closed '{$cache_file}'.");
      }
      else {
        _debug_echo("File cache: failed to close '{$cache_file}'.");
      }
    }
    else {
      _debug_echo("File cache: failed to ftruncate file '{$cache_file}'.");
    }
  }
  else {
    _debug_echo("File cache: failed to rewind file '{$cache_file}'.");
  }
  adserve_variable('fd', '');

  // every $lifetime seconds we flush the cache to the database
  $time = time();
  if ($last_sync < time() - $lifetime) {
    ad_cache_file_rebuild();
  }
}