You are here

function download_count_cron in Download Count 8

Same name and namespace in other branches
  1. 7.3 download_count.module \download_count_cron()

Implements hook_cron().

Daily file download counts are cached for convenience.

File

./download_count.module, line 108
Tracks file downloads for files stored in the drupal files table.

Code

function download_count_cron() {
  $count = 0;
  $last_cron = Drupal::config('download_count.settings')
    ->get('download_count_last_cron');
  $connection = Database::getConnection();
  $query = $connection
    ->select('download_count', 'd');
  $query
    ->addExpression('UNIX_TIMESTAMP(DATE(FROM_UNIXTIME(timestamp)))', 'date');
  $query
    ->addExpression('COUNT(dcid)', 'count');
  $query
    ->fields('d', [
    'fid',
    'type',
    'id',
  ]);
  $query
    ->condition('d.timestamp', $last_cron, '>');
  $query
    ->groupBy('d.type');
  $query
    ->groupBy('d.id');
  $query
    ->groupBy('d.fid');
  $query
    ->groupBy('date');
  $result = $query
    ->execute()
    ->fetchAll();
  $queue = Drupal::queue('download_count');
  foreach ($result as $record) {
    $queue
      ->createItem($record);
    $count++;
  }
  if ($count > 0) {
    Drupal::logger('download_count')
      ->notice('Download count queued {$count} new entries for caching.');
  }
  Drupal::service('config.factory')
    ->getEditable('download_count.settings')
    ->set('download_count_last_cron', REQUEST_TIME)
    ->save();
}