Code coverage for /20081101/includes/actions.inc

Line #Times calledCode
1
<?php
2
// $Id: actions.inc,v 1.21 2008/10/10 08:49:51 dries Exp $
3
4
/**
5
 * @file
6
 * This is the actions engine for executing stored actions.
7
 */
8
9
/**
10
 * Perform a given list of actions by executing their callback functions.
11
 *
12
 * Given the IDs of actions to perform, find out what the callbacks
13
 * for the actions are by querying the database. Then call each callback
14
 * using the function call $function($object, $context, $a1, $a2)
15
 * where $function is the name of a function written in compliance with
16
 * the action specification; that is, foo($object, $context).
17
 *
18
 * @param $action_ids
19
 *   The ID of the action to perform. Can be a single action ID or an array
20
 *   of IDs. IDs of instances will be numeric; IDs of singletons will be
21
 *   function names.
22
 * @param $object
23
 *   Parameter that will be passed along to the callback. Typically the
24
 *   object that the action will act on; a node, user or comment object.
25
 * @param $context
26
 *   Parameter that will be passed along to the callback. $context is a
27
 *   keyed array containing extra information about what is currently
28
 *   happening at the time of the call. Typically $context['hook'] and
29
 *   $context['op'] will tell which hook-op combination resulted in this
30
 *   call to actions_do().
31
 * @param $a1
32
 *   Parameter that will be passed along to the callback.
33
 * @param $a2
34
 *   Parameter that will be passed along to the callback.
35
 *
36
 * @return
37
 *   An associative array containing the result of the function that
38
 *   performs the action, keyed on action ID.
39
 */
