action.module

This is the Actions module for executing stored actions.

File

drupal/core/modules/action/action.module
View source
<?php

/**
 * @file
 * This is the Actions module for executing stored actions.
 */

/**
 * @defgroup actions Actions
 * @{
 * Functions that perform an action on a certain system object.
 *
 * Action functions are declared by modules by implementing hook_action_info().
 * Modules can cause action functions to run by calling actions_do().
 *
 * Each action function takes two to four arguments:
 * - $entity: The object that the action acts on, such as a node, comment, or
 *   user.
 * - $context: Array of additional information about what triggered the action.
 * - $a1, $a2: Optional additional information, which can be passed into
 *   actions_do() and will be passed along to the action function.
 *
 * @} End of "defgroup actions".
 */

/**
 * Implements hook_help().
 */
function action_help($path, $arg) {
  switch ($path) {
    case 'admin/help#action':
      $output = '<p>' . t('Actions are individual tasks that the system can do, such as unpublishing a piece of content or banning a user. Other modules can fire these actions when certain system events happen; for example, when a new post is added or when a user logs in. Modules may also provide additional actions. Visit the <a href="@actions">Actions page</a> to configure actions.', array(
        '@actions' => url('admin/config/system/actions'),
      )) . '</p>';
      return $output;
    case 'admin/config/system/actions':
    case 'admin/config/system/actions/manage':
      $output = '<p>' . t('There are two types of actions: simple and advanced. Simple actions do not require any additional configuration and are listed here automatically. Advanced actions need to be created and configured before they can be used because they have options that need to be specified; for example, sending an e-mail to a specified address or unpublishing content containing certain words. To create an advanced action, select the action from the drop-down list in the advanced action section below and click the <em>Create</em> button.') . '</p>';
      return $output;
    case 'admin/config/system/actions/configure':
      return t('An advanced action offers additional configuration options which may be filled out below. Changing the <em>Description</em> field is recommended in order to better identify the precise action taking place.');
  }
}

/**
 * Implements hook_permission().
 */
