Projet

Général

Profil

Paste
Télécharger (43 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / module.inc @ cd5c298a

1
<?php
2

    
3
/**
4
 * @file
5
 * API for loading and interacting with Drupal modules.
6
 */
7

    
8
/**
9
 * Loads all the modules that have been enabled in the system table.
10
 *
11
 * @param $bootstrap
12
 *   Whether to load only the reduced set of modules loaded in "bootstrap mode"
13
 *   for cached pages. See bootstrap.inc.
14
 *
15
 * @return
16
 *   If $bootstrap is NULL, return a boolean indicating whether all modules
17
 *   have been loaded.
18
 */
19
function module_load_all($bootstrap = FALSE) {
20
  static $has_run = FALSE;
21

    
22
  if (isset($bootstrap)) {
23
    foreach (module_list(TRUE, $bootstrap) as $module) {
24
      drupal_load('module', $module);
25
    }
26
    // $has_run will be TRUE if $bootstrap is FALSE.
27
    $has_run = !$bootstrap;
28
  }
29
  return $has_run;
30
}
31

    
32

    
33
/**
34
 * Returns a list of currently active modules.
35
 *
36
 * Usually, this returns a list of all enabled modules. When called early on in
37
 * the bootstrap, it will return a list of vital modules only (those needed to
38
 * generate cached pages).
39
 *
40
 * All parameters to this function are optional and should generally not be
41
 * changed from their defaults.
42
 *
43
 * @param $refresh
44
 *   (optional) Whether to force the module list to be regenerated (such as
45
 *   after the administrator has changed the system settings). Defaults to
46
 *   FALSE.
47
 * @param $bootstrap_refresh
48
 *   (optional) When $refresh is TRUE, setting $bootstrap_refresh to TRUE forces
49
 *   the module list to be regenerated using the reduced set of modules loaded
50
 *   in "bootstrap mode" for cached pages. Otherwise, setting $refresh to TRUE
51
 *   generates the complete list of enabled modules.
52
 * @param $sort
53
 *   (optional) By default, modules are ordered by weight and module name. Set
54
 *   this option to TRUE to return a module list ordered only by module name.
55
 * @param $fixed_list
56
 *   (optional) If an array of module names is provided, this will override the
57
 *   module list with the given set of modules. This will persist until the next
58
 *   call with $refresh set to TRUE or with a new $fixed_list passed in. This
59
 *   parameter is primarily intended for internal use (e.g., in install.php and
60
 *   update.php).
61
 *
62
 * @return
63
 *   An associative array whose keys and values are the names of the modules in
64
 *   the list.
65
 */
66
function module_list($refresh = FALSE, $bootstrap_refresh = FALSE, $sort = FALSE, $fixed_list = NULL) {
67
  static $list = array(), $sorted_list;
68

    
69
  if (empty($list) || $refresh || $fixed_list) {
70
    $list = array();
71
    $sorted_list = NULL;
72
    if ($fixed_list) {
73
      foreach ($fixed_list as $name => $module) {
74
        drupal_get_filename('module', $name, $module['filename']);
75
        $list[$name] = $name;
76
      }
77
    }
78
    else {
79
      if ($refresh) {
80
        // For the $refresh case, make sure that system_list() returns fresh
81
        // data.
82
        drupal_static_reset('system_list');
83
      }
84
      if ($bootstrap_refresh) {
85
        $list = system_list('bootstrap');
86
      }
87
      else {
88
        // Not using drupal_map_assoc() here as that requires common.inc.
89
        $list = array_keys(system_list('module_enabled'));
90
        $list = (!empty($list) ? array_combine($list, $list) : array());
91
      }
92
    }
93
  }
94
  if ($sort) {
95
    if (!isset($sorted_list)) {
96
      $sorted_list = $list;
97
      ksort($sorted_list);
98
    }
99
    return $sorted_list;
100
  }
101
  return $list;
102
}
103

    
104
/**
105
 * Builds a list of bootstrap modules and enabled modules and themes.
106
 *
107
 * @param $type
108
 *   The type of list to return:
109
 *   - module_enabled: All enabled modules.
110
 *   - bootstrap: All enabled modules required for bootstrap.
111
 *   - theme: All themes.
112
 *
113
 * @return
114
 *   An associative array of modules or themes, keyed by name. For $type
115
 *   'bootstrap', the array values equal the keys. For $type 'module_enabled'
116
 *   or 'theme', the array values are objects representing the respective
117
 *   database row, with the 'info' property already unserialized.
118
 *
119
 * @see module_list()
120
 * @see list_themes()
121
 */
122
function system_list($type) {
123
  $lists = &drupal_static(__FUNCTION__);
124

    
125
  // For bootstrap modules, attempt to fetch the list from cache if possible.
126
  // if not fetch only the required information to fire bootstrap hooks
127
  // in case we are going to serve the page from cache.
128
  if ($type == 'bootstrap') {
129
    if (isset($lists['bootstrap'])) {
130
      return $lists['bootstrap'];
131
    }
132
    if ($cached = cache_get('bootstrap_modules', 'cache_bootstrap')) {
133
      $bootstrap_list = $cached->data;
134
    }
135
    else {
136
      $bootstrap_list = db_query("SELECT name, filename FROM {system} WHERE status = 1 AND bootstrap = 1 AND type = 'module' ORDER BY weight ASC, name ASC")->fetchAllAssoc('name');
137
      cache_set('bootstrap_modules', $bootstrap_list, 'cache_bootstrap');
138
    }
139
    // To avoid a separate database lookup for the filepath, prime the
140
    // drupal_get_filename() static cache for bootstrap modules only.
141
    // The rest is stored separately to keep the bootstrap module cache small.
142
    foreach ($bootstrap_list as $module) {
143
      drupal_get_filename('module', $module->name, $module->filename);
144
    }
145
    // We only return the module names here since module_list() doesn't need
146
    // the filename itself.
147
    $lists['bootstrap'] = array_keys($bootstrap_list);
148
  }
149
  // Otherwise build the list for enabled modules and themes.
150
  elseif (!isset($lists['module_enabled'])) {
151
    if ($cached = cache_get('system_list', 'cache_bootstrap')) {
152
      $lists = $cached->data;
153
    }
154
    else {
155
      $lists = array(
156
        'module_enabled' => array(),
157
        'theme' => array(),
158
        'filepaths' => array(),
159
      );
160
      // The module name (rather than the filename) is used as the fallback
161
      // weighting in order to guarantee consistent behavior across different
162
      // Drupal installations, which might have modules installed in different
163
      // locations in the file system. The ordering here must also be
164
      // consistent with the one used in module_implements().
165
      $result = db_query("SELECT * FROM {system} WHERE type = 'theme' OR (type = 'module' AND status = 1) ORDER BY weight ASC, name ASC");
166
      foreach ($result as $record) {
167
        $record->info = unserialize($record->info);
168
        // Build a list of all enabled modules.
169
        if ($record->type == 'module') {
170
          $lists['module_enabled'][$record->name] = $record;
171
        }
172
        // Build a list of themes.
173
        if ($record->type == 'theme') {
174
          $lists['theme'][$record->name] = $record;
175
        }
176
        // Build a list of filenames so drupal_get_filename can use it.
177
        if ($record->status) {
178
          $lists['filepaths'][] = array('type' => $record->type, 'name' => $record->name, 'filepath' => $record->filename);
179
        }
180
      }
181
      foreach ($lists['theme'] as $key => $theme) {
182
        if (!empty($theme->info['base theme'])) {
183
          // Make a list of the theme's base themes.
184
          require_once DRUPAL_ROOT . '/includes/theme.inc';
185
          $lists['theme'][$key]->base_themes = drupal_find_base_themes($lists['theme'], $key);
186
          // Don't proceed if there was a problem with the root base theme.
187
          if (!current($lists['theme'][$key]->base_themes)) {
188
            continue;
189
          }
190
          // Determine the root base theme.
191
          $base_key = key($lists['theme'][$key]->base_themes);
192
          // Add to the list of sub-themes for each of the theme's base themes.
193
          foreach (array_keys($lists['theme'][$key]->base_themes) as $base_theme) {
194
            $lists['theme'][$base_theme]->sub_themes[$key] = $lists['theme'][$key]->info['name'];
195
          }
196
          // Add the base theme's theme engine info.
197
          $lists['theme'][$key]->info['engine'] = isset($lists['theme'][$base_key]->info['engine']) ? $lists['theme'][$base_key]->info['engine'] : 'theme';
198
        }
199
        else {
200
          // A plain theme is its own engine.
201
          $base_key = $key;
202
          if (!isset($lists['theme'][$key]->info['engine'])) {
203
            $lists['theme'][$key]->info['engine'] = 'theme';
204
          }
205
        }
206
        // Set the theme engine prefix.
207
        $lists['theme'][$key]->prefix = ($lists['theme'][$key]->info['engine'] == 'theme') ? $base_key : $lists['theme'][$key]->info['engine'];
208
      }
209
      cache_set('system_list', $lists, 'cache_bootstrap');
210
    }
211
    // To avoid a separate database lookup for the filepath, prime the
212
    // drupal_get_filename() static cache with all enabled modules and themes.
213
    foreach ($lists['filepaths'] as $item) {
214
      drupal_get_filename($item['type'], $item['name'], $item['filepath']);
215
    }
216
  }
217

    
218
  return $lists[$type];
219
}
220

    
221
/**
222
 * Resets all system_list() caches.
223
 */
224
function system_list_reset() {
225
  drupal_static_reset('system_list');
226
  drupal_static_reset('system_rebuild_module_data');
227
  drupal_static_reset('list_themes');
228
  cache_clear_all('bootstrap_modules', 'cache_bootstrap');
229
  cache_clear_all('system_list', 'cache_bootstrap');
230

    
231
  // Clean up the bootstrap file scan cache.
232
  drupal_static_reset('_drupal_file_scan_cache');
233
  cache_clear_all('_drupal_file_scan_cache', 'cache_bootstrap');
234
}
235

    
236
/**
237
 * Determines which modules require and are required by each module.
238
 *
239
 * @param $files
240
 *   The array of filesystem objects used to rebuild the cache.
241
 *
242
 * @return
243
 *   The same array with the new keys for each module:
244
 *   - requires: An array with the keys being the modules that this module
245
 *     requires.
246
 *   - required_by: An array with the keys being the modules that will not work
247
 *     without this module.
248
 */
249
function _module_build_dependencies($files) {
250
  require_once DRUPAL_ROOT . '/includes/graph.inc';
251
  foreach ($files as $filename => $file) {
252
    $graph[$file->name]['edges'] = array();
253
    if (isset($file->info['dependencies']) && is_array($file->info['dependencies'])) {
254
      foreach ($file->info['dependencies'] as $dependency) {
255
        $dependency_data = drupal_parse_dependency($dependency);
256
        $graph[$file->name]['edges'][$dependency_data['name']] = $dependency_data;
257
      }
258
    }
259
  }
260
  drupal_depth_first_search($graph);
261
  foreach ($graph as $module => $data) {
262
    $files[$module]->required_by = isset($data['reverse_paths']) ? $data['reverse_paths'] : array();
263
    $files[$module]->requires = isset($data['paths']) ? $data['paths'] : array();
264
    $files[$module]->sort = $data['weight'];
265
  }
266
  return $files;
267
}
268

    
269
/**
270
 * Determines whether a given module exists.
271
 *
272
 * @param string $module
273
 *   The name of the module (without the .module extension).
274
 *
275
 * @return bool
276
 *   TRUE if the module is both installed and enabled, FALSE otherwise.
277
 */
278
function module_exists($module) {
279
  $list = module_list();
280
  return isset($list[$module]);
281
}
282

    
283
/**
284
 * Loads a module's installation hooks.
285
 *
286
 * @param $module
287
 *   The name of the module (without the .module extension).
288
 *
289
 * @return
290
 *   The name of the module's install file, if successful; FALSE otherwise.
291
 */
292
function module_load_install($module) {
293
  // Make sure the installation API is available
294
  include_once DRUPAL_ROOT . '/includes/install.inc';
295

    
296
  return module_load_include('install', $module);
297
}
298

    
299
/**
300
 * Loads a module include file.
301
 *
302
 * Examples:
303
 * @code
304
 *   // Load node.admin.inc from the node module.
305
 *   module_load_include('inc', 'node', 'node.admin');
306
 *   // Load content_types.inc from the node module.
307
 *   module_load_include('inc', 'node', 'content_types');
308
 * @endcode
309
 *
310
 * Do not use this function to load an install file, use module_load_install()
311
 * instead. Do not use this function in a global context since it requires
312
 * Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file'
313
 * instead.
314
 *
315
 * @param $type
316
 *   The include file's type (file extension).
317
 * @param $module
318
 *   The module to which the include file belongs.
319
 * @param $name
320
 *   (optional) The base file name (without the $type extension). If omitted,
321
 *   $module is used; i.e., resulting in "$module.$type" by default.
322
 *
323
 * @return
324
 *   The name of the included file, if successful; FALSE otherwise.
325
 */
326
function module_load_include($type, $module, $name = NULL) {
327
  static $files = array();
328

    
329
  if (!isset($name)) {
330
    $name = $module;
331
  }
332

    
333
  $key = $type . ':' . $module . ':' . $name;
334
  if (isset($files[$key])) {
335
    return $files[$key];
336
  }
337

    
338
  if (function_exists('drupal_get_path')) {
339
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
340
    if (is_file($file)) {
341
      require_once $file;
342
      $files[$key] = $file;
343
      return $file;
344
    }
345
    else {
346
      $files[$key] = FALSE;
347
    }
348
  }
349
  return FALSE;
350
}
351

    
352
/**
353
 * Loads an include file for each module enabled in the {system} table.
354
 */
355
function module_load_all_includes($type, $name = NULL) {
356
  $modules = module_list();
357
  foreach ($modules as $module) {
358
    module_load_include($type, $module, $name);
359
  }
360
}
361

    
362
/**
363
 * Enables or installs a given list of modules.
364
 *
365
 * Definitions:
366
 * - "Enabling" is the process of activating a module for use by Drupal.
367
 * - "Disabling" is the process of deactivating a module.
368
 * - "Installing" is the process of enabling it for the first time or after it
369
 *   has been uninstalled.
370
 * - "Uninstalling" is the process of removing all traces of a module.
371
 *
372
 * Order of events:
373
 * - Gather and add module dependencies to $module_list (if applicable).
374
 * - For each module that is being enabled:
375
 *   - Install module schema and update system registries and caches.
376
 *   - If the module is being enabled for the first time or had been
377
 *     uninstalled, invoke hook_install() and add it to the list of installed
378
 *     modules.
379
 *   - Invoke hook_enable().
380
 * - Invoke hook_modules_installed().
381
 * - Invoke hook_modules_enabled().
382
 *
383
 * @param string[] $module_list
384
 *   An array of module names.
385
 * @param bool $enable_dependencies
386
 *   If TRUE, dependencies will automatically be added and enabled in the
387
 *   correct order. This incurs a significant performance cost, so use FALSE
388
 *   if you know $module_list is already complete and in the correct order.
389
 *
390
 * @return bool
391
 *   FALSE if one or more dependencies are missing, TRUE otherwise.
392
 *
393
 * @see hook_install()
394
 * @see hook_enable()
395
 * @see hook_modules_installed()
396
 * @see hook_modules_enabled()
397
 * @see module_disable()
398
 * @see drupal_uninstall_modules()
399
 */
400
function module_enable($module_list, $enable_dependencies = TRUE) {
401
  if ($enable_dependencies) {
402
    // Get all module data so we can find dependencies and sort.
403
    $module_data = system_rebuild_module_data();
404
    // Create an associative array with weights as values.
405
    $module_list = array_flip(array_values($module_list));
406

    
407
    // The array is iterated over manually (instead of using a foreach) because
408
    // modules may be added to the list within the loop and we need to process
409
    // them.
410
    while ($module = key($module_list)) {
411
      next($module_list);
412
      if (!isset($module_data[$module])) {
413
        // This module is not found in the filesystem, abort.
414
        return FALSE;
415
      }
416
      if ($module_data[$module]->status) {
417
        // Skip already enabled modules.
418
        unset($module_list[$module]);
419
        continue;
420
      }
421
      $module_list[$module] = $module_data[$module]->sort;
422

    
423
      // Add dependencies to the list, with a placeholder weight.
424
      // The new modules will be processed as the while loop continues.
425
      foreach (array_keys($module_data[$module]->requires) as $dependency) {
426
        if (!isset($module_list[$dependency])) {
427
          $module_list[$dependency] = 0;
428
        }
429
      }
430
    }
431

    
432
    if (!$module_list) {
433
      // Nothing to do. All modules already enabled.
434
      return TRUE;
435
    }
436

    
437
    // Sort the module list by pre-calculated weights.
438
    arsort($module_list);
439
    $module_list = array_keys($module_list);
440
  }
441

    
442
  // Required for module installation checks.
443
  include_once DRUPAL_ROOT . '/includes/install.inc';
444

    
445
  $modules_installed = array();
446
  $modules_enabled = array();
447
  foreach ($module_list as $module) {
448
    // Only process modules that are not already enabled.
449
    $existing = db_query("SELECT status FROM {system} WHERE type = :type AND name = :name", array(
450
      ':type' => 'module',
451
      ':name' => $module))
452
      ->fetchObject();
453
    if ($existing->status == 0) {
454
      // Load the module's code.
455
      drupal_load('module', $module);
456
      module_load_install($module);
457

    
458
      // Update the database and module list to reflect the new module. This
459
      // needs to be done first so that the module's hook implementations,
460
      // hook_schema() in particular, can be called while it is being
461
      // installed.
462
      db_update('system')
463
        ->fields(array('status' => 1))
464
        ->condition('type', 'module')
465
        ->condition('name', $module)
466
        ->execute();
467
      // Refresh the module list to include it.
468
      system_list_reset();
469
      module_list(TRUE);
470
      module_implements('', FALSE, TRUE);
471
      _system_update_bootstrap_status();
472
      // Update the registry to include it.
473
      registry_update();
474
      // Refresh the schema to include it.
475
      drupal_get_schema(NULL, TRUE);
476
      // Update the theme registry to include it.
477
      drupal_theme_rebuild();
478
      // Clear entity cache.
479
      entity_info_cache_clear();
480

    
481
      // Now install the module if necessary.
482
      if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
483
        drupal_install_schema($module);
484

    
485
        // Set the schema version to the number of the last update provided
486
        // by the module.
487
        $versions = drupal_get_schema_versions($module);
488
        $version = $versions ? max($versions) : SCHEMA_INSTALLED;
489

    
490
        // If the module has no current updates, but has some that were
491
        // previously removed, set the version to the value of
492
        // hook_update_last_removed().
493
        if ($last_removed = module_invoke($module, 'update_last_removed')) {
494
          $version = max($version, $last_removed);
495
        }
496
        drupal_set_installed_schema_version($module, $version);
497
        // Allow the module to perform install tasks.
498
        module_invoke($module, 'install');
499
        // Record the fact that it was installed.
500
        $modules_installed[] = $module;
501
        watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
502
      }
503

    
504
      // Enable the module.
505
      module_invoke($module, 'enable');
506

    
507
      // Record the fact that it was enabled.
508
      $modules_enabled[] = $module;
509
      watchdog('system', '%module module enabled.', array('%module' => $module), WATCHDOG_INFO);
510
    }
511
  }
512

    
513
  // If any modules were newly installed, invoke hook_modules_installed().
514
  if (!empty($modules_installed)) {
515
    module_invoke_all('modules_installed', $modules_installed);
516
  }
517

    
518
  // If any modules were newly enabled, invoke hook_modules_enabled().
519
  if (!empty($modules_enabled)) {
520
    module_invoke_all('modules_enabled', $modules_enabled);
521
  }
522

    
523
  return TRUE;
524
}
525

    
526
/**
527
 * Disables a given set of modules.
528
 *
529
 * @param string[] $module_list
530
 *   An array of module names.
531
 * @param bool $disable_dependents
532
 *   If TRUE, dependent modules will automatically be added and disabled in the
533
 *   correct order. This incurs a significant performance cost, so use FALSE
534
 *   if you know $module_list is already complete and in the correct order.
535
 *
536
 * @see drupal_uninstall_modules()
537
 * @see module_enable()
538
 */
