module.inc

  1. 7.x drupal/includes/module.inc
  2. 5.x drupal/includes/module.inc
  3. 6.x drupal/includes/module.inc
  4. 8.x drupal/core/includes/module.inc

API for loading and interacting with Drupal modules.

Functions

Namesort descending Description
drupal_alter Passes alterable variables to specific hook_TYPE_alter() implementations.
drupal_required_modules Returns an array of modules required by core.
module_disable Disables a given set of modules.
module_enable Enables or installs a given list of modules.
module_exists Determines whether a given module exists.
module_hook Determines whether a module implements a hook.
module_hook_info Retrieves a list of hooks that are declared through hook_hook_info().
module_implements Determines which modules are implementing a hook.
module_implements_write_cache Writes the hook implementation cache.
module_invoke Invokes a hook in a particular module.
module_invoke_all Invokes a hook in all enabled modules that implement it.
module_list Returns a list of currently active modules.
module_load_all Loads all the modules that have been enabled in the system table.
module_load_all_includes Loads an include file for each module enabled in the {system} table.
module_load_include Loads a module include file.
module_load_install Loads a module's installation hooks.
system_list Builds a list of bootstrap modules and enabled modules and themes.
system_list_reset Resets all system_list() caches.
_module_build_dependencies Determines which modules require and are required by each module.

File

