Skip navigation
Help

module.inc

  1. drupal
    1. 6 drupal/includes/module.inc
    2. 7 drupal/includes/module.inc

API for loading and interacting with Drupal modules.

Functions & methods

NameDescription
drupal_alterHands off alterable variables to type-specific *_alter implementations.
drupal_required_modulesArray of modules required by core.
module_disableDisable a given set of modules.
module_enableEnables or installs a given list of modules.
module_existsDetermine whether a given module exists.
module_hookDetermine whether a module implements a hook.
module_hook_infoRetrieve a list of what hooks are explicitly declared.
module_implementsDetermine which modules are implementing a hook.
module_implements_write_cacheWrites the hook implementation cache.
module_invokeInvoke a hook in a particular module.
module_invoke_allInvoke a hook in all enabled modules that implement it.
module_listReturns a list of currently active modules.
module_load_allLoad all the modules that have been enabled in the system table.
module_load_all_includesLoad an include file for each of the modules that have been enabled in the system table.
module_load_includeLoad a module include file.
module_load_installLoad a module's installation hooks.
system_listBuild a list of bootstrap modules and enabled modules and themes.
system_list_resetReset all system_list() caches.
_module_build_dependenciesFind dependencies any level deep and fill in required by information too.

File

drupal/includes/module.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API for loading and interacting with Drupal modules.
  5. */
  6. /**
  7. * Load 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. * Build 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. cache_set('system_list', $lists, 'cache_bootstrap');
  174. }
  175. // To avoid a separate database lookup for the filepath, prime the
  176. // drupal_get_filename() static cache with all enabled modules and themes.
  177. foreach ($lists['filepaths'] as $item) {
  178. drupal_get_filename($item['type'], $item['name'], $item['filepath']);
  179. }
  180. }
  181. return $lists[$type];
  182. }
  183. /**
  184. * Reset all system_list() caches.
  185. */
  186. function system_list_reset() {
  187. drupal_static_reset('system_list');
  188. drupal_static_reset('system_rebuild_module_data');
  189. drupal_static_reset('list_themes');
  190. cache_clear_all('bootstrap_modules', 'cache_bootstrap');
  191. cache_clear_all('system_list', 'cache_bootstrap');
  192. }
  193. /**
  194. * Find dependencies any level deep and fill in required by information too.
  195. *
  196. * @param $files
  197. * The array of filesystem objects used to rebuild the cache.
  198. *
  199. * @return
  200. * The same array with the new keys for each module:
  201. * - requires: An array with the keys being the modules that this module
  202. * requires.
  203. * - required_by: An array with the keys being the modules that will not work
  204. * without this module.
  205. */
  206. function _module_build_dependencies($files) {
  207. require_once DRUPAL_ROOT . '/includes/graph.inc';
  208. foreach ($files as $filename => $file) {
  209. $graph[$file->name]['edges'] = array();
  210. if (isset($file->info['dependencies']) && is_array($file->info['dependencies'])) {
  211. foreach ($file->info['dependencies'] as $dependency) {
  212. $dependency_data = drupal_parse_dependency($dependency);
  213. $graph[$file->name]['edges'][$dependency_data['name']] = $dependency_data;
  214. }
  215. }
  216. }
  217. drupal_depth_first_search($graph);
  218. foreach ($graph as $module => $data) {
  219. $files[$module]->required_by = isset($data['reverse_paths']) ? $data['reverse_paths'] : array();
  220. $files[$module]->requires = isset($data['paths']) ? $data['paths'] : array();
  221. $files[$module]->sort = $data['weight'];
  222. }
  223. return $files;
  224. }
  225. /**
  226. * Determine whether a given module exists.
  227. *
  228. * @param $module
  229. * The name of the module (without the .module extension).
  230. *
  231. * @return
  232. * TRUE if the module is both installed and enabled.
  233. */
  234. function module_exists($module) {
  235. $list = module_list();
  236. return isset($list[$module]);
  237. }
  238. /**
  239. * Load a module's installation hooks.
  240. *
  241. * @param $module
  242. * The name of the module (without the .module extension).
  243. *
  244. * @return
  245. * The name of the module's install file, if successful; FALSE otherwise.
  246. */
  247. function module_load_install($module) {
  248. // Make sure the installation API is available
  249. include_once DRUPAL_ROOT . '/includes/install.inc';
  250. return module_load_include('install', $module);
  251. }
  252. /**
  253. * Load a module include file.
  254. *
  255. * Examples:
  256. * @code
  257. * // Load node.admin.inc from the node module.
  258. * module_load_include('inc', 'node', 'node.admin');
  259. * // Load content_types.inc from the node module.
  260. * module_load_include('inc', 'node', 'content_types');
  261. * @endcode
  262. *
  263. * Do not use this function to load an install file, use module_load_install()
  264. * instead. Do not use this function in a global context since it requires
  265. * Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file'
  266. * instead.
  267. *
  268. * @param $type
  269. * The include file's type (file extension).
  270. * @param $module
  271. * The module to which the include file belongs.
  272. * @param $name
  273. * (optional) The base file name (without the $type extension). If omitted,
  274. * $module is used; i.e., resulting in "$module.$type" by default.
  275. *
  276. * @return
  277. * The name of the included file, if successful; FALSE otherwise.
  278. */
  279. function module_load_include($type, $module, $name = NULL) {
  280. if (!isset($name)) {
  281. $name = $module;
  282. }
  283. if (function_exists('drupal_get_path')) {
  284. $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
  285. if (is_file($file)) {
  286. require_once $file;
  287. return $file;
  288. }
  289. }
  290. return FALSE;
  291. }
  292. /**
  293. * Load an include file for each of the modules that have been enabled in
  294. * the system table.
  295. */
  296. function module_load_all_includes($type, $name = NULL) {
  297. $modules = module_list();
  298. foreach ($modules as $module) {
  299. module_load_include($type, $module, $name);
  300. }
  301. }
  302. /**
  303. * Enables or installs a given list of modules.
  304. *
  305. * Definitions:
  306. * - "Enabling" is the process of activating a module for use by Drupal.
  307. * - "Disabling" is the process of deactivating a module.
  308. * - "Installing" is the process of enabling it for the first time or after it
  309. * has been uninstalled.
  310. * - "Uninstalling" is the process of removing all traces of a module.
  311. *
  312. * Order of events:
  313. * - Gather and add module dependencies to $module_list (if applicable).
  314. * - For each module that is being enabled:
  315. * - Install module schema and update system registries and caches.
  316. * - If the module is being enabled for the first time or had been
  317. * uninstalled, invoke hook_install() and add it to the list of installed
  318. * modules.
  319. * - Invoke hook_enable().
  320. * - Invoke hook_modules_installed().
  321. * - Invoke hook_modules_enabled().
  322. *
  323. * @param $module_list
  324. * An array of module names.
  325. * @param $enable_dependencies
  326. * If TRUE, dependencies will automatically be added and enabled in the
  327. * correct order. This incurs a significant performance cost, so use FALSE
  328. * if you know $module_list is already complete and in the correct order.
  329. *
  330. * @return
  331. * FALSE if one or more dependencies are missing, TRUE otherwise.
  332. *
  333. * @see hook_install()
  334. * @see hook_enable()
  335. * @see hook_modules_installed()
  336. * @see hook_modules_enabled()
  337. */
  338. function module_enable($module_list, $enable_dependencies = TRUE) {
  339. if ($enable_dependencies) {
  340. // Get all module data so we can find dependencies and sort.
  341. $module_data = system_rebuild_module_data();
  342. // Create an associative array with weights as values.
  343. $module_list = array_flip(array_values($module_list));
  344. while (list($module) = each($module_list)) {
  345. if (!isset($module_data[$module])) {
  346. // This module is not found in the filesystem, abort.
  347. return FALSE;
  348. }
  349. if ($module_data[$module]->status) {
  350. // Skip already enabled modules.
  351. unset($module_list[$module]);
  352. continue;
  353. }
  354. $module_list[$module] = $module_data[$module]->sort;
  355. // Add dependencies to the list, with a placeholder weight.
  356. // The new modules will be processed as the while loop continues.
  357. foreach (array_keys($module_data[$module]->requires) as $dependency) {
  358. if (!isset($module_list[$dependency])) {
  359. $module_list[$dependency] = 0;
  360. }
  361. }
  362. }
  363. if (!$module_list) {
  364. // Nothing to do. All modules already enabled.
  365. return TRUE;
  366. }
  367. // Sort the module list by pre-calculated weights.
  368. arsort($module_list);
  369. $module_list = array_keys($module_list);
  370. }
  371. // Required for module installation checks.
  372. include_once DRUPAL_ROOT . '/includes/install.inc';
  373. $modules_installed = array();
  374. $modules_enabled = array();
  375. foreach ($module_list as $module) {
  376. // Only process modules that are not already enabled.
  377. $existing = db_query("SELECT status FROM {system} WHERE type = :type AND name = :name", array(
  378. ':type' => 'module',
  379. ':name' => $module))
  380. ->fetchObject();
  381. if ($existing->status == 0) {
  382. // Load the module's code.
  383. drupal_load('module', $module);
  384. module_load_install($module);
  385. // Update the database and module list to reflect the new module. This
  386. // needs to be done first so that the module's hook implementations,
  387. // hook_schema() in particular, can be called while it is being
  388. // installed.
  389. db_update('system')
  390. ->fields(array('status' => 1))
  391. ->condition('type', 'module')
  392. ->condition('name', $module)
  393. ->execute();
  394. // Refresh the module list to include it.
  395. system_list_reset();
  396. module_list(TRUE);
  397. module_implements('', FALSE, TRUE);
  398. _system_update_bootstrap_status();
  399. // Update the registry to include it.
  400. registry_update();
  401. // Refresh the schema to include it.
  402. drupal_get_schema(NULL, TRUE);
  403. // Clear entity cache.
  404. entity_info_cache_clear();
  405. // Now install the module if necessary.
  406. if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
  407. drupal_install_schema($module);
  408. // Set the schema version to the number of the last update provided
  409. // by the module.
  410. $versions = drupal_get_schema_versions($module);
  411. $version = $versions ? max($versions) : SCHEMA_INSTALLED;
  412. // If the module has no current updates, but has some that were
  413. // previously removed, set the version to the value of
  414. // hook_update_last_removed().
  415. if ($last_removed = module_invoke($module, 'update_last_removed')) {
  416. $version = max($version, $last_removed);
  417. }
  418. drupal_set_installed_schema_version($module, $version);
  419. // Allow the module to perform install tasks.
  420. module_invoke($module, 'install');
  421. // Record the fact that it was installed.
  422. $modules_installed[] = $module;
  423. watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
  424. }
  425. // Enable the module.
  426. module_invoke($module, 'enable');
  427. // Record the fact that it was enabled.
  428. $modules_enabled[] = $module;
  429. watchdog('system', '%module module enabled.', array('%module' => $module), WATCHDOG_INFO);
  430. }
  431. }
  432. // If any modules were newly installed, invoke hook_modules_installed().
  433. if (!empty($modules_installed)) {
  434. module_invoke_all('modules_installed', $modules_installed);
  435. }
  436. // If any modules were newly enabled, invoke hook_modules_enabled().
  437. if (!empty($modules_enabled)) {
  438. module_invoke_all('modules_enabled', $modules_enabled);
  439. }
  440. return TRUE;
  441. }
  442. /**
  443. * Disable a given set of modules.
  444. *
  445. * @param $module_list
  446. * An array of module names.
  447. * @param $disable_dependents
  448. * If TRUE, dependent modules will automatically be added and disabled in the
  449. * correct order. This incurs a significant performance cost, so use FALSE
  450. * if you know $module_list is already complete and in the correct order.
  451. */
  452. function module_disable($module_list, $disable_dependents = TRUE) {
  453. if ($disable_dependents) {
  454. // Get all module data so we can find dependents and sort.
  455. $module_data = system_rebuild_module_data();
  456. // Create an associative array with weights as values.
  457. $module_list = array_flip(array_values($module_list));
  458. $profile = drupal_get_profile();
  459. while (list($module) = each($module_list)) {
  460. if (!isset($module_data[$module]) || !$module_data[$module]->status) {
  461. // This module doesn't exist or is already disabled, skip it.
  462. unset($module_list[$module]);
  463. continue;
  464. }
  465. $module_list[$module] = $module_data[$module]->sort;
  466. // Add dependent modules to the list, with a placeholder weight.
  467. // The new modules will be processed as the while loop continues.
  468. foreach ($module_data[$module]->required_by as $dependent => $dependent_data) {
  469. if (!isset($module_list[$dependent]) && $dependent != $profile) {
  470. $module_list[$dependent] = 0;
  471. }
  472. }
  473. }
  474. // Sort the module list by pre-calculated weights.
  475. asort($module_list);
  476. $module_list = array_keys($module_list);
  477. }
  478. $invoke_modules = array();
  479. foreach ($module_list as $module) {
  480. if (module_exists($module)) {
  481. // Check if node_access table needs rebuilding.
  482. if (!node_access_needs_rebuild() && module_hook($module, 'node_grants')) {
  483. node_access_needs_rebuild(TRUE);
  484. }
  485. module_load_install($module);
  486. module_invoke($module, 'disable');
  487. db_update('system')
  488. ->fields(array('status' => 0))
  489. ->condition('type', 'module')
  490. ->condition('name', $module)
  491. ->execute();
  492. $invoke_modules[] = $module;
  493. watchdog('system', '%module module disabled.', array('%module' => $module), WATCHDOG_INFO);
  494. }
  495. }
  496. if (!empty($invoke_modules)) {
  497. // Refresh the module list to exclude the disabled modules.
  498. system_list_reset();
  499. module_list(TRUE);
  500. module_implements('', FALSE, TRUE);
  501. // Invoke hook_modules_disabled before disabling modules,
  502. // so we can still call module hooks to get information.
  503. module_invoke_all('modules_disabled', $invoke_modules);
  504. // Update the registry to remove the newly-disabled module.
  505. registry_update();
  506. _system_update_bootstrap_status();
  507. }
  508. // If there remains no more node_access module, rebuilding will be
  509. // straightforward, we can do it right now.
  510. if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
  511. node_access_rebuild();
  512. }
  513. }
  514. /**
  515. * @defgroup hooks Hooks
  516. * @{
  517. * Allow modules to interact with the Drupal core.
  518. *
  519. * Drupal's module system is based on the concept of "hooks". A hook is a PHP
  520. * function that is named foo_bar(), where "foo" is the name of the module
  521. * (whose filename is thus foo.module) and "bar" is the name of the hook. Each
  522. * hook has a defined set of parameters and a specified result type.
  523. *
  524. * To extend Drupal, a module need simply implement a hook. When Drupal wishes
  525. * to allow intervention from modules, it determines which modules implement a
  526. * hook and calls that hook in all enabled modules that implement it.
  527. *
  528. * The available hooks to implement are explained here in the Hooks section of
  529. * the developer documentation. The string "hook" is used as a placeholder for
  530. * the module name in the hook definitions. For example, if the module file is
  531. * called example.module, then hook_help() as implemented by that module would
  532. * be defined as example_help().
  533. *
  534. * The example functions included are not part of the Drupal core, they are
  535. * just models that you can modify. Only the hooks implemented within modules
  536. * are executed when running Drupal.
  537. *
  538. * See also @link themeable the themeable group page. @endlink
  539. */
  540. /**
  541. * Determine whether a module implements a hook.
  542. *
  543. * @param $module
  544. * The name of the module (without the .module extension).
  545. * @param $hook
  546. * The name of the hook (e.g. "help" or "menu").
  547. *
  548. * @return
  549. * TRUE if the module is both installed and enabled, and the hook is
  550. * implemented in that module.
  551. */
  552. function module_hook($module, $hook) {
  553. $function = $module . '_' . $hook;
  554. if (function_exists($function)) {
  555. return TRUE;
  556. }
  557. // If the hook implementation does not exist, check whether it may live in an
  558. // optional include file registered via hook_hook_info().
  559. $hook_info = module_hook_info();
  560. if (isset($hook_info[$hook]['group'])) {
  561. module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  562. if (function_exists($function)) {
  563. return TRUE;
  564. }
  565. }
  566. return FALSE;
  567. }
  568. /**
  569. * Determine which modules are implementing a hook.
  570. *
  571. * @param $hook
  572. * The name of the hook (e.g. "help" or "menu").
  573. * @param $sort
  574. * By default, modules are ordered by weight and filename, settings this option
  575. * to TRUE, module list will be ordered by module name.
  576. * @param $reset
  577. * For internal use only: Whether to force the stored list of hook
  578. * implementations to be regenerated (such as after enabling a new module,
  579. * before processing hook_enable).
  580. *
  581. * @return
  582. * An array with the names of the modules which are implementing this hook.
  583. *
  584. * @see module_implements_write_cache()
  585. */
  586. function module_implements($hook, $sort = FALSE, $reset = FALSE) {
  587. // Use the advanced drupal_static() pattern, since this is called very often.
  588. static $drupal_static_fast;
  589. if (!isset($drupal_static_fast)) {
  590. $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  591. }
  592. $implementations = &$drupal_static_fast['implementations'];
  593. // We maintain a persistent cache of hook implementations in addition to the
  594. // static cache to avoid looping through every module and every hook on each
  595. // request. Benchmarks show that the benefit of this caching outweighs the
  596. // additional database hit even when using the default database caching
  597. // backend and only a small number of modules are enabled. The cost of the
  598. // cache_get() is more or less constant and reduced further when non-database
  599. // caching backends are used, so there will be more significant gains when a
  600. // large number of modules are installed or hooks invoked, since this can
  601. // quickly lead to module_hook() being called several thousand times
  602. // per request.
  603. if ($reset) {
  604. $implementations = array();
  605. cache_set('module_implements', array(), 'cache_bootstrap');
  606. drupal_static_reset('module_hook_info');
  607. drupal_static_reset('drupal_alter');
  608. cache_clear_all('hook_info', 'cache_bootstrap');
  609. return;
  610. }
  611. // Fetch implementations from cache.
  612. if (empty($implementations)) {
  613. $implementations = cache_get('module_implements', 'cache_bootstrap');
  614. if ($implementations === FALSE) {
  615. $implementations = array();
  616. }
  617. else {
  618. $implementations = $implementations->data;
  619. }
  620. }
  621. if (!isset($implementations[$hook])) {
  622. // The hook is not cached, so ensure that whether or not it has
  623. // implementations, that the cache is updated at the end of the request.
  624. $implementations['#write_cache'] = TRUE;
  625. $hook_info = module_hook_info();
  626. $implementations[$hook] = array();
  627. $list = module_list(FALSE, FALSE, $sort);
  628. foreach ($list as $module) {
  629. $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  630. // Since module_hook() may needlessly try to load the include file again,
  631. // function_exists() is used directly here.
  632. if (function_exists($module . '_' . $hook)) {
  633. $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  634. }
  635. }
  636. // Allow modules to change the weight of specific implementations but avoid
  637. // an infinite loop.
  638. if ($hook != 'module_implements_alter') {
  639. drupal_alter('module_implements', $implementations[$hook], $hook);
  640. }
  641. }
  642. else {
  643. foreach ($implementations[$hook] as $module => $group) {
  644. // If this hook implementation is stored in a lazy-loaded file, so include
  645. // that file first.
  646. if ($group) {
  647. module_load_include('inc', $module, "$module.$group");
  648. }
  649. // It is possible that a module removed a hook implementation without the
  650. // implementations cache being rebuilt yet, so we check whether the
  651. // function exists on each request to avoid undefined function errors.
  652. // Since module_hook() may needlessly try to load the include file again,
  653. // function_exists() is used directly here.
  654. if (!function_exists($module . '_' . $hook)) {
  655. // Clear out the stale implementation from the cache and force a cache
  656. // refresh to forget about no longer existing hook implementations.
  657. unset($implementations[$hook][$module]);
  658. $implementations['#write_cache'] = TRUE;
  659. }
  660. }
  661. }
  662. return array_keys($implementations[$hook]);
  663. }
  664. /**
  665. * Retrieve a list of what hooks are explicitly declared.
  666. */
  667. function module_hook_info() {
  668. // This function is indirectly invoked from bootstrap_invoke_all(), in which
  669. // case common.inc, subsystems, and modules are not loaded yet, so it does not
  670. // make sense to support hook groups resp. lazy-loaded include files prior to
  671. // full bootstrap.
  672. if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
  673. return array();
  674. }
  675. $hook_info = &drupal_static(__FUNCTION__);
  676. if (!isset($hook_info)) {
  677. $hook_info = array();
  678. $cache = cache_get('hook_info', 'cache_bootstrap');
  679. if ($cache === FALSE) {
  680. // Rebuild the cache and save it.
  681. // We can't use module_invoke_all() here or it would cause an infinite
  682. // loop.
  683. foreach (module_list() as $module) {
  684. $function = $module . '_hook_info';
  685. if (function_exists($function)) {
  686. $result = $function();
  687. if (isset($result) && is_array($result)) {
  688. $hook_info = array_merge_recursive($hook_info, $result);
  689. }
  690. }
  691. }
  692. // We can't use drupal_alter() for the same reason as above.
  693. foreach (module_list() as $module) {
  694. $function = $module . '_hook_info_alter';
  695. if (function_exists($function)) {
  696. $function($hook_info);
  697. }
  698. }
  699. cache_set('hook_info', $hook_info, 'cache_bootstrap');
  700. }
  701. else {
  702. $hook_info = $cache->data;
  703. }
  704. }
  705. return $hook_info;
  706. }
  707. /**
  708. * Writes the hook implementation cache.
  709. *
  710. * @see module_implements()
  711. */
  712. function module_implements_write_cache() {
  713. $implementations = &drupal_static('module_implements');
  714. // Check whether we need to write the cache. We do not want to cache hooks
  715. // which are only invoked on HTTP POST requests since these do not need to be
  716. // optimized as tightly, and not doing so keeps the cache entry smaller.
  717. if (isset($implementations['#write_cache']) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')) {
  718. unset($implementations['#write_cache']);
  719. cache_set('module_implements', $implementations, 'cache_bootstrap');
  720. }
  721. }
  722. /**
  723. * Invoke a hook in a particular module.
  724. *
  725. * @param $module
  726. * The name of the module (without the .module extension).
  727. * @param $hook
  728. * The name of the hook to invoke.
  729. * @param ...
  730. * Arguments to pass to the hook implementation.
  731. *
  732. * @return
  733. * The return value of the hook implementation.
  734. */
  735. function module_invoke() {
  736. $args = func_get_args();
  737. $module = $args[0];
  738. $hook = $args[1];
  739. unset($args[0], $args[1]);
  740. if (module_hook($module, $hook)) {
  741. return call_user_func_array($module . '_' . $hook, $args);
  742. }
  743. }
  744. /**
  745. * Invoke a hook in all enabled modules that implement it.
  746. *
  747. * @param $hook
  748. * The name of the hook to invoke.
  749. * @param ...
  750. * Arguments to pass to the hook.
  751. *
  752. * @return
  753. * An array of return values of the hook implementations. If modules return
  754. * arrays from their implementations, those are merged into one array.
  755. */
  756. function module_invoke_all() {
  757. $args = func_get_args();
  758. $hook = $args[0];
  759. unset($args[0]);
  760. $return = array();
  761. foreach (module_implements($hook) as $module) {
  762. $function = $module . '_' . $hook;
  763. if (function_exists($function)) {
  764. $result = call_user_func_array($function, $args);
  765. if (isset($result) && is_array($result)) {
  766. $return = array_merge_recursive($return, $result);
  767. }
  768. elseif (isset($result)) {
  769. $return[] = $result;
  770. }
  771. }
  772. }
  773. return $return;
  774. }
  775. /**
  776. * @} End of "defgroup hooks".
  777. */
  778. /**
  779. * Array of modules required by core.
  780. */
  781. function drupal_required_modules() {
  782. $files = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', 'modules', 'name', 0);
  783. $required = array();
  784. // An install profile is required and one must always be loaded.
  785. $required[] = drupal_get_profile();
  786. foreach ($files as $name => $file) {
  787. $info = drupal_parse_info_file($file->uri);
  788. if (!empty($info) && !empty($info['required']) && $info['required']) {
  789. $required[] = $name;
  790. }
  791. }
  792. return $required;
  793. }
  794. /**
  795. * Hands off alterable variables to type-specific *_alter implementations.
  796. *
  797. * This dispatch function hands off the passed-in variables to type-specific
  798. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  799. * interface for all altering operations.
  800. *
  801. * A maximum of 2 alterable arguments is supported. In case more arguments need
  802. * to be passed and alterable, modules provide additional variables assigned by
  803. * reference in the last $context argument:
  804. * @code
  805. * $context = array(
  806. * 'alterable' => &$alterable,
  807. * 'unalterable' => $unalterable,
  808. * 'foo' => 'bar',
  809. * );
  810. * drupal_alter('mymodule_data', $alterable1, $alterable2, $context);
  811. * @endcode
  812. *
  813. * Note that objects are always passed by reference in PHP5. If it is absolutely
  814. * required that no implementation alters a passed object in $context, then an
  815. * object needs to be cloned:
  816. * @code
  817. * $context = array(
  818. * 'unalterable_object' => clone $object,
  819. * );
  820. * drupal_alter('mymodule_data', $data, $context);
  821. * @endcode
  822. *
  823. * @param $type
  824. * A string describing the type of the alterable $data. 'form', 'links',
  825. * 'node_content', and so on are several examples. Alternatively can be an
  826. * array, in which case hook_TYPE_alter() is invoked for each value in the
  827. * array, ordered first by module, and then for each module, in the order of
  828. * values in $type. For example, when Form API is using drupal_alter() to
  829. * execute both hook_form_alter() and hook_form_FORM_ID_alter()
  830. * implementations, it passes array('form', 'form_' . $form_id) for $type.
  831. * @param $data
  832. * The variable that will be passed to hook_TYPE_alter() implementations to be
  833. * altered. The type of this variable depends on the value of the $type
  834. * argument. For example, when altering a 'form', $data will be a structured
  835. * array. When altering a 'profile', $data will be an object.
  836. * @param $context1
  837. * (optional) An additional variable that is passed by reference.
  838. * @param $context2
  839. * (optional) An additional variable that is passed by reference. If more
  840. * context needs to be provided to implementations, then this should be an
  841. * associative array as described above.
  842. */
  843. function drupal_alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
  844. // Use the advanced drupal_static() pattern, since this is called very often.
  845. static $drupal_static_fast;
  846. if (!isset($drupal_static_fast)) {
  847. $drupal_static_fast['functions'] = &drupal_static(__FUNCTION__);
  848. }
  849. $functions = &$drupal_static_fast['functions'];
  850. // Most of the time, $type is passed as a string, so for performance,
  851. // normalize it to that. When passed as an array, usually the first item in
  852. // the array is a generic type, and additional items in the array are more
  853. // specific variants of it, as in the case of array('form', 'form_FORM_ID').
  854. if (is_array($type)) {
  855. $cid = implode(',', $type);
  856. $extra_types = $type;
  857. $type = array_shift($extra_types);
  858. // Allow if statements in this function to use the faster isset() rather
  859. // than !empty() both when $type is passed as a string, or as an array with
  860. // one item.
  861. if (empty($extra_types)) {
  862. unset($extra_types);
  863. }
  864. }
  865. else {
  866. $cid = $type;
  867. }
  868. // Some alter hooks are invoked many times per page request, so statically
  869. // cache the list of functions to call, and on subsequent calls, iterate
  870. // through them quickly.
  871. if (!isset($functions[$cid])) {
  872. $functions[$cid] = array();
  873. $hook = $type . '_alter';
  874. $modules = module_implements($hook);
  875. if (!isset($extra_types)) {
  876. // For the more common case of a single hook, we do not need to call
  877. // function_exists(), since module_implements() returns only modules with
  878. // implementations.
  879. foreach ($modules as $module) {
  880. $functions[$cid][] = $module . '_' . $hook;
  881. }
  882. }
  883. else {
  884. // For multiple hooks, we need $modules to contain every module that
  885. // implements at least one of them.
  886. $extra_modules = array();
  887. foreach ($extra_types as $extra_type) {
  888. $extra_modules = array_merge($extra_modules, module_implements($extra_type . '_alter'));
  889. }
  890. // If any modules implement one of the extra hooks that do not implement
  891. // the primary hook, we need to add them to the $modules array in their
  892. // appropriate order.
  893. if (array_diff($extra_modules, $modules)) {
  894. // Order the modules by the order returned by module_list().
  895. $modules = array_intersect(module_list(), array_merge($modules, $extra_modules));
  896. }
  897. foreach ($modules as $module) {
  898. // Since $modules is a merged array, for any given module, we do not
  899. // know whether it has any particular implementation, so we need a
  900. // function_exists().
  901. $function = $module . '_' . $hook;
  902. if (function_exists($function)) {
  903. $functions[$cid][] = $function;
  904. }
  905. foreach ($extra_types as $extra_type) {
  906. $function = $module . '_' . $extra_type . '_alter';
  907. if (function_exists($function)) {
  908. $functions[$cid][] = $function;
  909. }
  910. }
  911. }
  912. }
  913. // Allow the theme to alter variables after the theme system has been
  914. // initialized.
  915. global $theme, $base_theme_info;
  916. if (isset($theme)) {
  917. $theme_keys = array();
  918. foreach ($base_theme_info as $base) {
  919. $theme_keys[] = $base->name;
  920. }
  921. $theme_keys[] = $theme;
  922. foreach ($theme_keys as $theme_key) {
  923. $function = $theme_key . '_' . $hook;
  924. if (function_exists($function)) {
  925. $functions[$cid][] = $function;
  926. }
  927. if (isset($extra_types)) {
  928. foreach ($extra_types as $extra_type) {
  929. $function = $theme_key . '_' . $extra_type . '_alter';
  930. if (function_exists($function)) {
  931. $functions[$cid][] = $function;
  932. }
  933. }
  934. }
  935. }
  936. }
  937. }
  938. foreach ($functions[$cid] as $function) {
  939. $function($data, $context1, $context2);
  940. }
  941. }