539
function module_disable($module_list, $disable_dependents = TRUE) {
540
  if ($disable_dependents) {
541
    // Get all module data so we can find dependents and sort.
542
    $module_data = system_rebuild_module_data();
543
    // Create an associative array with weights as values.
544
    $module_list = array_flip(array_values($module_list));
545

    
546
    $profile = drupal_get_profile();
547
    // The array is iterated over manually (instead of using a foreach) because
548
    // modules may be added to the list within the loop and we need to process
549
    // them.
550
    while ($module = key($module_list)) {
551
      next($module_list);
552
      if (!isset($module_data[$module]) || !$module_data[$module]->status) {
553
        // This module doesn't exist or is already disabled, skip it.
554
        unset($module_list[$module]);
555
        continue;
556
      }
557
      $module_list[$module] = $module_data[$module]->sort;
558

    
559
      // Add dependent modules to the list, with a placeholder weight.
560
      // The new modules will be processed as the while loop continues.
561
      foreach ($module_data[$module]->required_by as $dependent => $dependent_data) {
562
        if (!isset($module_list[$dependent]) && $dependent != $profile) {
563
          $module_list[$dependent] = 0;
564
        }
565
      }
566
    }
567

    
568
    // Sort the module list by pre-calculated weights.
569
    asort($module_list);
570
    $module_list = array_keys($module_list);
571
  }
572

    
573
  $invoke_modules = array();
574

    
575
  foreach ($module_list as $module) {
576
    if (module_exists($module)) {
577
      // Check if node_access table needs rebuilding.
578
      if (!node_access_needs_rebuild() && module_hook($module, 'node_grants')) {
579
        node_access_needs_rebuild(TRUE);
580
      }
581

    
582
      module_load_install($module);
583
      module_invoke($module, 'disable');
584
      db_update('system')
585
        ->fields(array('status' => 0))
586
        ->condition('type', 'module')
587
        ->condition('name', $module)
588
        ->execute();
589
      $invoke_modules[] = $module;
590
      watchdog('system', '%module module disabled.', array('%module' => $module), WATCHDOG_INFO);
591
    }
592
  }
593

    
594
  if (!empty($invoke_modules)) {
595
    // Refresh the module list to exclude the disabled modules.
596
    system_list_reset();
597
    module_list(TRUE);
598
    module_implements('', FALSE, TRUE);
599
    entity_info_cache_clear();
600
    // Invoke hook_modules_disabled before disabling modules,
601
    // so we can still call module hooks to get information.
602
    module_invoke_all('modules_disabled', $invoke_modules);
603
    // Update the registry to remove the newly-disabled module.
604
    registry_update();
605
    _system_update_bootstrap_status();
606
    // Update the theme registry to remove the newly-disabled module.
607
    drupal_theme_rebuild();
608
  }
609

    
610
  // If there remains no more node_access module, rebuilding will be
611
  // straightforward, we can do it right now.
612
  if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
613
    node_access_rebuild();
614
  }
