summaryrefslogtreecommitdiff
path: root/modules/trigger/trigger.module
blob: c085741a04e9542284038184174bd30708b8a6a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<?php
// $Id$

/**
 * @file
 * Enables functions to be stored and executed at a later time when
 * triggered by other modules or by one of Drupal's core API hooks.
 */

/**
 * Implement hook_help().
 */
function trigger_help($path, $arg) {
  $explanation = '<p>' . t('Triggers are system events, such as when new content is added or when a user logs in. Trigger module combines these triggers with actions (functional tasks), such as unpublishing content or e-mailing an administrator. The <a href="@url">Actions settings page</a> contains a list of existing actions and provides the ability to create and configure additional actions.', array('@url' => url('admin/settings/actions'))) . '</p>';
  switch ($path) {
    case 'admin/structure/trigger/comment':
      return $explanation . '<p>' . t('Below you can assign actions to run when certain comment-related triggers happen. For example, you could promote a post to the front page when a comment is added.') . '</p>';
    case 'admin/structure/trigger/node':
      return $explanation . '<p>' . t('Below you can assign actions to run when certain content-related triggers happen. For example, you could send an e-mail to an administrator when a post is created or updated.') . '</p>';
    case 'admin/structure/trigger/cron':
      return $explanation . '<p>' . t('Below you can assign actions to run during each pass of a <a href="@cron">cron maintenance task</a>.', array('@cron' => url('admin/reports/status'))) . '</p>';
    case 'admin/structure/trigger/taxonomy':
      return $explanation . '<p>' . t('Below you can assign actions to run when certain taxonomy-related triggers happen. For example, you could send an e-mail to an administrator when a term is deleted.') . '</p>';
    case 'admin/structure/trigger/user':
      return $explanation . '<p>' . t("Below you can assign actions to run when certain user-related triggers happen. For example, you could send an e-mail to an administrator when a user account is deleted.") . '</p>';
    case 'admin/help#trigger':
      $output = '<p>' . t('The Trigger module provides the ability to trigger <a href="@actions">actions</a> upon system events, such as when new content is added or when a user logs in.', array('@actions' => url('admin/settings/actions'))) . '</p>';
      $output .= '<p>' . t('The combination of actions and triggers can perform many useful tasks, such as e-mailing an administrator if a user account is deleted, or automatically unpublishing comments that contain certain words. By default, there are five "contexts" of events (Comments, Content, Cron, Taxonomy, and Users), but more may be added by additional modules.') . '</p>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@trigger">Trigger module</a>.', array('@trigger' => 'http://drupal.org/handbook/modules/trigger/')) . '</p>';
      return $output;
  }
}

/**
 * Implement hook_menu().
 */