function action_permission() {
  return array(
    'administer actions' => array(
      'title' => t('Administer actions'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function action_menu() {
  $items['admin/config/system/actions'] = array(
    'title' => 'Actions',
    'description' => 'Manage the actions defined for your site.',
    'access arguments' => array(
      'administer actions',
    ),
    'page callback' => 'action_admin_manage',
    'file' => 'action.admin.inc',
  );
  $items['admin/config/system/actions/manage'] = array(
    'title' => 'Manage actions',
    'description' => 'Manage the actions defined for your site.',
    'page callback' => 'action_admin_manage',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -2,
    'file' => 'action.admin.inc',
  );
  $items['admin/config/system/actions/configure'] = array(
    'title' => 'Configure an advanced action',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'action_admin_configure',
    ),
    'access arguments' => array(
      'administer actions',
    ),
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'file' => 'action.admin.inc',
  );
  $items['admin/config/system/actions/delete/%action'] = array(
    'title' => 'Delete action',
    'description' => 'Delete an action.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'action_admin_delete_form',
      5,
    ),
    'access arguments' => array(
      'administer actions',
    ),
    'file' => 'action.admin.inc',
  );
  $items['admin/config/system/actions/orphan'] = array(
    'title' => 'Remove orphans',
    'page callback' => 'action_admin_remove_orphans',
    'access arguments' => array(
      'administer actions',
    ),
    'type' => MENU_CALLBACK,
    'file' => 'action.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_rebuild().
 */
function action_rebuild() {

  // Synchronize any actions that were added or removed.
  action_synchronize();
}

/**
 * Performs a given list of actions by executing their callback functions.
 *
 * Given the IDs of actions to perform, this function finds out what the
 * callback functions for the actions are by querying the database. Then
 * it calls each callback using the function call $function($object, $context,
 * $a1, $a2), passing the input arguments of this function (see below) to the
 * action function.
 *
 * @param $action_ids
 *   The IDs of the actions to perform. Can be a single action ID or an array
 *   of IDs. IDs of configurable actions must be given as numeric action IDs;
 *   IDs of non-configurable actions may be given as action function names.
 * @param $object
 *   The object that the action will act on: a node, user, or comment object.
 * @param $context
 *   Associative array containing extra information about what triggered
 *   the action call, with $context['hook'] giving the name of the hook
 *   that resulted in this call to actions_do(). Additional parameters
 *   will be used as the data for token replacement.
 * @param $a1
 *   Passed along to the callback.
 * @param $a2
 *   Passed along to the callback.
 *
 * @return
 *   An associative array containing the results of the functions that
 *   perform the actions, keyed on action ID.
 *
 * @ingroup actions
 */
function actions_do($action_ids, $object = NULL, $context = NULL, $a1 = NULL, $a2 = NULL) {

  // $stack tracks the number of recursive calls.
  static $stack;
  $stack++;
  $recursion_limit = config('action.settings')
    ->get('recursion_limit');
  if ($stack > $recursion_limit) {
    watchdog('action', 'Stack overflow: recursion limit for actions_do() has been reached. Stack is limited by %limit calls.', array(
      '%limit' => $recursion_limit,
    ), WATCHDOG_ERROR);
    return;
  }
  $actions = array();
  $available_actions = action_list();
  $result = array();
  if (is_array($action_ids)) {
    $conditions = array();
    foreach ($action_ids as $action_id) {
      if (is_numeric($action_id)) {
        $conditions[] = $action_id;
      }
      elseif (isset($available_actions[$action_id])) {
        $actions[$action_id] = $available_actions[$action_id];
      }
    }

    // When we have action instances we must go to the database to retrieve
    // instance data.
    if (!empty($conditions)) {
      $query = db_select('actions');
      $query
        ->addField('actions', 'aid');
      $query
        ->addField('actions', 'type');
      $query
        ->addField('actions', 'callback');
      $query
        ->addField('actions', 'parameters');
      $query
        ->condition('aid', $conditions, 'IN');
      foreach ($query
        ->execute() as $action) {
        $actions[$action->aid] = $action->parameters ? unserialize($action->parameters) : array();
        $actions[$action->aid]['callback'] = $action->callback;
        $actions[$action->aid]['type'] = $action->type;
      }
    }

    // Fire actions, in no particular order.
    foreach ($actions as $action_id => $params) {

      // Configurable actions need parameters.
      if (is_numeric($action_id)) {
        $function = $params['callback'];
        if (function_exists($function)) {
          $context = array_merge($context, $params);
          $result[$action_id] = $function($object, $context, $a1, $a2);
        }
        else {
          $result[$action_id] = FALSE;
        }
      }
      else {
        $result[$action_id] = $action_id($object, $context, $a1, $a2);
      }
    }
  }
  else {

    // If it's a configurable action, retrieve stored parameters.
    if (is_numeric($action_ids)) {
      $action = db_query("SELECT callback, parameters FROM {actions} WHERE aid = :aid", array(
        ':aid' => $action_ids,
      ))
        ->fetchObject();
      $function = $action->callback;
      if (function_exists($function)) {
        $context = array_merge($context, unserialize($action->parameters));
        $result[$action_ids] = $function($object, $context, $a1, $a2);
      }
      else {
        $result[$action_ids] = FALSE;
      }
    }
    else {
      if (function_exists($action_ids)) {
        $result[$action_ids] = $action_ids($object, $context, $a1, $a2);
      }
      else {

        // Set to avoid undefined index error messages later.
        $result[$action_ids] = FALSE;
      }
    }
  }
  $stack--;
  return $result;
}

/**
 * Discovers all available actions by invoking hook_action_info().
 *
 * This function contrasts with action_get_all_actions(); see the
 * documentation of action_get_all_actions() for an explanation.
 *
 * @param $reset
 *   Reset the action info static cache.
 *
 * @return
 *   An associative array keyed on action function name, with the same format
 *   as the return value of hook_action_info(), containing all
 *   modules' hook_action_info() return values as modified by any
 *   hook_action_info_alter() implementations.
 *
 * @see hook_action_info()
 */
function action_list($reset = FALSE) {
  $actions =& drupal_static(__FUNCTION__);
  if (!isset($actions) || $reset) {
    $actions = module_invoke_all('action_info');
    drupal_alter('action_info', $actions);
  }

  // See module_implements() for an explanation of this cast.
  return (array) $actions;
}

/**
 * Retrieves all action instances from the database.
 *
 * This function differs from the action_list() function, which gathers
 * actions by invoking hook_action_info(). The actions returned by this
 * function and the actions returned by action_list() are partially
 * synchronized. Non-configurable actions from hook_action_info()
 * implementations are put into the database when action_synchronize() is
 * called, which happens when admin/config/system/actions is visited.
 * Configurable actions are not added to the database until they are configured
 * in the user interface, in which case a database row is created for each
 * configuration of each action.
 *
 * @return
 *   Associative array keyed by numeric action ID. Each value is an associative
 *   array with keys 'callback', 'label', 'type' and 'configurable'.
 */
function action_get_all_actions() {
  $actions = db_query("SELECT aid, type, callback, parameters, label FROM {actions}")
    ->fetchAllAssoc('aid', PDO::FETCH_ASSOC);
  foreach ($actions as &$action) {
    $action['configurable'] = (bool) $action['parameters'];
    unset($action['parameters']);
    unset($action['aid']);
  }
  return $actions;
}

/**
 * Creates an associative array keyed by hashes of function names or IDs.
 *
 * Hashes are used to prevent actual function names from going out into HTML
 * forms and coming back.
 *
 * @param $actions
 *   An associative array with function names or action IDs as keys
 *   and associative arrays with keys 'label', 'type', etc. as values.
 *   This is usually the output of action_list() or action_get_all_actions().
 *
 * @return
 *   An associative array whose keys are hashes of the input array keys, and
 *   whose corresponding values are associative arrays with components
 *   'callback', 'label', 'type', and 'configurable' from the input array.
 */
function action_actions_map($actions) {
  $actions_map = array();
  foreach ($actions as $callback => $array) {
    $key = drupal_hash_base64($callback);
    $actions_map[$key]['callback'] = isset($array['callback']) ? $array['callback'] : $callback;
    $actions_map[$key]['label'] = $array['label'];
    $actions_map[$key]['type'] = $array['type'];
    $actions_map[$key]['configurable'] = $array['configurable'];
  }
  return $actions_map;
}

/**
 * Returns an action array key (function or ID), given its hash.
 *
 * Faster than action_actions_map() when you only need the function name or ID.
 *
 * @param $hash
 *   Hash of a function name or action ID array key. The array key
 *   is a key into the return value of action_list() (array key is the action
 *   function name) or action_get_all_actions() (array key is the action ID).
 *
 * @return
 *   The corresponding array key, or FALSE if no match is found.
 */
function action_function_lookup($hash) {

  // Check for a function name match.
  $actions_list = action_list();
  foreach ($actions_list as $function => $array) {
    if (drupal_hash_base64($function) == $hash) {
      return $function;
    }
  }
  $aid = FALSE;

  // Must be a configurable action; check database.
  $result = db_query("SELECT aid FROM {actions} WHERE parameters <> ''")
    ->fetchAll(PDO::FETCH_ASSOC);
  foreach ($result as $row) {
    if (drupal_hash_base64($row['aid']) == $hash) {
      $aid = $row['aid'];
      break;
    }
  }
  return $aid;
}

/**
 * Synchronizes actions that are provided by modules in hook_action_info().
 *
 * Actions provided by modules in hook_action_info() implementations are
 * synchronized with actions that are stored in the actions database table.
 * This is necessary so that actions that do not require configuration can
 * receive action IDs.
 *
 * @param $delete_orphans
 *   If TRUE, any actions that exist in the database but are no longer
 *   found in the code (for example, because the module that provides them has
 *   been disabled) will be deleted.
 */
function action_synchronize($delete_orphans = FALSE) {
  $actions_in_code = action_list(TRUE);
  $actions_in_db = db_query("SELECT aid, callback, label FROM {actions} WHERE parameters = ''")
    ->fetchAllAssoc('callback', PDO::FETCH_ASSOC);

  // Go through all the actions provided by modules.
  foreach ($actions_in_code as $callback => $array) {

    // Ignore configurable actions since their instances get put in when the
    // user adds the action.
    if (!$array['configurable']) {

      // If we already have an action ID for this action, no need to assign aid.
      if (isset($actions_in_db[$callback])) {
        unset($actions_in_db[$callback]);
      }
      else {

        // This is a new singleton that we don't have an aid for; assign one.
        db_insert('actions')
          ->fields(array(
          'aid' => $callback,
          'type' => $array['type'],
          'callback' => $callback,
          'parameters' => '',
          'label' => $array['label'],
        ))
          ->execute();
        watchdog('action', "Action '%action' added.", array(
          '%action' => $array['label'],
        ));
      }
    }
  }

  // Any actions that we have left in $actions_in_db are orphaned.
  if ($actions_in_db) {
    $orphaned = array_keys($actions_in_db);
    if ($delete_orphans) {
      $actions = db_query('SELECT aid, label FROM {actions} WHERE callback IN (:orphaned)', array(
        ':orphaned' => $orphaned,
      ))
        ->fetchAll();
      foreach ($actions as $action) {
        action_delete($action->aid);
        watchdog('action', "Removed orphaned action '%action' from database.", array(
          '%action' => $action->label,
        ));
      }
    }
    else {
      $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
      $count = count($actions_in_db);
      $orphans = implode(', ', $orphaned);
      watchdog('action', '@count orphaned actions (%orphans) exist in the actions table. !link', array(
        '@count' => $count,
        '%orphans' => $orphans,
        '!link' => $link,
      ), WATCHDOG_INFO);
    }
  }
}

/**
 * Saves an action and its user-supplied parameter values to the database.
 *
 * @param $function
 *   The name of the function to be called when this action is performed.
 * @param $type
 *   The type of action, to describe grouping and/or context, e.g., 'node',
 *   'user', 'comment', or 'system'.
 * @param $params
 *   An associative array with parameter names as keys and parameter values as
 *   values.
 * @param $label
 *   A user-supplied label of this particular action, e.g., 'Send e-mail
 *   to Jim'.
 * @param $aid
 *   The ID of this action. If omitted, a new action is created.
 *
 * @return
 *   The ID of the action.
 */
function action_save($function, $type, $params, $label, $aid = NULL) {

  // aid is the callback for singleton actions so we need to keep a separate
  // table for numeric aids.
  if (!$aid) {
    $aid = db_next_id();
  }
  db_merge('actions')
    ->key(array(
    'aid' => $aid,
  ))
    ->fields(array(
    'callback' => $function,
    'type' => $type,
    'parameters' => serialize($params),
    'label' => $label,
  ))
    ->execute();
  watchdog('action', 'Action %action saved.', array(
    '%action' => $label,
  ));
  return $aid;
}

/**
 * Retrieves a single action from the database.
 *
 * @param $aid
 *   The ID of the action to retrieve.
 *
 * @return
 *   The appropriate action row from the database as an object.
 */
function action_load($aid) {
  return db_query("SELECT aid, type, callback, parameters, label FROM {actions} WHERE aid = :aid", array(
    ':aid' => $aid,
  ))
    ->fetchObject();
}

/**
 * Deletes a single action from the database.
 *
 * @param $aid
 *   The ID of the action to delete.
 */
function action_delete($aid) {
  db_delete('actions')
    ->condition('aid', $aid)
    ->execute();
  module_invoke_all('action_delete', $aid);
}

/**
 * Implements hook_action_info().
 *
 * @ingroup actions
 */
function action_action_info() {
  return array(
    'action_message_action' => array(
      'type' => 'system',
      'label' => t('Display a message to the user'),
      'configurable' => TRUE,
      'triggers' => array(
        'any',
      ),
    ),
    'action_send_email_action' => array(
      'type' => 'system',
      'label' => t('Send e-mail'),
      'configurable' => TRUE,
      'triggers' => array(
        'any',
      ),
    ),
    'action_goto_action' => array(
      'type' => 'system',
      'label' => t('Redirect to URL'),
      'configurable' => TRUE,
      'triggers' => array(
        'any',
      ),
    ),
  );
}

/**
 * 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.
 *
 * @see action_send_email_action_validate()
 * @see action_send_email_action_submit()
 */
function action_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'],
    '#maxlength' => '254',
    '#description' => t('The e-mail address to which the message should be sent OR enter [node:author:mail], [comment:author:mail], etc. if you would like to send an e-mail to the author of the original post.'),
  );
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => $context['subject'],
    '#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. You may include placeholders like [node:title], [user:name], and [comment:body] to represent data that will be different each time message is sent. Not all placeholders will be available in all contexts.'),
  );
  return $form;
}