615
}
616

    
617
/**
618
 * @defgroup hooks Hooks
619
 * @{
620
 * Allow modules to interact with the Drupal core.
621
 *
622
 * Drupal's module system is based on the concept of "hooks". A hook is a PHP
623
 * function that is named foo_bar(), where "foo" is the name of the module
624
 * (whose filename is thus foo.module) and "bar" is the name of the hook. Each
625
 * hook has a defined set of parameters and a specified result type.
626
 *
627
 * To extend Drupal, a module need simply implement a hook. When Drupal wishes
628
 * to allow intervention from modules, it determines which modules implement a
629
 * hook and calls that hook in all enabled modules that implement it.
630
 *
631
 * The available hooks to implement are explained here in the Hooks section of
632
 * the developer documentation. The string "hook" is used as a placeholder for
633
 * the module name in the hook definitions. For example, if the module file is
634
 * called example.module, then hook_help() as implemented by that module would
635
 * be defined as example_help().
636
 *
637
 * The example functions included are not part of the Drupal core, they are
638
 * just models that you can modify. Only the hooks implemented within modules
639
 * are executed when running Drupal.
640
 *
641
 * @see themeable
642
 * @see callbacks
643
 */
644

    
645
 /**
646
  * @defgroup callbacks Callbacks
647
  * @{
648
  * Callback function signatures.
649
  *
650
  * Drupal's API sometimes uses callback functions to allow you to define how
651
  * some type of processing happens. A callback is a function with a defined
652
  * signature, which you define in a module. Then you pass the function name as
653
  * a parameter to a Drupal API function or return it as part of a hook
654
  * implementation return value, and your function is called at an appropriate
655
  * time. For instance, when setting up batch processing you might need to
656
  * provide a callback function for each processing step and/or a callback for
657
  * when processing is finished; you would do that by defining these functions
658
  * and passing their names into the batch setup function.
659
  *
660
  * Callback function signatures, like hook definitions, are described by
661
  * creating and documenting dummy functions in a *.api.php file; normally, the
662
  * dummy callback function's name should start with "callback_", and you should
663
  * document the parameters and return value and provide a sample function body.
664
  * Then your API documentation can refer to this callback function in its
665
  * documentation. A user of your API can usually name their callback function
666
  * anything they want, although a standard name would be to replace "callback_"
667
  * with the module name.
668
  *
669
  * @see hooks
670
  * @see themeable
671
  *
672
  * @}
673
  */