drupal/includes/module.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API for loading and interacting with Drupal modules.
  5. */
  6. /**
  7. * Loads all the modules that have been enabled in the system table.
  8. *
  9. * @param $bootstrap
  10. * Whether to load only the reduced set of modules loaded in "bootstrap mode"
  11. * for cached pages. See bootstrap.inc.
  12. *
  13. * @return
  14. * If $bootstrap is NULL, return a boolean indicating whether all modules
  15. * have been loaded.
  16. */
  17. function module_load_all($bootstrap = FALSE) {
  18. static $has_run = FALSE;
  19. if (isset($bootstrap)) {
  20. foreach (module_list(TRUE, $bootstrap) as $module) {
  21. drupal_load('module', $module);
  22. }
  23. // $has_run will be TRUE if $bootstrap is FALSE.
  24. $has_run = !$bootstrap;
  25. }
  26. return $has_run;
  27. }
  28. /**
  29. * Returns a list of currently active modules.
  30. *
  31. * Usually, this returns a list of all enabled modules. When called early on in
  32. * the bootstrap, it will return a list of vital modules only (those needed to
  33. * generate cached pages).
  34. *
  35. * All parameters to this function are optional and should generally not be
  36. * changed from their defaults.
  37. *
  38. * @param $refresh
  39. * (optional) Whether to force the module list to be regenerated (such as
  40. * after the administrator has changed the system settings). Defaults to
  41. * FALSE.
  42. * @param $bootstrap_refresh
  43. * (optional) When $refresh is TRUE, setting $bootstrap_refresh to TRUE forces
  44. * the module list to be regenerated using the reduced set of modules loaded
  45. * in "bootstrap mode" for cached pages. Otherwise, setting $refresh to TRUE
  46. * generates the complete list of enabled modules.
  47. * @param $sort
  48. * (optional) By default, modules are ordered by weight and module name. Set
  49. * this option to TRUE to return a module list ordered only by module name.
  50. * @param $fixed_list
  51. * (optional) If an array of module names is provided, this will override the
  52. * module list with the given set of modules. This will persist until the next
  53. * call with $refresh set to TRUE or with a new $fixed_list passed in. This
  54. * parameter is primarily intended for internal use (e.g., in install.php and
  55. * update.php).
  56. *
  57. * @return
  58. * An associative array whose keys and values are the names of the modules in
  59. * the list.
  60. */
  61. function module_list($refresh = FALSE, $bootstrap_refresh = FALSE, $sort = FALSE, $fixed_list = NULL) {
  62. static $list = array(), $sorted_list;
  63. if (empty($list) || $refresh || $fixed_list) {
  64. $list = array();
  65. $sorted_list = NULL;
  66. if ($fixed_list) {
  67. foreach ($fixed_list as $name => $module) {
  68. drupal_get_filename('module', $name, $module['filename']);
  69. $list[$name] = $name;
  70. }
  71. }
  72. else {
  73. if ($refresh) {
  74. // For the $refresh case, make sure that system_list() returns fresh
  75. // data.
  76. drupal_static_reset('system_list');
  77. }
  78. if ($bootstrap_refresh) {
  79. $list = system_list('bootstrap');
  80. }
  81. else {
  82. // Not using drupal_map_assoc() here as that requires common.inc.
  83. $list = array_keys(system_list('module_enabled'));
  84. $list = (!empty($list) ? array_combine($list, $list) : array());
  85. }
  86. }
  87. }
  88. if ($sort) {
  89. if (!isset($sorted_list)) {
  90. $sorted_list = $list;
  91. ksort($sorted_list);
  92. }
  93. return $sorted_list;
  94. }
  95. return $list;
  96. }
  97. /**
  98. * Builds a list of bootstrap modules and enabled modules and themes.
  99. *
  100. * @param $type
  101. * The type of list to return:
  102. * - module_enabled: All enabled modules.
  103. * - bootstrap: All enabled modules required for bootstrap.
  104. * - theme: All themes.
  105. *
  106. * @return
  107. * An associative array of modules or themes, keyed by name. For $type
  108. * 'bootstrap', the array values equal the keys. For $type 'module_enabled'
  109. * or 'theme', the array values are objects representing the respective
  110. * database row, with the 'info' property already unserialized.
  111. *
  112. * @see module_list()
  113. * @see list_themes()
  114. */
  115. function system_list($type) {
  116. $lists = &drupal_static(__FUNCTION__);
  117. // For bootstrap modules, attempt to fetch the list from cache if possible.
  118. // if not fetch only the required information to fire bootstrap hooks
  119. // in case we are going to serve the page from cache.
  120. if ($type == 'bootstrap') {
  121. if (isset($lists['bootstrap'])) {
  122. return $lists['bootstrap'];
  123. }
  124. if ($cached = cache_get('bootstrap_modules', 'cache_bootstrap')) {
  125. $bootstrap_list = $cached->data;
  126. }
  127. else {
  128. $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');
  129. cache_set('bootstrap_modules', $bootstrap_list, 'cache_bootstrap');
  130. }
  131. // To avoid a separate database lookup for the filepath, prime the
  132. // drupal_get_filename() static cache for bootstrap modules only.
  133. // The rest is stored separately to keep the bootstrap module cache small.
  134. foreach ($bootstrap_list as $module) {
  135. drupal_get_filename('module', $module->name, $module->filename);
  136. }
  137. // We only return the module names here since module_list() doesn't need
  138. // the filename itself.
  139. $lists['bootstrap'] = array_keys($bootstrap_list);
  140. }
  141. // Otherwise build the list for enabled modules and themes.
  142. elseif (!isset($lists['module_enabled'])) {
  143. if ($cached = cache_get('system_list', 'cache_bootstrap')) {
  144. $lists = $cached->data;
  145. }
  146. else {
  147. $lists = array(
  148. 'module_enabled' => array(),
  149. 'theme' => array(),
  150. 'filepaths' => array(),
  151. );
  152. // The module name (rather than the filename) is used as the fallback
  153. // weighting in order to guarantee consistent behavior across different
  154. // Drupal installations, which might have modules installed in different
  155. // locations in the file system. The ordering here must also be
  156. // consistent with the one used in module_implements().
  157. $result = db_query("SELECT * FROM {system} WHERE type = 'theme' OR (type = 'module' AND status = 1) ORDER BY weight ASC, name ASC");
  158. foreach ($result as $record) {
  159. $record->info = unserialize($record->info);
  160. // Build a list of all enabled modules.
  161. if ($record->type == 'module') {
  162. $lists['module_enabled'][$record->name] = $record;
  163. }
  164. // Build a list of themes.
  165. if ($record->type == 'theme') {
  166. $lists['theme'][$record->name] = $record;
  167. }
  168. // Build a list of filenames so drupal_get_filename can use it.
  169. if ($record->status) {
  170. $lists['filepaths'][] = array('type' => $record->type, 'name' => $record->name, 'filepath' => $record->filename);
  171. }
  172. }
  173. foreach ($lists['theme'] as $key => $theme) {
  174. if (!empty($theme->info['base theme'])) {
  175. // Make a list of the theme's base themes.
  176. require_once DRUPAL_ROOT . '/includes/theme.inc';
  177. $lists['theme'][$key]->base_themes = drupal_find_base_themes($lists['theme'], $key);
  178. // Don't proceed if there was a problem with the root base theme.
  179. if (!current($lists['theme'][$key]->base_themes)) {
  180. continue;
  181. }
  182. // Determine the root base theme.
  183. $base_key = key($lists['theme'][$key]->base_themes);
  184. // Add to the list of sub-themes for each of the theme's base themes.
  185. foreach (array_keys($lists['theme'][$key]->base_themes) as $base_theme) {
  186. $lists['theme'][$base_theme]->sub_themes[$key] = $lists['theme'][$key]->info['name'];
  187. }
  188. // Add the base theme's theme engine info.
  189. $lists['theme'][$key]->info['engine'] = isset($lists['theme'][$base_key]->info['engine']) ? $lists['theme'][$base_key]->info['engine'] : 'theme';
  190. }
  191. else {
  192. // A plain theme is its own engine.
  193. $base_key = $key;
  194. if (!isset($lists['theme'][$key]->info['engine'])) {
  195. $lists['theme'][$key]->info['engine'] = 'theme';
  196. }
  197. }
  198. // Set the theme engine prefix.
  199. $lists['theme'][$key]->prefix = ($lists['theme'][$key]->info['engine'] == 'theme') ? $base_key : $lists['theme'][$key]->info['engine'];
  200. }
  201. cache_set('system_list', $lists, 'cache_bootstrap');
  202. }
  203. // To avoid a separate database lookup for the filepath, prime the
  204. // drupal_get_filename() static cache with all enabled modules and themes.
  205. foreach ($lists['filepaths'] as $item) {
  206. drupal_get_filename($item['type'], $item['name'], $item['filepath']);
  207. }
  208. }
  209. return $lists[$type];
  210. }
  211. /**
  212. * Resets all system_list() caches.
  213. */
  214. function system_list_reset() {
  215. drupal_static_reset('system_list');
  216. drupal_static_reset('system_rebuild_module_data');
  217. drupal_static_reset('list_themes');
  218. cache_clear_all('bootstrap_modules', 'cache_bootstrap');
  219. cache_clear_all('system_list', 'cache_bootstrap');
  220. }
  221. /**
  222. * Determines which modules require and are required by each module.
  223. *
  224. * @param $files
  225. * The array of filesystem objects used to rebuild the cache.
  226. *
  227. * @return
  228. * The same array with the new keys for each module:
  229. * - requires: An array with the keys being the modules that this module
  230. * requires.
  231. * - required_by: An array with the keys being the modules that will not work
  232. * without this module.
  233. */
  234. function _module_build_dependencies($files) {
  235. require_once DRUPAL_ROOT . '/includes/graph.inc';
  236. foreach ($files as $filename => $file) {
  237. $graph[$file->name]['edges'] = array();
  238. if (isset($file->info['dependencies']) && is_array($file->info['dependencies'])) {
  239. foreach ($file->info['dependencies'] as $dependency) {
  240. $dependency_data = drupal_parse_dependency($dependency);
  241. $graph[$file->name]['edges'][$dependency_data['name']] = $dependency_data;
  242. }
  243. }
  244. }
  245. drupal_depth_first_search($graph);
  246. foreach ($graph as $module => $data) {
  247. $files[$module]->required_by = isset($data['reverse_paths']) ? $data['reverse_paths'] : array();
  248. $files[$module]->requires = isset($data['paths']) ? $data['paths'] : array();
  249. $files[$module]->sort = $data['weight'];
  250. }
  251. return $files;
  252. }
  253. /**
  254. * Determines whether a given module exists.
  255. *
  256. * @param $module
  257. * The name of the module (without the .module extension).
  258. *
  259. * @return
  260. * TRUE if the module is both installed and enabled.
  261. */
  262. function module_exists($module) {
  263. $list = module_list();
  264. return isset($list[$module]);
  265. }
  266. /**
  267. * Loads a module's installation hooks.
  268. *
  269. * @param $module
  270. * The name of the module (without the .module extension).
  271. *
  272. * @return
  273. * The name of the module's install file, if successful; FALSE otherwise.
  274. */
  275. function module_load_install($module) {
  276. // Make sure the installation API is available
  277. include_once DRUPAL_ROOT . '/includes/install.inc';
  278. return module_load_include('install', $module);
  279. }
  280. /**
  281. * Loads a module include file.
  282. *
  283. * Examples:
  284. * @code
  285. * // Load node.admin.inc from the node module.
  286. * module_load_include('inc', 'node', 'node.admin');
  287. * // Load content_types.inc from the node module.
  288. * module_load_include('inc', 'node', 'content_types');
  289. * @endcode
  290. *
  291. * Do not use this function to load an install file, use module_load_install()
  292. * instead. Do not use this function in a global context since it requires
  293. * Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file'
  294. * instead.
  295. *
  296. * @param $type
  297. * The include file's type (file extension).
  298. * @param $module
  299. * The module to which the include file belongs.
  300. * @param $name
  301. * (optional) The base file name (without the $type extension). If omitted,
  302. * $module is used; i.e., resulting in "$module.$type" by default.
  303. *
  304. * @return
  305. * The name of the included file, if successful; FALSE otherwise.
  306. */
  307. function module_load_include($type, $module, $name = NULL) {
  308. if (!isset($name)) {
  309. $name = $module;
  310. }
  311. if (function_exists('drupal_get_path')) {
  312. $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
  313. if (is_file($file)) {
  314. require_once $file;
  315. return $file;
  316. }
  317. }
  318. return FALSE;
  319. }
  320. /**
  321. * Loads an include file for each module enabled in the {system} table.
  322. */
  323. function module_load_all_includes($type, $name = NULL) {
  324. $modules = module_list();
  325. foreach ($modules as $module) {
  326. module_load_include($type, $module, $name);
  327. }
  328. }
  329. /**
  330. * Enables or installs a given list of modules.
  331. *
  332. * Definitions:
  333. * - "Enabling" is the process of activating a module for use by Drupal.
  334. * - "Disabling" is the process of deactivating a module.
  335. * - "Installing" is the process of enabling it for the first time or after it
  336. * has been uninstalled.
  337. * - "Uninstalling" is the process of removing all traces of a module.
  338. *
  339. * Order of events:
  340. * - Gather and add module dependencies to $module_list (if applicable).
  341. * - For each module that is being enabled:
  342. * - Install module schema and update system registries and caches.
  343. * - If the module is being enabled for the first time or had been
  344. * uninstalled, invoke hook_install() and add it to the list of installed
  345. * modules.
  346. * - Invoke hook_enable().
  347. * - Invoke hook_modules_installed().
  348. * - Invoke hook_modules_enabled().
  349. *
  350. * @param $module_list
  351. * An array of module names.
  352. * @param $enable_dependencies
  353. * If TRUE, dependencies will automatically be added and enabled in the
  354. * correct order. This incurs a significant performance cost, so use FALSE
  355. * if you know $module_list is already complete and in the correct order.
  356. *
  357. * @return
  358. * FALSE if one or more dependencies are missing, TRUE otherwise.
  359. *
  360. * @see hook_install()
  361. * @see hook_enable()
  362. * @see hook_modules_installed()
  363. * @see hook_modules_enabled()
  364. */
  365. function module_enable($module_list, $enable_dependencies = TRUE) {
  366. if ($enable_dependencies) {
  367. // Get all module data so we can find dependencies and sort.
  368. $module_data = system_rebuild_module_data();
  369. // Create an associative array with weights as values.
  370. $module_list = array_flip(array_values($module_list));
  371. while (list($module) = each($module_list)) {
  372. if (!isset($module_data[$module])) {
  373. // This module is not found in the filesystem, abort.
  374. return FALSE;
  375. }
  376. if ($module_data[$module]->status) {
  377. // Skip already enabled modules.
  378. unset($module_list[$module]);
  379. continue;
  380. }
  381. $module_list[$module] = $module_data[$module]->sort;
  382. // Add dependencies to the list, with a placeholder weight.
  383. // The new modules will be processed as the while loop continues.
  384. foreach (array_keys($module_data[$module]->requires) as $dependency) {
  385. if (!isset($module_list[$dependency])) {
  386. $module_list[$dependency] = 0;
  387. }
  388. }
  389. }
  390. if (!$module_list) {
  391. // Nothing to do. All modules already enabled.
  392. return TRUE;
  393. }
  394. // Sort the module list by pre-calculated weights.
  395. arsort($module_list);
  396. $module_list = array_keys($module_list);
  397. }
  398. // Required for module installation checks.
  399. include_once DRUPAL_ROOT . '/includes/install.inc';
  400. $modules_installed = array();
  401. $modules_enabled = array();
  402. foreach ($module_list as $module) {
  403. // Only process modules that are not already enabled.
  404. $existing = db_query("SELECT status FROM {system} WHERE type = :type AND name = :name", array(
  405. ':type' => 'module',
  406. ':name' => $module))
  407. ->fetchObject();
  408. if ($existing->status == 0) {
  409. // Load the module's code.
  410. drupal_load('module', $module);
  411. module_load_install($module);
  412. // Update the database and module list to reflect the new module. This
  413. // needs to be done first so that the module's hook implementations,
  414. // hook_schema() in particular, can be called while it is being
  415. // installed.
  416. db_update('system')
  417. ->fields(array('status' => 1))
  418. ->condition('type', 'module')
  419. ->condition('name', $module)
  420. ->execute();
  421. // Refresh the module list to include it.
  422. system_list_reset();
  423. module_list(TRUE);
  424. module_implements('', FALSE, TRUE);
  425. _system_update_bootstrap_status();
  426. // Update the registry to include it.
  427. registry_update();
  428. // Refresh the schema to include it.
  429. drupal_get_schema(NULL, TRUE);
  430. // Update the theme registry to include it.
  431. drupal_theme_rebuild();
  432. // Clear entity cache.
  433. entity_info_cache_clear();
  434. // Now install the module if necessary.
  435. if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
  436. drupal_install_schema($module);
  437. // Set the schema version to the number of the last update provided
  438. // by the module.
  439. $versions = drupal_get_schema_versions($module);
  440. $version = $versions ? max($versions) : SCHEMA_INSTALLED;
  441. // If the module has no current updates, but has some that were
  442. // previously removed, set the version to the value of
  443. // hook_update_last_removed().
  444. if ($last_removed = module_invoke($module, 'update_last_removed')) {
  445. $version = max($version, $last_removed);
  446. }
  447. drupal_set_installed_schema_version($module, $version);
  448. // Allow the module to perform install tasks.
  449. module_invoke($module, 'install');
  450. // Record the fact that it was installed.
  451. $modules_installed[] = $module;
  452. watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
  453. }
  454. // Enable the module.
  455. module_invoke($module, 'enable');
  456. // Record the fact that it was enabled.
  457. $modules_enabled[] = $module;
  458. watchdog('system', '%module module enabled.', array('%module' => $module), WATCHDOG_INFO);
  459. }
  460. }
  461. // If any modules were newly installed, invoke hook_modules_installed().
  462. if (!empty($modules_installed)) {
  463. module_invoke_all('modules_installed', $modules_installed);
  464. }
  465. // If any modules were newly enabled, invoke hook_modules_enabled().
  466. if (!empty($modules_enabled)) {
  467. module_invoke_all('modules_enabled', $modules_enabled);
  468. }
  469. return TRUE;
  470. }
  471. /**
  472. * Disables a given set of modules.
  473. *
  474. * @param $module_list
  475. * An array of module names.
  476. * @param $disable_dependents
  477. * If TRUE, dependent modules will automatically be added and disabled in the
  478. * correct order. This incurs a significant performance cost, so use FALSE
  479. * if you know $module_list is already complete and in the correct order.
  480. */
  481. function module_disable($module_list, $disable_dependents = TRUE) {
  482. if ($disable_dependents) {
  483. // Get all module data so we can find dependents and sort.
  484. $module_data = system_rebuild_module_data();
  485. // Create an associative array with weights as values.
  486. $module_list = array_flip(array_values($module_list));
  487. $profile = drupal_get_profile();
  488. while (list($module) = each($module_list)) {
  489. if (!isset($module_data[$module]) || !$module_data[$module]->status) {
  490. // This module doesn't exist or is already disabled, skip it.
  491. unset($module_list[$module]);
  492. continue;
  493. }
  494. $module_list[$module] = $module_data[$module]->sort;
  495. // Add dependent modules to the list, with a placeholder weight.
  496. // The new modules will be processed as the while loop continues.
  497. foreach ($module_data[$module]->required_by as $dependent => $dependent_data) {
  498. if (!isset($module_list[$dependent]) && $dependent != $profile) {
  499. $module_list[$dependent] = 0;
  500. }
  501. }
  502. }
  503. // Sort the module list by pre-calculated weights.
  504. asort($module_list);
  505. $module_list = array_keys($module_list);
  506. }
  507. $invoke_modules = array();
  508. foreach ($module_list as $module) {
  509. if (module_exists($module)) {
  510. // Check if node_access table needs rebuilding.
  511. if (!node_access_needs_rebuild() && module_hook($module, 'node_grants')) {
  512. node_access_needs_rebuild(TRUE);
  513. }
  514. module_load_install($module);
  515. module_invoke($module, 'disable');
  516. db_update('system')
  517. ->fields(array('status' => 0))
  518. ->condition('type', 'module')
  519. ->condition('name', $module)
  520. ->execute();
  521. $invoke_modules[] = $module;
  522. watchdog('system', '%module module disabled.', array('%module' => $module), WATCHDOG_INFO);
  523. }
  524. }
  525. if (!empty($invoke_modules)) {
  526. // Refresh the module list to exclude the disabled modules.
  527. system_list_reset();
  528. module_list(TRUE);
  529. module_implements('', FALSE, TRUE);
  530. entity_info_cache_clear();
  531. // Invoke hook_modules_disabled before disabling modules,
  532. // so we can still call module hooks to get information.
  533. module_invoke_all('modules_disabled', $invoke_modules);
  534. // Update the registry to remove the newly-disabled module.
  535. registry_update();
  536. _system_update_bootstrap_status();
  537. // Update the theme registry to remove the newly-disabled module.
  538. drupal_theme_rebuild();
  539. }
  540. // If there remains no more node_access module, rebuilding will be
  541. // straightforward, we can do it right now.
  542. if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
  543. node_access_rebuild();
  544. }
  545. }
  546. /**
  547. * @defgroup hooks Hooks
  548. * @{
  549. * Allow modules to interact with the Drupal core.
  550. *
  551. * Drupal's module system is based on the concept of "hooks". A hook is a PHP
  552. * function that is named foo_bar(), where "foo" is the name of the module
  553. * (whose filename is thus foo.module) and "bar" is the name of the hook. Each
  554. * hook has a defined set of parameters and a specified result type.
  555. *
  556. * To extend Drupal, a module need simply implement a hook. When Drupal wishes
  557. * to allow intervention from modules, it determines which modules implement a
  558. * hook and calls that hook in all enabled modules that implement it.
  559. *
  560. * The available hooks to implement are explained here in the Hooks section of
  561. * the developer documentation. The string "hook" is used as a placeholder for
  562. * the module name in the hook definitions. For example, if the module file is
  563. * called example.module, then hook_help() as implemented by that module would
  564. * be defined as example_help().
  565. *
  566. * The example functions included are not part of the Drupal core, they are
  567. * just models that you can modify. Only the hooks implemented within modules
  568. * are executed when running Drupal.
  569. *
  570. * @see themeable
  571. * @see callbacks
  572. */
  573. /**
  574. * @defgroup callbacks Callbacks
  575. * @{
  576. * Callback function signatures.
  577. *
  578. * Drupal's API sometimes uses callback functions to allow you to define how
  579. * some type of processing happens. A callback is a function with a defined
  580. * signature, which you define in a module. Then you pass the function name as
  581. * a parameter to a Drupal API function or return it as part of a hook
  582. * implementation return value, and your function is called at an appropriate
  583. * time. For instance, when setting up batch processing you might need to
  584. * provide a callback function for each processing step and/or a callback for
  585. * when processing is finished; you would do that by defining these functions
  586. * and passing their names into the batch setup function.
  587. *
  588. * Callback function signatures, like hook definitions, are described by
  589. * creating and documenting dummy functions in a *.api.php file; normally, the
  590. * dummy callback function's name should start with "callback_", and you should
  591. * document the parameters and return value and provide a sample function body.
  592. * Then your API documentation can refer to this callback function in its
  593. * documentation. A user of your API can usually name their callback function
  594. * anything they want, although a standard name would be to replace "callback_"
  595. * with the module name.
  596. *
  597. * @see hooks
  598. * @see themeable
  599. *
  600. * @}
  601. */
  602. /**
  603. * Determines whether a module implements a hook.
  604. *
  605. * @param $module
  606. * The name of the module (without the .module extension).
  607. * @param $hook
  608. * The name of the hook (e.g. "help" or "menu").
  609. *
  610. * @return
  611. * TRUE if the module is both installed and enabled, and the hook is
  612. * implemented in that module.
  613. */
  614. function module_hook($module, $hook) {
  615. $function = $module . '_' . $hook;
  616. if (function_exists($function)) {
  617. return TRUE;
  618. }
  619. // If the hook implementation does not exist, check whether it may live in an
  620. // optional include file registered via hook_hook_info().
  621. $hook_info = module_hook_info();
  622. if (isset($hook_info[$hook]['group'])) {
  623. module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  624. if (function_exists($function)) {
  625. return TRUE;
  626. }
  627. }
  628. return FALSE;
  629. }
  630. /**
  631. * Determines which modules are implementing a hook.
  632. *
  633. * @param $hook
  634. * The name of the hook (e.g. "help" or "menu").
  635. * @param $sort
  636. * By default, modules are ordered by weight and filename, settings this option
  637. * to TRUE, module list will be ordered by module name.
  638. * @param $reset
  639. * For internal use only: Whether to force the stored list of hook
  640. * implementations to be regenerated (such as after enabling a new module,
  641. * before processing hook_enable).
  642. *
  643. * @return
  644. * An array with the names of the modules which are implementing this hook.
  645. *
  646. * @see module_implements_write_cache()
  647. */
  648. function module_implements($hook, $sort = FALSE, $reset = FALSE) {
  649. // Use the advanced drupal_static() pattern, since this is called very often.
  650. static $drupal_static_fast;
  651. if (!isset($drupal_static_fast)) {
  652. $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  653. }
  654. $implementations = &$drupal_static_fast['implementations'];
  655. // We maintain a persistent cache of hook implementations in addition to the
  656. // static cache to avoid looping through every module and every hook on each
  657. // request. Benchmarks show that the benefit of this caching outweighs the
  658. // additional database hit even when using the default database caching
  659. // backend and only a small number of modules are enabled. The cost of the
  660. // cache_get() is more or less constant and reduced further when non-database
  661. // caching backends are used, so there will be more significant gains when a
  662. // large number of modules are installed or hooks invoked, since this can
  663. // quickly lead to module_hook() being called several thousand times
  664. // per request.
  665. if ($reset) {
  666. $implementations = array();
  667. cache_set('module_implements', array(), 'cache_bootstrap');
  668. drupal_static_reset('module_hook_info');
  669. drupal_static_reset('drupal_alter');
  670. cache_clear_all('hook_info', 'cache_bootstrap');
  671. return;
  672. }
  673. // Fetch implementations from cache.
  674. if (empty($implementations)) {
  675. $implementations = cache_get('module_implements', 'cache_bootstrap');
  676. if ($implementations === FALSE) {
  677. $implementations = array();
  678. }
  679. else {
  680. $implementations = $implementations->data;
  681. }
  682. }
  683. if (!isset($implementations[$hook])) {
  684. // The hook is not cached, so ensure that whether or not it has
  685. // implementations, that the cache is updated at the end of the request.
  686. $implementations['#write_cache'] = TRUE;
  687. $hook_info = module_hook_info();
  688. $implementations[$hook] = array();
  689. $list = module_list(FALSE, FALSE, $sort);
  690. foreach ($list as $module) {
  691. $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  692. // Since module_hook() may needlessly try to load the include file again,
  693. // function_exists() is used directly here.
  694. if (function_exists($module . '_' . $hook)) {
  695. $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  696. }
  697. }
  698. // Allow modules to change the weight of specific implementations but avoid
  699. // an infinite loop.
  700. if ($hook != 'module_implements_alter') {
  701. drupal_alter('module_implements', $implementations[$hook], $hook);
  702. }
  703. }
  704. else {
  705. foreach ($implementations[$hook] as $module => $group) {
  706. // If this hook implementation is stored in a lazy-loaded file, so include
  707. // that file first.
  708. if ($group) {
  709. module_load_include('inc', $module, "$module.$group");
  710. }
  711. // It is possible that a module removed a hook implementation without the
  712. // implementations cache being rebuilt yet, so we check whether the
  713. // function exists on each request to avoid undefined function errors.
  714. // Since module_hook() may needlessly try to load the include file again,
  715. // function_exists() is used directly here.
  716. if (!function_exists($module . '_' . $hook)) {
  717. // Clear out the stale implementation from the cache and force a cache
  718. // refresh to forget about no longer existing hook implementations.
  719. unset($implementations[$hook][$module]);
  720. $implementations['#write_cache'] = TRUE;
  721. }
  722. }
  723. }
  724. return array_keys($implementations[$hook]);
  725. }
  726. /**
  727. * Retrieves a list of hooks that are declared through hook_hook_info().
  728. *
  729. * @return
  730. * An associative array whose keys are hook names and whose values are an
  731. * associative array containing a group name. The structure of the array
  732. * is the same as the return value of hook_hook_info().
  733. *
  734. * @see hook_hook_info()
  735. */
  736. function module_hook_info() {
  737. // This function is indirectly invoked from bootstrap_invoke_all(), in which
  738. // case common.inc, subsystems, and modules are not loaded yet, so it does not
  739. // make sense to support hook groups resp. lazy-loaded include files prior to
  740. // full bootstrap.
  741. if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
  742. return array();
  743. }
  744. $hook_info = &drupal_static(__FUNCTION__);
  745. if (!isset($hook_info)) {
  746. $hook_info = array();
  747. $cache = cache_get('hook_info', 'cache_bootstrap');
  748. if ($cache === FALSE) {
  749. // Rebuild the cache and save it.
  750. // We can't use module_invoke_all() here or it would cause an infinite
  751. // loop.
  752. foreach (module_list() as $module) {
  753. $function = $module . '_hook_info';
  754. if (function_exists($function)) {
  755. $result = $function();
  756. if (isset($result) && is_array($result)) {
  757. $hook_info = array_merge_recursive($hook_info, $result);
  758. }
  759. }
  760. }
  761. // We can't use drupal_alter() for the same reason as above.
  762. foreach (module_list() as $module) {
  763. $function = $module . '_hook_info_alter';
  764. if (function_exists($function)) {
  765. $function($hook_info);
  766. }
  767. }
  768. cache_set('hook_info', $hook_info, 'cache_bootstrap');
  769. }
  770. else {
  771. $hook_info = $cache->data;
  772. }
  773. }
  774. return $hook_info;
  775. }
  776. /**
  777. * Writes the hook implementation cache.
  778. *
  779. * @see module_implements()
  780. */
  781. function module_implements_write_cache() {
  782. $implementations = &drupal_static('module_implements');
  783. if (isset($implementations['#write_cache'])) {
  784. unset($implementations['#write_cache']);
  785. cache_set('module_implements', $implementations, 'cache_bootstrap');
  786. }
  787. }
  788. /**
  789. * Invokes a hook in a particular module.
  790. *
  791. * All arguments are passed by value. Use drupal_alter() if you need to pass
  792. * arguments by reference.
  793. *
  794. * @param $module
  795. * The name of the module (without the .module extension).
  796. * @param $hook
  797. * The name of the hook to invoke.
  798. * @param ...
  799. * Arguments to pass to the hook implementation.
  800. *
  801. * @return
  802. * The return value of the hook implementation.
  803. *
  804. * @see drupal_alter()
  805. */
  806. function module_invoke($module, $hook) {
  807. $args = func_get_args();
  808. // Remove $module and $hook from the arguments.
  809. unset($args[0], $args[1]);
  810. if (module_hook($module, $hook)) {
  811. return call_user_func_array($module . '_' . $hook, $args);
  812. }
  813. }
  814. /**
  815. * Invokes a hook in all enabled modules that implement it.
  816. *
  817. * All arguments are passed by value. Use drupal_alter() if you need to pass
  818. * arguments by reference.
  819. *
  820. * @param $hook
  821. * The name of the hook to invoke.
  822. * @param ...
  823. * Arguments to pass to the hook.
  824. *
  825. * @return
  826. * An array of return values of the hook implementations. If modules return
  827. * arrays from their implementations, those are merged into one array.
  828. *
  829. * @see drupal_alter()
  830. */
  831. function module_invoke_all($hook) {
  832. $args = func_get_args();
  833. // Remove $hook from the arguments.
  834. unset($args[0]);
  835. $return = array();
  836. foreach (module_implements($hook) as $module) {
  837. $function = $module . '_' . $hook;
  838. if (function_exists($function)) {
  839. $result = call_user_func_array($function, $args);
  840. if (isset($result) && is_array($result)) {
  841. $return = array_merge_recursive($return, $result);
  842. }
  843. elseif (isset($result)) {
  844. $return[] = $result;
  845. }
  846. }
  847. }
  848. return $return;
  849. }
  850. /**
  851. * @} End of "defgroup hooks".
  852. */
  853. /**
  854. * Returns an array of modules required by core.
  855. */
  856. function drupal_required_modules() {
  857. $files = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', 'modules', 'name', 0);
  858. $required = array();
  859. // An installation profile is required and one must always be loaded.
  860. $required[] = drupal_get_profile();
  861. foreach ($files as $name => $file) {
  862. $info = drupal_parse_info_file($file->uri);
  863. if (!empty($info) && !empty($info['required']) && $info['required']) {
  864. $required[] = $name;
  865. }
  866. }
  867. return $required;
  868. }
  869. /**
  870. * Passes alterable variables to specific hook_TYPE_alter() implementations.
  871. *
  872. * This dispatch function hands off the passed-in variables to type-specific
  873. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  874. * interface for all altering operations.
  875. *
  876. * A maximum of 2 alterable arguments is supported (a third is supported for
  877. * legacy reasons, but should not be used in new code). In case more arguments
  878. * need to be passed and alterable, modules provide additional variables
  879. * assigned by reference in the last $context argument:
  880. * @code
  881. * $context = array(
  882. * 'alterable' => &$alterable,
  883. * 'unalterable' => $unalterable,
  884. * 'foo' => 'bar',
  885. * );
  886. * drupal_alter('mymodule_data', $alterable1, $alterable2, $context);
  887. * @endcode
  888. *
  889. * Note that objects are always passed by reference in PHP5. If it is absolutely
  890. * required that no implementation alters a passed object in $context, then an
  891. * object needs to be cloned:
  892. * @code
  893. * $context = array(
  894. * 'unalterable_object' => clone $object,
  895. * );
  896. * drupal_alter('mymodule_data', $data, $context);
  897. * @endcode
  898. *
  899. * @param $type
  900. * A string describing the type of the alterable $data. 'form', 'links',
  901. * 'node_content', and so on are several examples. Alternatively can be an
  902. * array, in which case hook_TYPE_alter() is invoked for each value in the
  903. * array, ordered first by module, and then for each module, in the order of
  904. * values in $type. For example, when Form API is using drupal_alter() to
  905. * execute both hook_form_alter() and hook_form_FORM_ID_alter()
  906. * implementations, it passes array('form', 'form_' . $form_id) for $type.
  907. * @param $data
  908. * The variable that will be passed to hook_TYPE_alter() implementations to be
  909. * altered. The type of this variable depends on the value of the $type
  910. * argument. For example, when altering a 'form', $data will be a structured
  911. * array. When altering a 'profile', $data will be an object.
  912. * @param $context1
  913. * (optional) An additional variable that is passed by reference.
  914. * @param $context2
  915. * (optional) An additional variable that is passed by reference. If more
  916. * context needs to be provided to implementations, then this should be an
  917. * associative array as described above.
  918. * @param $context3
  919. * (optional) An additional variable that is passed by reference. This
  920. * parameter is deprecated and will not exist in Drupal 8; consequently, it
  921. * should not be used for new Drupal 7 code either. It is here only for
  922. * backwards compatibility with older code that passed additional arguments
  923. * to drupal_alter().
  924. */
  925. function drupal_alter($type, &$data, &$context1 = NULL, &$context2 = NULL, &$context3 = NULL) {
  926. // Use the advanced drupal_static() pattern, since this is called very often.
  927. static $drupal_static_fast;
  928. if (!isset($drupal_static_fast)) {
  929. $drupal_static_fast['functions'] = &drupal_static(__FUNCTION__);
  930. }
  931. $functions = &$drupal_static_fast['functions'];
  932. // Most of the time, $type is passed as a string, so for performance,
  933. // normalize it to that. When passed as an array, usually the first item in
  934. // the array is a generic type, and additional items in the array are more
  935. // specific variants of it, as in the case of array('form', 'form_FORM_ID').
  936. if (is_array($type)) {
  937. $cid = implode(',', $type);
  938. $extra_types = $type;
  939. $type = array_shift($extra_types);
  940. // Allow if statements in this function to use the faster isset() rather
  941. // than !empty() both when $type is passed as a string, or as an array with
  942. // one item.
  943. if (empty($extra_types)) {
  944. unset($extra_types);
  945. }
  946. }
  947. else {
  948. $cid = $type;
  949. }
  950. // Some alter hooks are invoked many times per page request, so statically
  951. // cache the list of functions to call, and on subsequent calls, iterate
  952. // through them quickly.
  953. if (!isset($functions[$cid])) {
  954. $functions[$cid] = array();
  955. $hook = $type . '_alter';
  956. $modules = module_implements($hook);
  957. if (!isset($extra_types)) {
  958. // For the more common case of a single hook, we do not need to call
  959. // function_exists(), since module_implements() returns only modules with
  960. // implementations.
  961. foreach ($modules as $module) {
  962. $functions[$cid][] = $module . '_' . $hook;
  963. }
  964. }
  965. else {
  966. // For multiple hooks, we need $modules to contain every module that
  967. // implements at least one of them.
  968. $extra_modules = array();
  969. foreach ($extra_types as $extra_type) {
  970. $extra_modules = array_merge($extra_modules, module_implements($extra_type . '_alter'));
  971. }
  972. // If any modules implement one of the extra hooks that do not implement
  973. // the primary hook, we need to add them to the $modules array in their
  974. // appropriate order. module_implements() can only return ordered
  975. // implementations of a single hook. To get the ordered implementations
  976. // of multiple hooks, we mimic the module_implements() logic of first
  977. // ordering by module_list(), and then calling
  978. // drupal_alter('module_implements').
  979. if (array_diff($extra_modules, $modules)) {
  980. // Merge the arrays and order by module_list().
  981. $modules = array_intersect(module_list(), array_merge($modules, $extra_modules));
  982. // Since module_implements() already took care of loading the necessary
  983. // include files, we can safely pass FALSE for the array values.
  984. $implementations = array_fill_keys($modules, FALSE);
  985. // Let modules adjust the order solely based on the primary hook. This
  986. // ensures the same module order regardless of whether this if block
  987. // runs. Calling drupal_alter() recursively in this way does not result
  988. // in an infinite loop, because this call is for a single $type, so we
  989. // won't end up in this code block again.
  990. drupal_alter('module_implements', $implementations, $hook);
  991. $modules = array_keys($implementations);
  992. }
  993. foreach ($modules as $module) {
  994. // Since $modules is a merged array, for any given module, we do not
  995. // know whether it has any particular implementation, so we need a
  996. // function_exists().
  997. $function = $module . '_' . $hook;
  998. if (function_exists($function)) {
  999. $functions[$cid][] = $function;
  1000. }
  1001. foreach ($extra_types as $extra_type) {
  1002. $function = $module . '_' . $extra_type . '_alter';
  1003. if (function_exists($function)) {
  1004. $functions[$cid][] = $function;
  1005. }
  1006. }
  1007. }
  1008. }
  1009. // Allow the theme to alter variables after the theme system has been
  1010. // initialized.
  1011. global $theme, $base_theme_info;
  1012. if (isset($theme)) {
  1013. $theme_keys = array();
  1014. foreach ($base_theme_info as $base) {
  1015. $theme_keys[] = $base->name;
  1016. }
  1017. $theme_keys[] = $theme;
  1018. foreach ($theme_keys as $theme_key) {
  1019. $function = $theme_key . '_' . $hook;
  1020. if (function_exists($function)) {
  1021. $functions[$cid][] = $function;
  1022. }
  1023. if (isset($extra_types)) {
  1024. foreach ($extra_types as $extra_type) {
  1025. $function = $theme_key . '_' . $extra_type . '_alter';
  1026. if (function_exists($function)) {
  1027. $functions[$cid][] = $function;
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }
  1033. }
  1034. foreach ($functions[$cid] as $function) {
  1035. $function($data, $context1, $context2, $context3);
  1036. }
  1037. }