<?php
// $Id: token_actions.module,v 1.4.2.9 2010/03/25 17:49:43 davereid Exp $

/**
 * @file
 * The Token Actions module.
 *
 * The Token Actions module provides ways to use tokens inside of actions.
 * Currently it provides the ability to show users a message, send a token-ized
 * mail, or redirect a user to a tokenized URL.
 *
 * @ingroup token
 */

/**
 * Implementation of hook_action_info().
 */
function token_actions_action_info() {
  return array(
    'token_actions_message_action' => array(
      'type' => 'system',
      'description' => t('Display a tokenized message to the user'),
      'configurable' => TRUE,
      'hooks' => array(
        'nodeapi' => array('view', 'insert', 'update', 'delete'),
        'comment' => array('view', 'insert', 'update', 'delete'),
        'user' => array('view', 'insert', 'update', 'delete', 'login'),
        'taxonomy' => array('insert', 'update', 'delete'),
      ),
    ),
    'token_actions_send_email_action' => array(
      'description' => t('Send tokenized e-mail'),
      'type' => 'system',
      'configurable' => TRUE,
      'hooks' => array(
        'nodeapi' => array('view', 'insert', 'update', 'delete'),
        'comment' => array('view', 'insert', 'update', 'delete'),
        'user' => array('view', 'insert', 'update', 'delete', 'login'),
        'taxonomy' => array('insert', 'update', 'delete'),
      )
    ),
    'token_actions_goto_action' => array(
      'description' => t('Redirect to a tokenized URL'),
      'type' => 'system',
      'configurable' => TRUE,
      'hooks' => array(
        'nodeapi' => array('view', 'insert', 'update', 'delete'),
        'comment' => array('view', 'insert', 'update', 'delete'),
        'user' => array('view', 'insert', 'update', 'delete', 'login'),
      )
    )
  );
}

/**
 * Return a form definition so the Send email action can be configured.
 *
 * @param $context
 *   Default values (if we are editing an existing action instance).
 * @return
 *   Form definition.
 */
function token_actions_send_email_action_form($context) {
  // Set default values for form.
  if (!isset($context['recipient'])) {
    $context['recipient'] = '';
  }
  if (!isset($context['subject'])) {
    $context['subject'] = '';
  }
  if (!isset($context['message'])) {
    $context['message'] = '';
  }

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#default_value' => $context['recipient'],
    '#size' => '20',
    '#maxlength' => '254',
    '#description' => t('The email address to which the message should be sent.'),
  );
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => $context['subject'],
    '#size' => '20',
    '#maxlength' => '254',
    '#description' => t('The subject of the message.'),
  );
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#default_value' => $context['message'],
    '#cols' => '80',
    '#rows' => '20',
    '#description' => t('The message that should be sent.'),
  );

  $form['help'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Placeholder tokens'),
    '#description' => t("The following placeholder tokens can be used in to generate the URL path. Some tokens may not be available, depending on the context in which the action is triggered."),
  );

  $form['help']['tokens'] = array(
    '#value' => theme('token_help', 'all'),
  );

  return $form;
}

function token_actions_send_email_action_submit($form, &$form_state) {
  // Process the HTML form to store configuration. The keyed array that
  // we return will be serialized to the database.
  $params = array(
    'recipient' => $form_state['values']['recipient'],
    'subject'   => $form_state['values']['subject'],
    'message'   => $form_state['values']['message'],
  );
  return $params;
}

/**
 * Implementation of a configurable Drupal action.
 * Sends an email.
 */
function token_actions_send_email_action($object, $context) {
  token_normalize_context($context);
  $params['from'] = variable_get('site_mail', ini_get('sendmail_from'));
  $recipient = token_replace_multiple($context['recipient'], $context);
  $params['subject'] = str_replace(array("\r", "\n"), '', token_replace_multiple($context['subject'], $context));
  $params['body'] = token_replace_multiple($context['message'], $context);

  if (drupal_mail('token_actions', 'action_send_email', $recipient, language_default(), $params)) {
    watchdog('action', 'Sent email to %recipient', array('%recipient' => $recipient));
  }
  else {
    watchdog('error', 'Unable to send email to %recipient', array('%recipient' => $recipient));
  }
}

function token_actions_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];
}

function token_actions_message_action_form($context) {
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#default_value' => isset($context['message']) ? $context['message'] : '',
    '#required' => TRUE,
    '#rows' => '8',
    '#description' => t('The message to be displayed to the current user.'),
  );

  $form['help'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Placeholder tokens'),
    '#description' => t("The following placeholder tokens can be used in the custom message text. Some tokens may not be available, depending on the context in which the action is triggered."),
  );

  $form['help']['tokens'] = array(
    '#value' => theme('token_help', 'all'),
  );

  return $form;
}

function token_actions_message_action_submit($form, &$form_state) {
  return array('message' => $form_state['values']['message']);
}

/**
 * Implementation of a configurable Drupal action.
 * Sends a configurable message to the current user's screen.
 */
function token_actions_message_action(&$object, $context = array()) {
  token_normalize_context($context);
  $context['message'] = token_replace_multiple($context['message'], $context);
  drupal_set_message($context['message']);
}

/**
 * Implementation of a configurable Drupal action.
 * Redirect user to a URL.
 */
function token_actions_goto_action_form($context) {
  $form['url'] = array(
    '#type' => 'textfield',
    '#title' => t('URL'),
    '#description' => t('The URL to which the user should be redirected. This can be an internal URL like node/1234 or an external URL like http://drupal.org.'),
    '#default_value' => isset($context['url']) ? $context['url'] : '',
    '#required' => TRUE,
  );
  $form['help'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Placeholder tokens'),
    '#description' => t("The following placeholder tokens can be used in the URL path. Some tokens may not be available, depending on the context in which the action is triggered."),
  );

  $form['help']['tokens'] = array(
    '#value' => theme('token_help', 'all'),
  );

  return $form;
}

function token_actions_goto_action_submit($form, &$form_state) {
  return array(
    'url' => $form_state['values']['url']
  );
}

function token_actions_goto_action($object, $context) {
  token_normalize_context($context);
  drupal_goto(token_replace_multiple($context['url'], $context));
}

/**
 * Load, into the context, the common objects user and node so we can use their
 * tokens. Sometimes Trigger, or Actions, load them for us, but sometimes not.
 */
function token_normalize_context(&$context) {
  $context['global'] = NULL;
  if (empty($context['user']) && !empty($context['node'])) {
    $context['user'] = user_load(array('uid' => $context['node']->uid));
  }
  if (empty($context['node']) && !empty($context['comment']) && !empty($context['comment']->nid)) {
    $context['node'] = node_load($context['comment']->nid);
  }
}