674

    
675
/**
676
 * Determines whether a module implements a hook.
677
 *
678
 * @param $module
679
 *   The name of the module (without the .module extension).
680
 * @param $hook
681
 *   The name of the hook (e.g. "help" or "menu").
682
 *
683
 * @return
684
 *   TRUE if the module is both installed and enabled, and the hook is
685
 *   implemented in that module.
686
 */
687
function module_hook($module, $hook) {
688
  $function = $module . '_' . $hook;
689
  if (function_exists($function)) {
690
    return TRUE;
691
  }
692
  // If the hook implementation does not exist, check whether it may live in an
693
  // optional include file registered via hook_hook_info().
694
  $hook_info = module_hook_info();
695
  if (isset($hook_info[$hook]['group'])) {
696
    module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
697
    if (function_exists($function)) {
698
      return TRUE;
699
    }
700
  }
701
  return FALSE;
702
}
703

    
704
/**
705
 * Determines which modules are implementing a hook.
706
 *
707
 * Lazy-loaded include files specified with "group" via hook_hook_info() or
708
 * hook_module_implements_alter() will be automatically included by this
709
 * function when necessary.
710
 *
711
 * @param string $hook
712
 *   The name of the hook (e.g. "help" or "menu").
713
 * @param bool $sort
714
 *   By default, modules are ordered by weight and filename, settings this option
715
 *   to TRUE, module list will be ordered by module name.
716
 * @param bool $reset
717
 *   For internal use only: Whether to force the stored list of hook
718
 *   implementations to be regenerated (such as after enabling a new module,
719
 *   before processing hook_enable).
720
 *
721
 * @return
722
 *   An array with the names of the modules which are implementing this hook.
723
 *
724
 * @see module_implements_write_cache()
725
 */