function trigger_menu() {
  $items['admin/structure/trigger'] = array(
    'title' => 'Triggers',
    'description' => 'Tell Drupal when to execute actions.',
    'page callback' => 'trigger_assign',
    'access arguments' => array('administer actions'),
    'file' => 'trigger.admin.inc',
  );

  // Explicitly define the system menu item so we can label it "cron" rather
  // than "system".
  $items['admin/structure/trigger/cron'] = array(
    'title' => 'Cron',
    'page callback' => 'trigger_assign',
    'page arguments' => array('system'),
    'access arguments' => array('administer actions'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'trigger.admin.inc',
  );

  // We want contributed modules to be able to describe
  // their hooks and have actions assignable to them.
  $hooks = module_invoke_all('hook_info');
  foreach ($hooks as $module => $hook) {
    // We've already done system.module.
    if ($module == 'system') {
      continue;
    }
    $info = db_select('system')
      ->fields('system', array('info'))
      ->condition('name', $module)
      ->execute()
      ->fetchField();
    $info = unserialize($info);
    $nice_name = $info['name'];
    $items["admin/structure/trigger/$module"] = array(
      'title' => $nice_name,
      'page callback' => 'trigger_assign',
      'page arguments' => array($module),
      'access arguments' => array('administer actions'),
      'type' => MENU_LOCAL_TASK,
      'file' => 'trigger.admin.inc',
    );
  }
  $items['admin/structure/trigger/unassign'] = array(
    'title' => 'Unassign',
    'description' => 'Unassign an action from a trigger.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('trigger_unassign'),
    'access arguments' => array('administer actions'),
    'type' => MENU_CALLBACK,
    'file' => 'trigger.admin.inc',
  );

  return $items;
}

/**
 * Get the aids of actions to be executed for a hook-op combination.
 *
 * @param $hook
 *   The name of the hook being fired.
 * @param $op
 *   The name of the operation being executed. Defaults to an empty string
 *   because some hooks (e.g., hook_cron()) do not have operations.
 * @return
 *   An array of action IDs.
 */
function _trigger_get_hook_aids($hook, $op = '') {
  return db_query("SELECT ta.aid, a.type FROM {trigger_assignments} ta LEFT JOIN {actions} a ON ta.aid = a.aid WHERE ta.hook = :hook AND ta.op = :op ORDER BY ta.weight", array(
    ':hook' => $hook,
    ':op' => $op,
  ))->fetchAllKeyed();
}

/**
 * Implement hook_theme().
 */
function trigger_theme() {
  return array(
    'trigger_display' => array(
      'arguments' => array('element'),
      'file' => 'trigger.admin.inc',
    ),
  );
}

/**
 * Implement hook_forms(). We reuse code by using the
 * same assignment form definition for each node-op combination.
 */
function trigger_forms() {
  $hooks = module_invoke_all('hook_info');
  foreach ($hooks as $module => $info) {
    foreach ($hooks[$module] as $hook => $ops) {
      foreach ($ops as $op => $description) {
        $forms['trigger_' . $hook . '_' . $op . '_assign_form'] = array('callback' => 'trigger_assign_form');
      }
    }
  }

  return $forms;
}

/**
 * When an action is called in a context that does not match its type,
 * the object that the action expects must be retrieved. For example, when
 * an action that works on users is called during the node hook, the
 * user object is not available since the node hook doesn't pass it.
 * So here we load the object the action expects.
 *
 * @param $type
 *   The type of action that is about to be called.
 * @param $node
 *   The node that was passed via the node hook.
 * @return
 *   The object expected by the action that is about to be called.
 */
function _trigger_normalize_node_context($type, $node) {
  switch ($type) {
    // If an action that works on comments is being called in a node context,
    // the action is expecting a comment object. But we do not know which comment
    // to give it. The first? The most recent? All of them? So comment actions
    // in a node context are not supported.

    // An action that works on users is being called in a node context.
    // Load the user object of the node's author.
    case 'user':
      return user_load($node->uid);
  }
}

/**
 * Simple wrapper function to make user hooks work with new entry points.
 *
 * @TODO: Take advantage of the new API and reorganise/remove this function.
 */
function _trigger_node($node, $op, $a3 = NULL, $a4 = NULL) {
  // Keep objects for reuse so that changes actions make to objects can persist.
  static $objects;
  // Prevent recursion by tracking which operations have already been called.
  static $recursion;
  if (isset($recursion[$op])) {
    return;
  }
  $recursion[$op] = TRUE;

  $aids = _trigger_get_hook_aids('node', $op);
  if (!$aids) {
    return;
  }
  $context = array(
    'hook' => 'node',
    'op' => $op,
  );

  // We need to get the expected object if the action's type is not 'node'.
  // We keep the object in $objects so we can reuse it if we have multiple actions
  // that make changes to an object.
  foreach ($aids as $aid => $type) {
    if ($type != 'node') {
      if (!isset($objects[$type])) {
        $objects[$type] = _trigger_normalize_node_context($type, $node);
      }
      // Since we know about the node, we pass that info along to the action.
      $context['node'] = $node;
      $result = actions_do($aid, $objects[$type], $context, $a3, $a4);
    }
    else {
      actions_do($aid, $node, $context, $a3, $a4);
    }
  }
}

/**
 * Implement hook_node_view().
 */
function trigger_node_view($node, $build_mode) {
  _trigger_node($node, 'view', $build_mode);
}

/**
 * Implement hook_node_update().
 */
function trigger_node_update($node) {
  _trigger_node($node, 'update');
}

/**
 * Implement hook_node_presave().
 */
function trigger_node_presave($node) {
  _trigger_node($node, 'presave');
}

/**
 * Implement hook_node_insert().
 */
function trigger_node_insert($node) {
  _trigger_node($node, 'insert');
}

/**
 * Implement hook_node_delete().
 */
function trigger_node_delete($node) {
  _trigger_node($node, 'delete');
}

/**
 * When an action is called in a context that does not match its type,
 * the object that the action expects must be retrieved. For example, when
 * an action that works on nodes is called during the comment hook, the
 * node object is not available since the comment hook doesn't pass it.
 * So here we load the object the action expects.
 *
 * @param $type
 *   The type of action that is about to be called.
 * @param $comment
 *   The comment that was passed via the comment hook.
 * @return
 *   The object expected by the action that is about to be called.
 */
function _trigger_normalize_comment_context($type, $comment) {
  switch ($type) {
    // An action that works with nodes is being called in a comment context.
    case 'node':
      return node_load(is_array($comment) ? $comment['nid'] : $comment->nid);

    // An action that works on users is being called in a comment context.
    case 'user':
      return user_load(is_array($comment) ? $comment['uid'] : $comment->uid);
  }
}

/**
 * Implement hook_comment_insert().
 */
function trigger_comment_insert($comment) {
  _trigger_comment($comment, 'insert');
}

/**
 * Implement hook_comment_update().
 */
function trigger_comment_update($comment) {
  _trigger_comment($comment, 'update');
}

/**
 * Implement hook_comment_delete().
 */
function trigger_comment_delete($comment) {
  _trigger_comment($comment, 'delete');
}

/**
 * Implement hook_comment_view().
 */
function trigger_comment_view($comment) {
  _trigger_comment($comment, 'view');
}

/**
 * Helper function for implementations of hook_comment_op().
 *
 * @param $a1
 *   Argument, which will be passed to the action.
 *   It can be a array of form values or a comment.
 * @param $op
 *   What kind of action is being performed.
 */
function _trigger_comment($a1, $op) {
  // Keep objects for reuse so that changes actions make to objects can persist.
  static $objects;
  $aids = _trigger_get_hook_aids('comment', $op);
  $context = array(
    'hook' => 'comment',
    'op' => $op,
  );
  // We need to get the expected object if the action's type is not 'comment'.
  // We keep the object in $objects so we can reuse it if we have multiple actions
  // that make changes to an object.
  foreach ($aids as $aid => $type) {
    if ($type != 'comment') {
      if (!isset($objects[$type])) {
        $objects[$type] = _trigger_normalize_comment_context($type, $a1);
      }
      // Since we know about the comment, we pass it along to the action
      // in case it wants to peek at it.
      $context['comment'] = (object) $a1;
      actions_do($aid, $objects[$type], $context);
    }
    else {
      $a1 = (object) $a1;
      actions_do($aid, $a1, $context);
    }
  }
}

/**
 * Implement hook_cron().
 */
function trigger_cron() {
  $aids = _trigger_get_hook_aids('cron', 'run');
  $context = array(
    'hook' => 'cron',
    'op' => 'run',
  );
  // Cron does not act on any specific object.
  $object = NULL;
  actions_do(array_keys($aids), $object, $context);
}

/**
 * When an action is called in a context that does not match its type,
 * the object that the action expects must be retrieved. For example, when
 * an action that works on nodes is called during the user hook, the
 * node object is not available since the user hook doesn't pass it.
 * So here we load the object the action expects.
 *
 * @param $type
 *   The type of action that is about to be called.
 * @param $account
 *   The account object that was passed via the user hook.
 * @return
 *   The object expected by the action that is about to be called.
 */
function _trigger_normalize_user_context($type, $account) {
  switch ($type) {
    // If an action that works on comments is being called in a user context,
    // the action is expecting a comment object. But we have no way of
    // determining the appropriate comment object to pass. So comment
    // actions in a user context are not supported.

    // An action that works with nodes is being called in a user context.
    // If a single node is being viewed, return the node.
    case 'node':
      // If we are viewing an individual node, return the node.
      if ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == NULL)) {
        return node_load(array('nid' => arg(1)));
      }
  }
}

