<?php
// $Id: simplenews_action.module,v 1.1.2.6 2009/01/21 08:21:08 sutharsan Exp $

/**
 * @file simplenews_action.inc
 * Provide actions for simplenews.
 *
 * @ingroup simplenews
 */

/*
* Implementation of hook_action_info()
*/
function simplenews_action_info() {
  return array(
    'simplenews_send_newsletter_action' => array(
      'description' => t('Send single simplenews newsletter'),
      'type' => 'simplenews',
      'configurable' => TRUE,
      'hooks' => array(
        'cron' => array('run'),
        'user' => array('insert'),
        'simplenews' => array('subscribe'),
      ),
    ),
    'simplenews_cron_action' => array(
      'description' => t('Send pending simplenews newsletters'),
      'type' => 'simplenews',
      'configurable' => FALSE,
      'hooks' => array(
        'cron' => array('run'),
      ),
    ),
    'simplenews_subscribe_user_action' => array(
      'type' => 'simplenews',
      'description' => t('Subscribe the user to a newsletter'),
      'configurable' => TRUE,
      'hooks' => array(
        'user' => array('insert', 'update'),
      ),
    ),
    'simplenews_unsubscribe_user_action' => array(
      'type' => 'simplenews',
      'description' => t('Unsubscribe the user from a newsletter'),
      'configurable' => TRUE,
      'hooks' => array(
        'user' => array('update', 'delete'),
      ),
    ),
  );
}

/**
 * A configurable Drupal action. Send a simplenews newsletter.
 *   hook = cron: Send a newsletter to all subscribers.
 *   hook = user: Send a newsletter to the user who triggered the action.
 *
 *   Available context:
 *    $context['nid']     newsletter id
 *    $context['title']   newsletter title
 *    $context['resend']  allow resending of a previously send newsletter
 *
 *   @see simplenews_send_newsletter_action_form()
 *   @see simplenews_send_newsletter_action_submit()
 */
function simplenews_send_newsletter_action(&$object, $context = array()) {
  if ($context['hook'] == 'cron' || $context['hook'] == 'user' || $context['hook'] == 'simplenews') {

    // Determine newsletter receipients
    $accounts = array();
    if ($context['hook'] == 'user' || $context['hook'] == 'simplenews') {
      $accounts[] = $context['account'];
    }

    // Get send status of this newsletter. The global newsletter send status is used not the send status of individual emails.
    $s_status = db_result(db_query("SELECT s_status FROM {simplenews_newsletters} WHERE nid = %d", $context['nid']));

    // Send newsletter if resend is allowed OR newsletter is not yet send.
    if ($context['resend'] OR $s_status == SIMPLENEWS_STATUS_SEND_NOT) {
      if ($context['hook'] == 'cron') {
        // Set newsletter send status to pending if send by cron.
        db_query("UPDATE {simplenews_newsletters} SET s_status = %d WHERE nid = %d", SIMPLENEWS_STATUS_SEND_PENDING, $context['nid']);
      }
      simplenews_send_node($context['nid'], $accounts);
    }
    watchdog('action', 'Simplenews newsletter %title send.', array('%title' => $context['title']));
  }
}

/**
 * Implementation of a configurable Drupal action. Send newsletter
 */
function simplenews_send_newsletter_action_form($context) {
//TODO improve usability by adding a pre-selection of newsletters before the newsletter issue selection
//     Requires AHAH function to select newsletters issues based on selected newsletter
//
//  if (!isset($context['newsletter'])) {
//    $context['newsletter'] = array();
//  }
  if (!isset($context['newsletter_issue'])) {
    $context['newsletter_issue'] = array();
  }
  if (!isset($context['resend'])) {
    $context['resend'] = FALSE;
  }
 
  $tree = taxonomy_get_tree(variable_get('simplenews_vid', ''));
  $terms = array();
  foreach ($tree as $newsletter) {
    $terms[$newsletter->tid] = check_plain($newsletter->name);
  }
//  $form['newsletter'] = array(
//    '#title' => t('Newsletter'),
//    '#type' => 'select',
//    '#options' => $terms,
//    '#default_value' => $context['newsletter'],
//    '#description' => t('The newsletter series'),
//  );
  $result = taxonomy_select_nodes(array_keys($terms));
  $nids = array();
  while ($node = db_fetch_object($result)) {
    $nids[$node->nid] = check_plain($node->title);
  }
  $form['newsletter_issue'] = array(
    '#title' => t('Newsletter issue'),
    '#type' => 'select',
    '#options' => $nids,
    '#default_value' => $context['newsletter_issue'],
    '#description' => t('The newsletter issue to send'),
  );
  $form['resend'] = array(
    '#title' => t('Allow to resend newsletter'),
    '#type' => 'checkbox',
    '#default_value' => $context['resend'],
    '#description' => t('When checked a newsletter will be send even when already send before. The newsletter send status is checked, not the status of individual email addresses. Use this for repeated (e.g. monthly) newsletters.'),
  );
 
  return $form;
}

/**
 * Validate simplenews_send_newsletter_action form submissions.
 */
function simplenews_send_newsletter_action_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the send newsletter form.
  if (empty($form_values['newsletter_issue'])) {
    form_set_error('newsletter_issue', t('Please select a newsletter issue.'));
  }
}

/**
 * Process simplenews_send_newsletter_action form submissions.
 */