726
function module_implements($hook, $sort = FALSE, $reset = FALSE) {
727
  // Use the advanced drupal_static() pattern, since this is called very often.
728
  static $drupal_static_fast;
729
  if (!isset($drupal_static_fast)) {
730
    $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
731
    $drupal_static_fast['verified'] = &drupal_static(__FUNCTION__ . ':verified');
732
  }
733
  $implementations = &$drupal_static_fast['implementations'];
734
  $verified = &$drupal_static_fast['verified'];
735

    
736
  // We maintain a persistent cache of hook implementations in addition to the
737
  // static cache to avoid looping through every module and every hook on each
738
  // request. Benchmarks show that the benefit of this caching outweighs the
739
  // additional database hit even when using the default database caching
740
  // backend and only a small number of modules are enabled. The cost of the
741
  // cache_get() is more or less constant and reduced further when non-database
742
  // caching backends are used, so there will be more significant gains when a
743
  // large number of modules are installed or hooks invoked, since this can
744
  // quickly lead to module_hook() being called several thousand times
745
  // per request.
746
  if ($reset) {
747
    $implementations = array();
748
    $verified = array();
749
    cache_set('module_implements', array(), 'cache_bootstrap');
750
    drupal_static_reset('module_hook_info');
751
    drupal_static_reset('drupal_alter');
752
    cache_clear_all('hook_info', 'cache_bootstrap');
753
    cache_clear_all('system_cache_tables', 'cache');
754
    return;
755
  }
756

    
757
  // Fetch implementations from cache.
758
  // This happens on the first call to module_implements(*, *, FALSE) during a
759
  // request, but also when $implementations have been reset, e.g. after
760
  // module_enable().
761
  if (empty($implementations)) {
762
    $implementations = cache_get('module_implements', 'cache_bootstrap');
763
    if ($implementations === FALSE) {
764
      $implementations = array();
765
    }
766
    else {
767
      $implementations = $implementations->data;
768
    }
769
    // Forget all previously "verified" hooks, in case that $implementations
770
    // were cleared via drupal_static_reset('module_implements') instead of
771
    // module_implements(*, *, TRUE).
772
    $verified = array();
773
  }
774

    
775
  if (!isset($implementations[$hook])) {
776
    // The hook is not cached, so ensure that whether or not it has
777
    // implementations, that the cache is updated at the end of the request.
778
    $implementations['#write_cache'] = TRUE;
779
    // Discover implementations for this hook.
780
    $hook_info = module_hook_info();
781
    $implementations[$hook] = array();
782
    $list = module_list(FALSE, FALSE, $sort);
783
    foreach ($list as $module) {
784
      $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
785
      // Since module_hook() may needlessly try to load the include file again,
786
      // function_exists() is used directly here.
787
      if (function_exists($module . '_' . $hook)) {
788
        $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
789
      }
790
    }
791
    // Allow modules to change the weight of specific implementations, but avoid
792
    // an infinite loop.
793
    if ($hook != 'module_implements_alter') {
794
      // Remember the implementations before hook_module_implements_alter().
795
      $implementations_before = $implementations[$hook];
796
      drupal_alter('module_implements', $implementations[$hook], $hook);
797
      // Verify implementations that were added or modified.
798
      foreach (array_diff_assoc($implementations[$hook], $implementations_before) as $module => $group) {
799
        // If drupal_alter('module_implements') changed or added a $group, the
800
        // respective file needs to be included.
801
        if ($group) {
802
          module_load_include('inc', $module, "$module.$group");
803
        }
804
        // If a new implementation was added, verify that the function exists.
805
        if (!function_exists($module . '_' . $hook)) {
806
          unset($implementations[$hook][$module]);
807
        }
808
      }
809
    }
810
    // Implementations for this hook are now "verified".
811
    $verified[$hook] = TRUE;
812
  }
813
  elseif (!isset($verified[$hook])) {
814
    // Implementations for this hook were in the cache, but they are not
815
    // "verified" yet.
816
    foreach ($implementations[$hook] as $module => $group) {
817
      // If this hook implementation is stored in a lazy-loaded file, so include
818
      // that file first.
819
      if ($group) {
820
        module_load_include('inc', $module, "$module.$group");
821
      }
822
      // It is possible that a module removed a hook implementation without the
823
      // implementations cache being rebuilt yet, so we check whether the
824
      // function exists on each request to avoid undefined function errors.
825
      // Since module_hook() may needlessly try to load the include file again,
826
      // function_exists() is used directly here.
827
      if (!function_exists($module . '_' . $hook)) {
828
        // Clear out the stale implementation from the cache and force a cache
829
        // refresh to forget about no longer existing hook implementations.
830
        unset($implementations[$hook][$module]);
831
        $implementations['#write_cache'] = TRUE;
832
      }
833
    }
834
    $verified[$hook] = TRUE;
835
  }
836

    
837
  return array_keys($implementations[$hook]);
838
}
839

    
840
/**
841
 * Retrieves a list of hooks that are declared through hook_hook_info().
842
 *
843
 * @return
844
 *   An associative array whose keys are hook names and whose values are an
845
 *   associative array containing a group name. The structure of the array
846
 *   is the same as the return value of hook_hook_info().
847
 *
848
 * @see hook_hook_info()
849
 */