/**
 * trigger_user_login
 */
function trigger_user_login(&$edit, $account, $category) {
  _trigger_user('login', $edit, $account, $category);
}

/**
 * Implement hook_user_logout().
 */
function trigger_user_logout($account) {
  _trigger_user('logout', $edit = NULL, $account);
}

/**
 * Implement hook_user_insert().
 */
function trigger_user_insert(&$edit, $account, $category) {
  _trigger_user('insert', $edit, $account, $category);
}

/**
 * Implement hook_user_update().
 */
function trigger_user_update(&$edit, $account, $category) {
  _trigger_user('update', $edit, $account, $category);
}

/**
 * Implement hook_user_cancel().
 */
function trigger_user_cancel($edit, $account, $method) {
  switch ($method) {
    case 'user_cancel_reassign':
    case 'user_cancel_delete':
      _trigger_user('delete', $edit, $account, $method);
      break;
  }
}

/**
 * Implement hook_user_view().
 */
function trigger_user_view($account) {
  _trigger_user('view', $edit = NULL, $account, NULL);
}

/**
 * Simple wrapper function to make user hooks work with new entry points.
 *
 * @TODO: Take advantage of the new API and reorganise/remove this function.
 */
function _trigger_user($op, &$edit, $account, $category = NULL) {
  // Keep objects for reuse so that changes actions make to objects can persist.
  static $objects;
  $aids = _trigger_get_hook_aids('user', $op);
  $context = array(
    'hook' => 'user',
    'op' => $op,
    'form_values' => &$edit,
  );
  foreach ($aids as $aid => $type) {
    if ($type != 'user') {
      if (!isset($objects[$type])) {
        $objects[$type] = _trigger_normalize_user_context($type, $account);
      }
      $context['account'] = $account;
      actions_do($aid, $objects[$type], $context);
    }
    else {
      actions_do($aid, $account, $context, $category);
    }
  }
}

/**
 * Implement hook_taxonomy().
 */
function trigger_taxonomy($op, $type, $array) {
  if ($type != 'term') {
    return;
  }
  $aids = _trigger_get_hook_aids('taxonomy', $op);
  $context = array(
    'hook' => 'taxonomy',
    'op' => $op
  );
  actions_do(array_keys($aids), (object) $array, $context);
}

/**
 * Often we generate a select field of all actions. This function
 * generates the options for that select.
 *
 * @param $type
 *   One of 'node', 'user', 'comment'.
 * @return
 *   Array keyed by action ID.
 */
function trigger_options($type = 'all') {
  $options = array(t('Choose an action'));
  foreach (actions_actions_map(actions_get_all_actions()) as $aid => $action) {
    $options[$action['type']][$aid] = $action['description'];
  }

  if ($type == 'all') {
    return $options;
  }
  else {
    return $options[$type];
  }
}

/**
 * Implement hook_actions_delete().
 *
 * Remove all trigger entries for the given action, when deleted.
 */
function trigger_actions_delete($aid) {
  db_delete('trigger_assignments')
    ->condition('aid', $aid)
    ->execute();
}