402366
function actions_do($action_ids, $object = NULL, $context = NULL, $a1 =
NULL, $a2 = NULL) {
41
  // $stack tracks the number of recursive calls.
426
  static $stack;
436
  $stack++;
446
  if ($stack > variable_get('actions_max_stack', 35)) {
450
    watchdog('actions', 'Stack overflow: too many calls to actions_do().
Aborting to prevent infinite recursion.', array(), WATCHDOG_ERROR);
460
    return;
470
  }
486
  $actions = array();
496
  $available_actions = actions_list();
506
  $result = array();
516
  if (is_array($action_ids)) {
52
530
    $conditions = array();
540
    foreach ($action_ids as $action_id) {
550
      if (is_numeric($action_id)) {
560
        $conditions[] = $action_id;
570
      }
580
      elseif (isset($available_actions[$action_id])) {
590
        $actions[$action_id] = $available_actions[$action_id];
600
      }
610
    }
62
63
    // When we have action instances we must go to the database to
64
    // retrieve instance data.
650
    if (!empty($conditions)) {
660
      $query = db_select('actions');
670
      $query->addField('actions', 'aid');
680
      $query->addField('actions', 'type');
690
      $query->addField('actions', 'callback');
700
      $query->addField('actions', 'parameters');
710
      $query->condition('aid', $conditions, 'IN');
720
      $result = $query->execute();
730
      foreach ($result as $action) {
740
        $actions[$action->aid] = $action->parameters ?
unserialize($action->parameters) : array();
750
        $actions[$action->aid]['callback'] = $action->callback;
760
        $actions[$action->aid]['type'] = $action->type;
770
      }
780
    }
79
80
    // Fire actions, in no particular order.
810
    foreach ($actions as $action_id => $params) {
820
      if (is_numeric($action_id)) { // Configurable actions need
parameters.
830
        $function = $params['callback'];
840
        $context = array_merge($context, $params);
850
        $result[$action_id] = $function($object, $context, $a1, $a2);
860
      }
87
      // Singleton action; $action_id is the function name.
88
      else {
890
        $result[$action_id] = $action_id($object, $context, $a1, $a2);
90
      }
910
    }
920
  }
93
  // Optimized execution of single action.
94
  else {
95
    // If it's a configurable action, retrieve stored parameters.
966
    if (is_numeric($action_ids)) {
970
      $action = db_query("SELECT callback, parameters FROM {actions} WHERE
aid = :aid", array(':aid' => $action_ids))->fetchObject();
980
      $function = $action->callback;
990
      $context = array_merge($context, unserialize($action->parameters));
1000
      $result[$action_ids] = $function($object, $context, $a1, $a2);
1010
    }
102
    // Singleton action; $action_ids is the function name.
103
    else {
1046
      $result[$action_ids] = $action_ids($object, $context, $a1, $a2);
105
    }
106
  }
1076
  $stack--;
1086
  return $result;
1090
}
110
111
112
/**
113
 * Discover all action functions by invoking hook_action_info().
114
 *
115
 * mymodule_action_info() {
116
 *   return array(
117
 *     'mymodule_functiondescription_action' => array(
118
 *       'type' => 'node',
119
 *       'description' => t('Save node'),
120
 *       'configurable' => FALSE,
121
 *       'hooks' => array(
122
 *         'nodeapi' => array('delete', 'insert', 'update', 'view'),
123
 *         'comment' => array('delete', 'insert', 'update', 'view'),
124
 *       )
125
 *     )
126
 *   );
127
 * }
128
 *
129
 * The description is used in presenting possible actions to the user for
130
 * configuration. The type is used to present these actions in a logical
131
 * grouping and to denote context. Some types are 'node', 'user',
'comment',
132
 * and 'system'. If an action is configurable it will provide form,
133
 * validation and submission functions. The hooks the action supports
134
 * are declared in the 'hooks' array.
135
 *
136
 * @param $reset
137
 *   Reset the action info static cache.
138
 *
139
 * @return
140
 *   An associative array keyed on function name. The value of each key is
141
 *   an array containing information about the action, such as type of
142
 *   action and description of the action, e.g.,
143
 *
144
 *   @code
145
 *   $actions['node_publish_action'] = array(
146
 *     'type' => 'node',
147
 *     'description' => t('Publish post'),
148
 *     'configurable' => FALSE,
149
 *     'hooks' => array(
150
 *       'nodeapi' => array('presave', 'insert', 'update', 'view'),
151
 *       'comment' => array('delete', 'insert', 'update', 'view'),
152
 *     ),
153
 *   );
154
 *   @endcode
155
 */
1562366
function actions_list($reset = FALSE) {
157215
  static $actions;
158215
  if (!isset($actions) || $reset) {
159215
    $actions = module_invoke_all('action_info');
160215
    drupal_alter('action_info', $actions);
161215
  }
162
163
  // See module_implements for explanations of this cast.
164215
  return (array)$actions;
1650
}
166
167
/**
168
 * Retrieve all action instances from the database.
169
 *
170
 * Compare with actions_list() which gathers actions by
171
 * invoking hook_action_info(). The two are synchronized
172
 * by visiting /admin/build/actions (when actions.module is
173
 * enabled) which runs actions_synchronize().
174
 *
175
 * @return
176
 *   Associative array keyed by action ID. Each value is
177
 *   an associative array with keys 'callback', 'description',
178
 *   'type' and 'configurable'.
179
 */
1802366
function actions_get_all_actions() {
18160
  $actions = db_query("SELECT aid, type, callback, parameters, description
FROM {actions}")->fetchAllAssoc('aid', PDO::FETCH_ASSOC);
18260
  foreach ($actions as &$action) {
18360
    $action['configurable'] = (bool) $action['parameters'];
18460
    unset($action['parameters']);
18560
    unset($action['aid']);
18660
  }
18760
  return $actions;
1880
}
189
190
/**
191
 * Create an associative array keyed by md5 hashes of function names.
192
 *
193
 * Hashes are used to prevent actual function names from going out into
194
 * HTML forms and coming back.
195
 *
196
 * @param $actions
197
 *   An associative array with function names as keys and associative
198
 *   arrays with keys 'description', 'type', etc. as values. Generally
199
 *   the output of actions_list() or actions_get_all_actions() is given
200
 *   as input to this function.
201
 *
202
 * @return
203
 *   An associative array keyed on md5 hash of function name. The value of
204
 *   each key is an associative array of function, description, and type
205
 *   for the action.
206
 */
2072366
function actions_actions_map($actions) {
20860
  $actions_map = array();
20960
  foreach ($actions as $callback => $array) {
21060
    $key = md5($callback);
21160
    $actions_map[$key]['callback']     = isset($array['callback']) ?
$array['callback'] : $callback;
21260
    $actions_map[$key]['description']  = $array['description'];
21360
    $actions_map[$key]['type']         = $array['type'];
21460
    $actions_map[$key]['configurable'] = $array['configurable'];
21560
  }
21660
  return $actions_map;
2170
}
218
219
/**
220
 * Given an md5 hash of a function name, return the function name.
221
 *
222
 * Faster than actions_actions_map() when you only need the function name.
223
 *
224
 * @param $hash
225
 *   MD5 hash of a function name
226
 *
227
 * @return
228
 *   Function name
229
 */
2302366
function actions_function_lookup($hash) {
23132
  $actions_list = actions_list();
23232
  foreach ($actions_list as $function => $array) {
23332
    if (md5($function) == $hash) {
23432
      return $function;
2350
    }
23632
  }
237
238
  // Must be an instance; must check database.
2390
  return db_query("SELECT aid FROM {actions} WHERE MD5(aid) = :hash AND
parameters <> ''", array(':hash' => $hash))->fetchField();
2400
}
241
242
/**
243
 * Synchronize actions that are provided by modules.
244
 *
245
 * They are synchronized with actions that are stored in the actions table.
246
 * This is necessary so that actions that do not require configuration can
247
 * receive action IDs. This is not necessarily the best approach,
248
 * but it is the most straightforward.
249
 */
2502366
function actions_synchronize($actions_in_code = array(), $delete_orphans =
FALSE) {
251143
  if (!$actions_in_code) {
252137
    $actions_in_code = actions_list(TRUE);
253137
  }
254143
  $actions_in_db = db_query("SELECT aid, callback, description FROM
{actions} WHERE parameters = ''")->fetchAllAssoc('callback',
PDO::FETCH_ASSOC);
255
256
  // Go through all the actions provided by modules.
257143
  foreach ($actions_in_code as $callback => $array) {
258
    // Ignore configurable actions since their instances get put in
259
    // when the user adds the action.
260143
    if (!$array['configurable']) {
261
      // If we already have an action ID for this action, no need to assign
aid.
262143
      if (array_key_exists($callback, $actions_in_db)) {
26310
        unset($actions_in_db[$callback]);
26410
      }
265
      else {
266
        // This is a new singleton that we don't have an aid for; assign
one.
267134
        db_insert('actions')
268134
          ->fields(array(
269134
            'aid' => $callback,
270134
            'type' => $array['type'],
271134
            'callback' => $callback,
272134
            'parameters' => '',
273134
            'description' => $array['description'],
274134
            ))
275134
          ->execute();
276134
        watchdog('actions', "Action '%action' added.", array('%action' =>
filter_xss_admin($array['description'])));
277
      }
278143
    }
279143
  }
280
281
  // Any actions that we have left in $actions_in_db are orphaned.
282143
  if ($actions_in_db) {
2830
    $orphaned = array_keys($actions_in_db);
284
2850
    if ($delete_orphans) {
2860
      $results = db_select('actions')
2870
        ->addField('actions', 'aid')
2880
        ->addField('actions', 'description')
2890
        ->condition('callback', $orphaned, 'IN')
2900
        ->execute();
2910
      foreach ($results as $action) {
2920
        actions_delete($action->aid);
2930
        watchdog('actions', "Removed orphaned action '%action' from
database.", array('%action' => filter_xss_admin($action->description)));
2940
      }
2950
    }
296
    else {
2970
      $link = l(t('Remove orphaned actions'),
'admin/settings/actions/orphan');
2980
      $count = count($actions_in_db);
2990
      $orphans = implode(', ', $orphaned);
3000
      watchdog('actions', format_plural($count, 'One orphaned action
(%orphans) exists in the actions table. !link', '@count orphaned actions
(%orphans) exist in the actions table. !link'), array('@count' => $count,
'%orphans' => $orphans, '!link' => $link), WATCHDOG_WARNING);
301
    }
3020
  }
303143
}
304
305
/**
306
 * Save an action and its associated user-supplied parameter values to the
database.
307
 *
308
 * @param $function
309
 *   The name of the function to be called when this action is performed.
310
 * @param $params
311
 *   An associative array with parameter names as keys and parameter values
312
 *   as values.
313
 * @param $desc
314
 *   A user-supplied description of this particular action, e.g., 'Send
315
 *   e-mail to Jim'.
316
 * @param $aid
317
 *   The ID of this action. If omitted, a new action is created.
318
 *
319
 * @return
320
 *   The ID of the action.
321
 */
3222366
function actions_save($function, $type, $params, $desc, $aid = NULL) {
323
  // aid is the callback for singleton actions so we need to keep a
324
  // separate table for numeric aids.
3252
  if (!$aid) {
3261
    $aid = db_insert('actions_aid')->execute();
3271
  }
328
3292
  db_merge('actions')
3302
    ->key(array('aid' => $aid))
3312
    ->fields(array(
3322
      'callback' => $function,
3332
      'type' => $type,
3342
      'parameters' => serialize($params),
3352
      'description' => $desc,
3362
    ))
3372
    ->execute();
338
3392
  watchdog('actions', 'Action %action saved.', array('%action' => $desc));
3402
  return $aid;
3410
}
342
343
/**
344
 * Retrieve a single action from the database.
345
 *
346
 * @param $aid
347
 *   integer The ID of the action to retrieve.
348
 *
349
 * @return
350
 *   The appropriate action row from the database as an object.
351
 */
3522366
function actions_load($aid) {
3533
  return db_query("SELECT aid, type, callback, parameters, description FROM
{actions} WHERE aid = :aid", array(':aid' => $aid))->fetchObject();
3540
}
355
356
/**
357
 * Delete a single action from the database.
358
 *
359
 * @param $aid
360
 *   integer The ID of the action to delete.
361
 */
3622366
function actions_delete($aid) {
3631
  db_delete('actions')
3641
    ->condition('aid', $aid)
3651
    ->execute();
3661
  module_invoke_all('actions_delete', $aid);
3671
}
3682366