850
function module_hook_info() {
851
  // This function is indirectly invoked from bootstrap_invoke_all(), in which
852
  // case common.inc, subsystems, and modules are not loaded yet, so it does not
853
  // make sense to support hook groups resp. lazy-loaded include files prior to
854
  // full bootstrap.
855
  if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
856
    return array();
857
  }
858
  $hook_info = &drupal_static(__FUNCTION__);
859

    
860
  if (!isset($hook_info)) {
861
    $hook_info = array();
862
    $cache = cache_get('hook_info', 'cache_bootstrap');
863
    if ($cache === FALSE) {
864
      // Rebuild the cache and save it.
865
      // We can't use module_invoke_all() here or it would cause an infinite
866
      // loop.
867
      foreach (module_list() as $module) {
868
        $function = $module . '_hook_info';
869
        if (function_exists($function)) {
870
          $result = $function();
871
          if (isset($result) && is_array($result)) {
872
            $hook_info = array_merge_recursive($hook_info, $result);
873
          }
874
        }
875
      }
876
      // We can't use drupal_alter() for the same reason as above.
877
      foreach (module_list() as $module) {
878
        $function = $module . '_hook_info_alter';
879
        if (function_exists($function)) {
880
          $function($hook_info);
881
        }
882
      }
883
      cache_set('hook_info', $hook_info, 'cache_bootstrap');
884
    }
885
    else {
886
      $hook_info = $cache->data;
887
    }
888
  }