/**
 * Validates action_send_email_action() form submissions.
 */
function action_send_email_action_validate($form, $form_state) {
  $form_values = $form_state['values'];

  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient']) && strpos($form_values['recipient'], ':mail') === FALSE) {

    // We want the literal %author placeholder to be emphasized in the error message.
    form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array(
      '%author' => '[node:author:mail]',
    )));
  }
}

/**
 * Processes action_send_email_action() form submissions.
 */
function action_send_email_action_submit($form, $form_state) {
  $form_values = $form_state['values'];

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

/**
 * Sends an e-mail message.
 *
 * @param object $entity
 *   An optional node entity, which will be added as $context['node'] if
 *   provided.
 * @param array $context
 *   Array with the following elements:
 *   - 'recipient': E-mail message recipient. This will be passed through
 *     token_replace().
 *   - 'subject': The subject of the message. This will be passed through
 *     token_replace().
 *   - 'message': The message to send. This will be passed through
 *     token_replace().
 *   - Other elements will be used as the data for token replacement.
 *
 * @ingroup actions
 */
function action_send_email_action($entity, $context) {
  if (empty($context['node'])) {
    $context['node'] = $entity;
  }
  $recipient = token_replace($context['recipient'], $context);

  // If the recipient is a registered user with a language preference, use
  // the recipient's preferred language. Otherwise, use the system default
  // language.
  $recipient_account = user_load_by_mail($recipient);
  if ($recipient_account) {
    $langcode = user_preferred_langcode($recipient_account);
  }
  else {
    $langcode = language_default()->langcode;
  }
  $params = array(
    'context' => $context,
  );
  if (drupal_mail('system', 'action_send_email', $recipient, $langcode, $params)) {
    watchdog('action', 'Sent email to %recipient', array(
      '%recipient' => $recipient,
    ));
  }
  else {
    watchdog('error', 'Unable to send email to %recipient', array(
      '%recipient' => $recipient,
    ));
  }
}

/**
 * Constructs the settings form for action_message_action().
 *
 * @see action_message_action_submit()
 */
function action_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. You may include placeholders like [node:title], [user:name], and [comment:body] to represent data that will be different each time message is sent. Not all placeholders will be available in all contexts.'),
  );
  return $form;
}

