You are here

function simpleads_cron in SimpleAds 7

Same name and namespace in other branches
  1. 7.2 includes/cron.inc \simpleads_cron()

Implements hook_cron().

File

./simpleads.module, line 680

Code

function simpleads_cron() {
  $ads = db_select('node', 'n')
    ->fields('n')
    ->condition('n.type', 'simpleads')
    ->execute();
  foreach ($ads as $ad) {
    $node = node_load($ad->nid);
    _simpleads_activate_deactive_ad($node);
  }
  $timestamp = variable_get('simpleads_last_aggregation_time', 0);
  if (date('m-d-Y', $timestamp) != date('m-d-Y', REQUEST_TIME)) {
    $result = db_query("SELECT\n        FROM_UNIXTIME(s.timestamp, '%Y%m%d') AS date,\n        s.nid, COUNT(*) AS all_count,\n        COUNT(DISTINCT s.ip_address) AS unique_count\n      FROM {simpleads_impressions} s\n      WHERE FROM_UNIXTIME(s.timestamp, '%Y%m%d') != FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y%m%d')\n      GROUP BY date, s.nid");
    $nids = array();
    foreach ($result as $row) {
      db_merge('simpleads_stats')
        ->key(array(
        'nid' => $row->nid,
        'date' => $row->date,
      ))
        ->fields(array(
        'nid' => $row->nid,
        'date' => $row->date,
        'clicks' => 0,
        'clicks_unique' => 0,
        'impressions' => $row->all_count,
        'impressions_unique' => $row->unique_count,
      ))
        ->execute();
      if (!in_array($row->nid, $nids)) {
        $nids[] = $row->nid;
      }
    }
    $result = db_query("SELECT\n        FROM_UNIXTIME(s.timestamp, '%Y%m%d') as date,\n        s.nid,\n        COUNT(*) as all_count,\n        COUNT(DISTINCT s.ip_address) as unique_count\n      FROM {simpleads_clicks} s\n      WHERE FROM_UNIXTIME(s.timestamp, '%Y%m%d') != FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y%m%d')\n      GROUP BY date, s.nid");
    foreach ($result as $row) {
      db_update('simpleads_stats')
        ->fields(array(
        'clicks' => $row->all_count,
        'clicks_unique' => $row->unique_count,
      ))
        ->condition('date', $row->date)
        ->condition('nid', $row->nid)
        ->execute();
      if (!in_array($row->nid, $nids)) {
        $nids[] = $row->nid;
      }
    }
    if (count($nids)) {
      db_query("DELETE FROM {simpleads_impressions}\n        WHERE nid IN (" . join(', ', $nids) . ")\n          AND FROM_UNIXTIME(timestamp, '%Y%m%d') != FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y%m%d')");
      db_query("DELETE FROM {simpleads_clicks}\n        WHERE nid IN (" . join(', ', $nids) . ")\n          AND FROM_UNIXTIME(timestamp, '%Y%m%d') != FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y%m%d')");
    }
    variable_set('simpleads_last_aggregation_time', REQUEST_TIME);
  }
}