889

    
890
  return $hook_info;
891
}
892

    
893
/**
894
 * Writes the hook implementation cache.
895
 *
896
 * @see module_implements()
897
 */
898
function module_implements_write_cache() {
899
  // The list of implementations includes vital modules only before full
900
  // bootstrap, so do not write cache if we are not fully bootstrapped yet.
901
  if (drupal_get_bootstrap_phase() != DRUPAL_BOOTSTRAP_FULL) {
902
    return;
903
  }
904
  $implementations = &drupal_static('module_implements');
905
  if (isset($implementations['#write_cache'])) {
906
    unset($implementations['#write_cache']);
907
    cache_set('module_implements', $implementations, 'cache_bootstrap');
908
  }
909
}
910

    
911
/**
912
 * Invokes a hook in a particular module.
913
 *
914
 * All arguments are passed by value. Use drupal_alter() if you need to pass
915
 * arguments by reference.
916
 *
917
 * @param $module
918
 *   The name of the module (without the .module extension).
919
 * @param $hook
920
 *   The name of the hook to invoke.
921
 * @param ...
922
 *   Arguments to pass to the hook implementation.
923
 *
924
 * @return
925
 *   The return value of the hook implementation.
926
 *
927
 * @see drupal_alter()
928
 */
929
function module_invoke($module, $hook) {
930
  $args = func_get_args();
931
  // Remove $module and $hook from the arguments.
932
  unset($args[0], $args[1]);
933
  if (module_hook($module, $hook)) {
934
    return call_user_func_array($module . '_' . $hook, $args);
935
  }
936
}
937

    
938
/**
939
 * Invokes a hook in all enabled modules that implement it.
940
 *
941
 * All arguments are passed by value. Use drupal_alter() if you need to pass
942
 * arguments by reference.
943
 *
944
 * @param $hook
945
 *   The name of the hook to invoke.
946
 * @param ...
947
 *   Arguments to pass to the hook.
948
 *
949
 * @return
950
 *   An array of return values of the hook implementations. If modules return
951
 *   arrays from their implementations, those are merged into one array
952
 *   recursively. Note: integer keys in arrays will be lost, as the merge is
953
 *   done using array_merge_recursive().
954
 *
955
 * @see drupal_alter()
956
 */
957
function module_invoke_all($hook) {
958
  $args = func_get_args();
959
  // Remove $hook from the arguments.
960
  unset($args[0]);
961
  $return = array();
962
  foreach (module_implements($hook) as $module) {
963
    $function = $module . '_' . $hook;
964
    if (function_exists($function)) {
965
      $result = call_user_func_array($function, $args);
966
      if (isset($result) && is_array($result)) {
967
        $return = array_merge_recursive($return, $result);
968
      }
969
      elseif (isset($result)) {
970
        $return[] = $result;
971
      }
972
    }
973
  }
974

    
975
  return $return;
976
}
977

    
978
/**
979
 * @} End of "defgroup hooks".
980
 */
981

    
982
/**
983
 * Returns an array of modules required by core.
984
 */
985
function drupal_required_modules() {
986
  $files = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', 'modules', 'name', 0);
987
  $required = array();
988

    
989
  // An installation profile is required and one must always be loaded.
990
  $required[] = drupal_get_profile();
991

    
992
  foreach ($files as $name => $file) {
993
    $info = drupal_parse_info_file($file->uri);
994
    if (!empty($info) && !empty($info['required']) && $info['required']) {
995
      $required[] = $name;
996
    }
997
  }
998

    
999
  return $required;
1000
}
1001

    
1002
/**
1003
 * Passes alterable variables to specific hook_TYPE_alter() implementations.
1004
 *
1005
 * This dispatch function hands off the passed-in variables to type-specific
1006
 * hook_TYPE_alter() implementations in modules. It ensures a consistent
1007
 * interface for all altering operations.
1008
 *
1009
 * A maximum of 2 alterable arguments is supported (a third is supported for
1010
 * legacy reasons, but should not be used in new code). In case more arguments
1011
 * need to be passed and alterable, modules provide additional variables
1012
 * assigned by reference in the last $context argument:
1013
 * @code
1014
 *   $context = array(
1015
 *     'alterable' => &$alterable,
1016
 *     'unalterable' => $unalterable,
1017
 *     'foo' => 'bar',
1018
 *   );
1019
 *   drupal_alter('mymodule_data', $alterable1, $alterable2, $context);
1020
 * @endcode
1021
 *
1022
 * Note that objects are always passed by reference in PHP5. If it is absolutely
1023
 * required that no implementation alters a passed object in $context, then an
1024
 * object needs to be cloned:
1025
 * @code
1026
 *   $context = array(
1027
 *     'unalterable_object' => clone $object,
1028
 *   );
1029
 *   drupal_alter('mymodule_data', $data, $context);
1030
 * @endcode
1031
 *
1032
 * @param $type
1033
 *   A string describing the type of the alterable $data. 'form', 'links',
1034
 *   'node_content', and so on are several examples. Alternatively can be an
1035
 *   array, in which case hook_TYPE_alter() is invoked for each value in the
1036
 *   array, ordered first by module, and then for each module, in the order of
1037
 *   values in $type. For example, when Form API is using drupal_alter() to
1038
 *   execute both hook_form_alter() and hook_form_FORM_ID_alter()
1039
 *   implementations, it passes array('form', 'form_' . $form_id) for $type.
1040
 * @param $data
1041
 *   The variable that will be passed to hook_TYPE_alter() implementations to be
1042
 *   altered. The type of this variable depends on the value of the $type
1043
 *   argument. For example, when altering a 'form', $data will be a structured
1044
 *   array. When altering a 'profile', $data will be an object.
1045
 * @param $context1
1046
 *   (optional) An additional variable that is passed by reference.
1047
 * @param $context2
1048
 *   (optional) An additional variable that is passed by reference. If more
1049
 *   context needs to be provided to implementations, then this should be an
1050
 *   associative array as described above.
1051
 * @param $context3
1052
 *   (optional) An additional variable that is passed by reference. This
1053
 *   parameter is deprecated and will not exist in Drupal 8; consequently, it
1054
 *   should not be used for new Drupal 7 code either. It is here only for
1055
 *   backwards compatibility with older code that passed additional arguments
1056
 *   to drupal_alter().
1057
 */