/**
 * Processes action_message_action form submissions.
 */
function action_message_action_submit($form, $form_state) {
  return array(
    'message' => $form_state['values']['message'],
  );
}

/**
 * Sends a message to the current user's screen.
 *
 * @param object $entity
 *   An optional node entity, which will be added as $context['node'] if
 *   provided.
 * @param array $context
 *   Array with the following elements:
 *   - 'message': The message to send. This will be passed through
 *     token_replace().
 *   - Other elements will be used as the data for token replacement in
 *     the message.
 *
 * @ingroup actions
 */
function action_message_action(&$entity, $context = array()) {
  if (empty($context['node'])) {
    $context['node'] = $entity;
  }
  $context['message'] = token_replace(filter_xss_admin($context['message']), $context);
  drupal_set_message($context['message']);
}

/**
 * Constructs the settings form for action_goto_action().
 *
 * @see action_goto_action_submit()
 */
function action_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 @url.', array(
      '@url' => 'http://drupal.org',
    )),
    '#default_value' => isset($context['url']) ? $context['url'] : '',
    '#required' => TRUE,
  );
  return $form;
}

/**
 * Processes action_goto_action form submissions.
 */
function action_goto_action_submit($form, $form_state) {
  return array(
    'url' => $form_state['values']['url'],
  );
}

