You are here

function heartbeat_cron in Heartbeat 6.4

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

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

File

./heartbeat.module, line 453

Code

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

  // 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,
    );
    $unlimited_templates = variable_get('heartbeat_activity_templates_unlimited', array());

    // Calculate the latest activity for each user.
    $arguments = array_merge($unlimited_templates, array(
      $keep_latest_number,
    ));
    $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      AND t1.message_id NOT IN (" . db_placeholders($unlimited_templates) . ")\n      GROUP BY t1.uid, t1.uaid HAVING COUNT(t2.uid) <= %d\n      ORDER BY t1.uid, t1.uaid, t1.timestamp DESC", $arguments);
    while ($row = db_fetch_object($result)) {
      $keep_uaids[$row->uaid] = $row->uaid;
    }
    $arguments = array_merge(array(
      $expire,
    ), $keep_uaids);
    $delete_result = db_query("SELECT uaid\n      FROM {heartbeat_activity}\n      WHERE\n        timestamp < %d\n      AND\n        uaid NOT IN (" . db_placeholders($keep_uaids) . ") ", $arguments);
    while ($row = db_fetch_object($delete_result)) {
      _heartbeat_activity_delete($row->uaid);
    }
  }

  // Remove activity for nodes that are removed.
  $result = db_query("SELECT uaid, nid, nid_target FROM {heartbeat_activity} WHERE nid > 0");
  while ($row = db_fetch_object($result)) {
    if (!($exists = db_result(db_query("SELECT nid FROM {node} WHERE nid = %d ", $row->nid)))) {
      _heartbeat_activity_delete($row->uaid);
    }
  }
}