1058
function drupal_alter($type, &$data, &$context1 = NULL, &$context2 = NULL, &$context3 = NULL) {
1059
  // Use the advanced drupal_static() pattern, since this is called very often.
1060
  static $drupal_static_fast;
1061
  if (!isset($drupal_static_fast)) {
1062
    $drupal_static_fast['functions'] = &drupal_static(__FUNCTION__);
1063
  }
1064
  $functions = &$drupal_static_fast['functions'];
1065

    
1066
  // Most of the time, $type is passed as a string, so for performance,
1067
  // normalize it to that. When passed as an array, usually the first item in
1068
  // the array is a generic type, and additional items in the array are more
1069
  // specific variants of it, as in the case of array('form', 'form_FORM_ID').
1070
  if (is_array($type)) {
1071
    $cid = implode(',', $type);
1072
    $extra_types = $type;
1073
    $type = array_shift($extra_types);
1074
    // Allow if statements in this function to use the faster isset() rather
1075
    // than !empty() both when $type is passed as a string, or as an array with
1076
    // one item.
1077
    if (empty($extra_types)) {
1078
      unset($extra_types);
1079
    }
1080
  }
1081
  else {
1082
    $cid = $type;
1083
  }
1084

    
1085
  // Some alter hooks are invoked many times per page request, so statically
1086
  // cache the list of functions to call, and on subsequent calls, iterate
1087
  // through them quickly.
1088
  if (!isset($functions[$cid])) {
1089
    $functions[$cid] = array();
1090
    $hook = $type . '_alter';
1091
    $modules = module_implements($hook);
1092
    if (!isset($extra_types)) {
1093
      // For the more common case of a single hook, we do not need to call
1094
      // function_exists(), since module_implements() returns only modules with
1095
      // implementations.
1096
      foreach ($modules as $module) {
1097
        $functions[$cid][] = $module . '_' . $hook;
1098
      }
1099
    }
1100
    else {
1101
      // For multiple hooks, we need $modules to contain every module that
1102
      // implements at least one of them.
1103
      $extra_modules = array();
1104
      foreach ($extra_types as $extra_type) {
1105
        $extra_modules = array_merge($extra_modules, module_implements($extra_type . '_alter'));
1106
      }
1107
      // If any modules implement one of the extra hooks that do not implement
1108
      // the primary hook, we need to add them to the $modules array in their
1109
      // appropriate order. module_implements() can only return ordered
1110
      // implementations of a single hook. To get the ordered implementations
1111
      // of multiple hooks, we mimic the module_implements() logic of first
1112
      // ordering by module_list(), and then calling
1113
      // drupal_alter('module_implements').
1114
      if (array_diff($extra_modules, $modules)) {
1115
        // Merge the arrays and order by module_list().
1116
        $modules = array_intersect(module_list(), array_merge($modules, $extra_modules));
1117
        // Since module_implements() already took care of loading the necessary
1118
        // include files, we can safely pass FALSE for the array values.
1119
        $implementations = array_fill_keys($modules, FALSE);
1120
        // Let modules adjust the order solely based on the primary hook. This
1121
        // ensures the same module order regardless of whether this if block
1122
        // runs. Calling drupal_alter() recursively in this way does not result
1123
        // in an infinite loop, because this call is for a single $type, so we
1124
        // won't end up in this code block again.
1125
        drupal_alter('module_implements', $implementations, $hook);
1126
        $modules = array_keys($implementations);
1127
      }
1128
      foreach ($modules as $module) {
1129
        // Since $modules is a merged array, for any given module, we do not
1130
        // know whether it has any particular implementation, so we need a
1131
        // function_exists().
1132
        $function = $module . '_' . $hook;
1133
        if (function_exists($function)) {
1134
          $functions[$cid][] = $function;
1135
        }
1136
        foreach ($extra_types as $extra_type) {
1137
          $function = $module . '_' . $extra_type . '_alter';
1138
          if (function_exists($function)) {
1139
            $functions[$cid][] = $function;
1140
          }
1141
        }
1142
      }
1143
    }
1144
    // Allow the theme to alter variables after the theme system has been
1145
    // initialized.
1146
    global $theme, $base_theme_info;
1147
    if (isset($theme)) {
1148
      $theme_keys = array();
1149
      foreach ($base_theme_info as $base) {
1150
        $theme_keys[] = $base->name;
1151
      }
1152
      $theme_keys[] = $theme;
1153
      foreach ($theme_keys as $theme_key) {
1154
        $function = $theme_key . '_' . $hook;
1155
        if (function_exists($function)) {
1156
          $functions[$cid][] = $function;
1157
        }
1158
        if (isset($extra_types)) {
1159
          foreach ($extra_types as $extra_type) {
1160
            $function = $theme_key . '_' . $extra_type . '_alter';
1161
            if (function_exists($function)) {
1162
              $functions[$cid][] = $function;
1163
            }
1164
          }
1165
        }
1166
      }
1167
    }
1168
  }
1169

    
1170
  foreach ($functions[$cid] as $function) {
1171
    $function($data, $context1, $context2, $context3);
1172
  }
1173
}