You are here

function newsletter_cron in Newsletter 7

Same name and namespace in other branches
  1. 7.2 newsletter.module \newsletter_cron()

Implements hook_cron().

File

./newsletter.module, line 328
Defines menu items for newsletter administration, permissions and basic drupal hooks.

Code

function newsletter_cron() {
  $status = array();
  $nlids_sent = array();

  // Custom Newsletters
  $custom_queues = variable_get('newsletter_custom_for_next_cron', array());
  if (!empty($custom_queues)) {
    foreach ($custom_queues as $num => $custom_queue) {
      $data = newsletter_create($custom_queue['subscribers'], $custom_queue['ntid'], $custom_queue['nnid'])
        ->send();
      $status = array_merge($status, $data['status']);
      $subscribers_left = $data['subscribers_left'];
      if (!empty($subscribers_left)) {
        $custom_queues[$num]['subscribers'] = $subscribers_left;
      }
      else {
        unset($custom_queues[$num]);
      }
    }
    variable_set('newsletter_custom_for_next_cron', $custom_queues);
  }

  // Nesletters with remaining subscribers or Manual queued
  $remaining = variable_get('newsletter_for_next_cron', array());
  if (!empty($remaining)) {
    foreach ($remaining as $nlid => $data) {
      if ($data === TRUE) {

        // There is a new Manual newsletter in the queue
        $remaining[$nlid] = array();
        variable_set('newsletter_for_next_cron', $remaining);
        $result = newsletter_create($nlid)
          ->send();
        $status = array_merge($status, $result);
        $nlids_sent[] = $nlid;
      }
      elseif (!empty($data)) {

        // There are remaining subscribers in one already sent newsletter
        $result = newsletter_create($nlid)
          ->send();
        $status = array_merge($status, $result);
        $nlids_sent[] = $nlid;
      }
    }
  }

  // Automated Newsletter lists that didn't have remaining for this cron run
  $cron_lists = db_query("SELECT nlid FROM {newsletter_list}\n    WHERE (send_again = CURDATE() OR send_again IS NULL)\n    AND (send_rate = 'Daily' OR send_rate = 'Weekly' OR send_rate = 'Monthly')")
    ->fetchAll();
  if (is_array($cron_lists)) {
    foreach ($cron_lists as $cron_list) {
      if (!in_array($cron_list->nlid, $nlids_sent, TRUE)) {
        $result = newsletter_create($cron_list->nlid)
          ->send();
        $status = array_merge($status, $result);
      }
    }
  }
  newsletter_feedback($status);
}