You are here

function birthdays_cron in Birthdays 7

Same name and namespace in other branches
  1. 5 birthdays.module \birthdays_cron()
  2. 6 birthdays.module \birthdays_cron()

Implements hook_cron().

File

./birthdays.module, line 1053
The Birthdays module allows users to add their birthday to their profile. It lists birthdays on a seperate page and in different blocks. Users can receive an email on their birthday automatically, and the administrator can receive daily reminders of…

Code

function birthdays_cron() {

  // The cronjob run at most once a day.
  $day = 24 * 60 * 60;
  $last_cron = variable_get('birthdays_last_cron', REQUEST_TIME - $day);
  if ($last_cron > REQUEST_TIME - $day) {
    return;
  }
  $instances = _birthdays_field_instances();

  // Prepare an admin mail.
  $admin_mail = array();
  foreach ($instances as $instance) {

    // Query for birthdays.
    $birthdays = array();
    switch ($instance['settings']['admin_mail']) {
      case BIRTHDAYS_ADMIN_MAIL_DAILY:
        $birthdays = _birthdays_get(FALSE, $instance, date('d', REQUEST_TIME), date('m', REQUEST_TIME), date('Y', REQUEST_TIME));
        $period = t('Today');
        break;
      case BIRTHDAYS_ADMIN_MAIL_WEEKLY:
        if (variable_get('date_first_day', 0) == date('w', REQUEST_TIME)) {
          for ($i = 0; $i++; $i < 7) {
            $qtime = REQUEST_TIME + $i * $day;
            $birthdays += _birthdays_get(FALSE, $instance, date('d', $qtime), date('m', $qtime), date('Y', $qtime));
          }
          $period = t('This week');
        }
        break;
      case BIRTHDAYS_ADMIN_MAIL_MONTHLY:
        if (date('d', REQUEST_TIME) == 1) {
          $birthdays = _birthdays_get(FALSE, $instance, 0, date('m', REQUEST_TIME), date('Y', REQUEST_TIME));
          $period = t('This month');
        }
        break;
    }

    // Add an entry to the mail.
    $entities = entity_load($instance['entity_type'], $birthdays);
    if (!empty($entities)) {
      $admin_mail[_birthdays_instance_description($instance) . ' (' . $period . ')'] = array(
        'instance' => $instance,
        'entities' => $entities,
      );
    }
  }

  // Send the admin mail.
  if (!empty($admin_mail)) {
    $to = variable_get('site_mail', ini_get('sendmail_from'));
    drupal_mail('birthdays', 'admin_mail', $to, language_default(), $admin_mail);
  }

  // Iterate over all the days that passed since the last cron run.
  while ($last_cron <= REQUEST_TIME - $day) {
    $last_cron += $day;
    foreach ($instances as $instance) {

      // Find the birthdays.
      $birthdays = _birthdays_get(TRUE, $instance, date('d', $last_cron), date('m', $last_cron), date('Y', $last_cron));
      $entities = entity_load($instance['entity_type'], $birthdays);

      // Invoke hook_birthdays().
      foreach ($entities as $entity) {
        module_invoke_all('birthdays', $entity, $instance);
      }
    }
  }
  variable_set('birthdays_last_cron', $last_cron);
}