You are here

function flickrcachewarmer_cron in Flickr 7

Implements hook_cron().

Called every time the Drupal cron runs.

File

cachewarmer/flickrcachewarmer.module, line 26
The Flickr Cache Warmer module.

Code

function flickrcachewarmer_cron() {
  $content_types = array_filter(variable_get('flickrcachewarmer_nodetypes', array()));

  // If no content types are selected in the settings, use all.
  if (empty($content_types)) {
    $names = node_type_get_names();
    $content_types = array_flip(array_map('check_plain', $names));
  }

  // Returns an array of nid's for selected content types.
  $nids = db_select('node', 'n')
    ->fields('n', array(
    'nid',
  ))
    ->fields('n', array(
    'type',
  ))
    ->condition('n.type', array_filter($content_types), 'IN')
    ->execute()
    ->fetchCol();

  // If the cache lifetime is substantially greater than the set cron
  // interval, cut the above array in chunks to batch process them.
  // Note it should currently not be used as we recommend to leave the cache
  // lifetime set to 'none'.
  $batchnumber = variable_get('cache_lifetime', 0) > 2 * variable_get('cron_safe_threshold', DRUPAL_CRON_DEFAULT_THRESHOLD) ? ceil(variable_get('cache_lifetime', 0) / variable_get('cron_safe_threshold', DRUPAL_CRON_DEFAULT_THRESHOLD)) : 1;

  // Interrupt if no nodes are found.
  if (count($nids) == 0) {
    return;
  }
  $batchnumber = $batchnumber > count($nids) ? count($nids) : $batchnumber;
  $batchsize = ceil(count($nids) / $batchnumber);
  $nids = array_chunk($nids, $batchsize, FALSE);

  // If the batch 'ID' is an undefined index (offset), reset it to zero.
  $batch = variable_get('flickrcachewarmer_batch', 0) > $batchnumber - 1 ? 0 : variable_get('flickrcachewarmer_batch', 0);

  // Go ahead to warm the cache for a batch of nodes.
  flickrcachewarmer_run($nids[$batch]);

  // Next time we should do the next batch.
  variable_set('flickrcachewarmer_batch', $batch + 1);
  $nidslist = implode(', ', $nids[$batch]);
  $batchplusone = $batch + 1;
  $nextcw = format_interval(variable_get('cron_safe_threshold', DRUPAL_CRON_DEFAULT_THRESHOLD), 2);
  $ctlist = implode(', ', $content_types);
  $message = t("Cache of nodes successfully rebuilt for the selected content types. Node ID's: %nidslist. This was batch # %batchplusone out of a total of %batchnumber", array(
    '%nidslist' => $nidslist,
    '%batchplusone' => $batchplusone,
    '%batchnumber' => $batchnumber,
  )) . '.<br />' . t('The next cache warming will take place in %nextcw (every cron run) on the following content types: %ctlist.', array(
    '%nextcw' => $nextcw,
    '%ctlist' => $ctlist,
  ));
  drupal_set_message($message, 'status', FALSE);
  watchdog('flickrcachewarmer', $message);
}