You are here

function ad_notify_cron in Advertisement 5.2

Same name and namespace in other branches
  1. 5 notify/ad_notify.module \ad_notify_cron()
  2. 6 notify/ad_notify.module \ad_notify_cron()

Drupal _cron() hook. For performance reasons, all notifications are actually sent via this cron hook.

File

notify/ad_notify.module, line 84
Receive email notifications regarding ads.

Code

function ad_notify_cron() {

  // Walk through all configured notifications and determine if any need to be
  // emailed.
  $result = db_query('SELECT n.notid, o.aid, n.oid, n.event, n.queued, n.delay, n.sent, n.expire, n.address, n.subject, n.body FROM {ad_notify} n INNER JOIN {ad_owners} o ON n.oid = o.oid WHERE n.status = %d', AD_NOTIFY_ENABLED);
  while ($notification = db_fetch_object($result)) {
    $send = FALSE;

    // Handle special case 'regular' notification that is simply a time-based
    // status email.
    if ($notification->event == 'regular') {
      if (time() - $notification->delay >= $notification->sent) {
        $send = TRUE;
        $count = 1;
      }
    }
    else {
      if (($event = trim($notification->event, '-')) != $notification->event) {

        // Event was prefixed by a -, so time is negative.  We can't pull a
        // future event out of the statistics table, so we let the module that
        // defined this event tell us whether or not it's happened.
        $event_count = module_invoke_all('adnotifyapi', $notification->event, $notification);
        if (isset($event_count[$notification->event])) {
          $send = TRUE;
        }
      }
      else {
        $count = db_result(db_query("SELECT COUNT(aid) AS count FROM {ad_statistics} WHERE aid = %d AND date > %d AND action = '%s'", $notification->aid, date('YmdH', $notification->sent), $notification->event));
        if ($count) {

          // See if the notification has been queued long enough to be sent.
          if (!$notification->delay || $notification->queued && time() > $notification->queued + $notification->delay) {
            $send = TRUE;
          }
          else {
            if (!$notification->queued) {

              // Queue up the notification to send it at a later time.
              db_query('UPDATE {ad_notify} SET queued = %d WHERE notid = %d', time(), $notification->notid);
            }
          }
        }
      }
    }
    if ($send) {
      ad_notify_send_mail($notification, $count);
      if ($notification->expire) {

        // Update the sent timestamp and counter, and auto-expire the
        // notification so it is not sent again.
        db_query('UPDATE {ad_notify} SET queued = 0, sent = %d, counter = counter + 1, status = %d WHERE notid = %d', time(), AD_NOTIFY_DISABLED, $notification->notid);
      }
      else {

        // Simply update the sent timestamp and counter.
        db_query('UPDATE {ad_notify} SET queued = 0, sent = %d, counter = counter + 1 WHERE notid = %d', time(), $notification->notid);
      }
    }
  }
}