/**
 * Redirects to a different URL.
 *
 * Action functions are declared by modules by implementing hook_action_info().
 * Modules can cause action functions to run by calling actions_do().
 *
 * @param object $entity
 *   An optional node entity, which will be added as $context['node'] if
 *   provided.
 * @param array $context
 *   Array with the following elements:
 *   - 'url': URL to redirect to. This will be passed through
 *     token_replace().
 *   - Other elements will be used as the data for token replacement.
 *
 * @ingroup actions.
 */
function action_goto_action($entity, $context) {
  drupal_goto(token_replace($context['url'], $context));
}

Functions

Namesort descending Description
actions_do Performs a given list of actions by executing their callback functions.
action_actions_map Creates an associative array keyed by hashes of function names or IDs.
action_action_info Implements hook_action_info().
action_delete Deletes a single action from the database.
action_function_lookup Returns an action array key (function or ID), given its hash.
action_get_all_actions Retrieves all action instances from the database.
action_goto_action Redirects to a different URL.
action_goto_action_form Constructs the settings form for action_goto_action().
action_goto_action_submit Processes action_goto_action form submissions.
action_help Implements hook_help().
action_list Discovers all available actions by invoking hook_action_info().
action_load Retrieves a single action from the database.
action_menu Implements hook_menu().
action_message_action Sends a message to the current user's screen.
action_message_action_form Constructs the settings form for action_message_action().
action_message_action_submit Processes action_message_action form submissions.
action_permission Implements hook_permission().
action_rebuild Implements hook_rebuild().
action_save Saves an action and its user-supplied parameter values to the database.
action_send_email_action Sends an e-mail message.
action_send_email_action_form Return a form definition so the Send email action can be configured.
action_send_email_action_submit Processes action_send_email_action() form submissions.
action_send_email_action_validate Validates action_send_email_action() form submissions.
action_synchronize Synchronizes actions that are provided by modules in hook_action_info().