You are here

function heartbeat_cron in Heartbeat 7

Same name and namespace in other branches
  1. 8 heartbeat.module \heartbeat_cron()
  2. 6.4 heartbeat.module \heartbeat_cron()

Implements hook_cron(). Delete too old message if this option is set and logs where the node does not exist anymore.

File

./heartbeat.module, line 75
Module file for heartbeat activity. Basic hook implementations and helper functions will be found here.

Code

function heartbeat_cron() {
  $uaids = array();
  $cron_delete_time = variable_get('heartbeat_activity_log_cron_delete', 2678400);
  $keep_latest_number = variable_get('heartbeat_activity_records_per_user', 10);
  $microseconds = microtime();

  // Delete activity older than the expiration date, while
  // keeping the latest X for each user.
  if ($cron_delete_time) {
    $expire = $_SERVER['REQUEST_TIME'] - $cron_delete_time;

    // Activity Ids that can not be removed (latest activity per user)
    $keep_uaids = array(
      0 => 0,
    );

    // Calculate the latest activity for each user.
    $result = db_query("SELECT\n        t1.uid,\n        t1.uaid as 'uaid',\n        COUNT(*) as 'rows_per_user',\n        t1.timestamp as 'real_date',\n        MIN(t2.timestamp) as 'oldest_date',\n        count(t2.uid) AS 'count'\n      FROM {heartbeat_activity} AS t1\n      INNER JOIN {heartbeat_activity} AS t2 ON t1.uid = t2.uid AND t2.timestamp >= t1.timestamp\n      WHERE (t1.timestamp, t1.uaid) < (t2.timestamp, t2.uaid)\n      GROUP BY t1.uid, t1.uaid HAVING COUNT(t2.uid) <= :latest\n      ORDER BY t1.uid, t1.uaid, t1.timestamp DESC", array(
      ':latest' => $keep_latest_number,
    ));

    //    $users = db_query("SELECT uid FROM {users} WHERE status = 1");
    //    $query = array();
    //    $args = array();
    //    foreach ($users as $key => $account) {
    //      $query[] = " ( SELECT uid, uaid FROM {heartbeat_activity} WHERE uid = :uid_$key ORDER BY uaid DESC LIMIT 0, :latest ) ";
    //      $args[':uid_' . $key] = $account->uid;
    //      $args[':latest'] = (int) $keep_latest_number;
    //    }
    //
    //    $result = db_query(implode("UNION", $query), $args);
    foreach ($result as $row) {
      $keep_uaids[$row->uaid] = $row->uaid;
    }

    //$arguments = array_merge(array($expire), $keep_uaids);
    $delete_result = db_query("SELECT uaid FROM {heartbeat_activity}\n      WHERE timestamp < :expire AND uaid NOT IN (:uaids) ", array(
      ':expire' => $expire,
      ':uaids' => $keep_uaids,
    ));
    foreach ($delete_result as $row) {
      $uaids[] = $row->uaid;
    }
  }
  if (!empty($uaids)) {
    heartbeat_activity_delete($uaids);
  }
  $microseconds_final = microtime();
  watchdog('cron', 'Cron finished in %secs seconds', array(
    '%secs' => $microseconds_final - $microseconds,
  ));
}