function simplenews_send_newsletter_action_submit($form, $form_state) {
  $form_values = $form_state['values'];

  $params = array(
    'nid' => $form_values['newsletter_issue'],
    'title' => $form['newsletter_issue']['#options'][$form_values['newsletter_issue']],
    'resend' => $form_values['resend'],
  );
  return $params;
}

/**
 * Implementation of a Drupal action. Send pending simplenews newsletters.
 */
function simplenews_cron_action(&$object, $context = array()) {
  simplenews_cron();
  watchdog('action', 'Simplenews cron executed.');
}

/**
 * A configurable Drupal action. Subscribe the user to a newsletter
 *   hook = user: Subscribe this user to selected newsletter
 *
 *   Available context:
 *    $context['tid']     newsletter tid
 *    $context['name']   newsletter name
 *
 *   @see simplenews_subscribe_user_action_form()
 *   @see simplenews_subscribe_user_action_submit()
 */
function simplenews_subscribe_user_action(&$object, $context = array()) {
  if ($context['hook'] == 'user') {
    if (isset($context['tid'])) {
      // This action is only called in the context of user. User data is in $context.
      $account = $context['account'];
      simplenews_subscribe_user($account->mail, $context['tid'], FALSE);
      drupal_set_message(t('You have been subscribed to newsletter %newsletter.', array('%newsletter' => $context['name'])));
      watchdog('action', 'User %name subscribed to newsletter %newsletter.', array('%name' => $account->name, '%newsletter' => $context['name']));
    }
  }
}

/**
 * Implementation of a configurable Drupal action.
 */
function simplenews_subscribe_user_action_form($context) {
  if (!isset($context['newsletter'])) {
    $context['newsletter'] = array();
  }
 
  $tree = taxonomy_get_tree(variable_get('simplenews_vid', ''));
  $terms = array();
  foreach ($tree as $newsletter) {
    $terms[$newsletter->tid] = check_plain($newsletter->name);
  }
  $form['newsletter'] = array(
    '#title' => t('Newsletter'),
    '#type' => 'select',
    '#options' => $terms,
    '#description' => t('The newsletter series the user will be subscribed to.'),
  );
  return $form;
}

/**
 * Process simplenews_subscribe_user_action form submissions.
 */
function simplenews_subscribe_user_action_submit($form, $form_state) {
  $form_values = $form_state['values'];

  $params = array(
    'tid' => $form_values['newsletter'],
    'name' => $form['newsletter']['#options'][$form_values['newsletter']],
  );
  return $params;
}

/**
 * A configurable Drupal action. Unsubscribe the user from a newsletter
 *   hook = user: Unsubscribe this user from selected newsletter
 *
 *   Available context:
 *    $context['tid']     newsletter tid
 *    $context['name']   newsletter name
 *
 *   @see simplenews_unsubscribe_user_action_form()
 *   @see simplenews_unsubscribe_user_action_submit()
 */
function simplenews_unsubscribe_user_action(&$object, $context = array()) {
  if ($context['hook'] == 'user') {
    if (isset($context['tid'])) {
      // This action is only called in the context of user. User data is in $context.
      $account = $context['account'];
      //TODO: Unsubscribing should be done by simplenews_unsubscribe_user but simplenews_get_user_subscription fails because the user is already removed
      if ($result = db_fetch_object(db_query("SELECT snid FROM {simplenews_subscriptions} WHERE mail = '%s'", $account->mail))) {
        db_query('DELETE FROM {simplenews_snid_tid} WHERE snid = %d AND tid = %d', $result->snid, $context['tid']);

        // Clean up simplenews_subscriptions if no more newsletter subscriptions.
        if (!db_result(db_query("SELECT COUNT(*) FROM {simplenews_snid_tid} t WHERE t.snid = %d", $result->snid))) {
          db_query('DELETE FROM {simplenews_subscriptions} WHERE snid = %d', $result->snid);
        }
      }
      drupal_set_message(t('You have been removed from the %newsletter subscription list.', array('%newsletter' => check_plain($context['name']))));
      watchdog('action', 'User %name unsubscribed from newsletter %newsletter.', array('%name' => check_plain($account->name), '%newsletter' => check_plain($context['name'])));
    }
  }
}

/**
 * Implementation of a configurable Drupal action.
 */
function simplenews_unsubscribe_user_action_form($context) {
  if (!isset($context['newsletter'])) {
    $context['newsletter'] = array();
  }
 
  $tree = taxonomy_get_tree(variable_get('simplenews_vid', ''));
  $terms = array();
  foreach ($tree as $newsletter) {
    $terms[$newsletter->tid] = check_plain($newsletter->name);
  }
  $form['newsletter'] = array(
    '#title' => t('Newsletter'),
    '#type' => 'select',
    '#options' => $terms,
    '#description' => t('The newsletter series the user will be unsubscribed from.'),
  );
  return $form;
}

/**
 * Process simplenews_unsubscribe_user_action form submissions.
 */
function simplenews_unsubscribe_user_action_submit($form, $form_state) {
  $form_values = $form_state['values'];

  $params = array(
    'tid' => $form_values['newsletter'],
    'name' => $form['newsletter']['#options'][$form_values['newsletter']],
  );
  return $params;
}

/**
 * Implementation of hook_hook_info().
 */
function simplenews_hook_info() {
  return array(
    'simplenews' => array(
      'simplenews' => array(
        'subscribe' => array(
          'runs when' => t('After a user has been subscribed'),
        ),
        'unsubscribe' => array(
          'runs when' => t('After a user has been unsubscribed'),
        ),
      ),
    ),
  );
}