module.inc

  1. drupal
    1. 4.6 includes/module.inc
    2. 4.7 includes/module.inc
    3. 5 includes/module.inc
    4. 6 includes/module.inc
    5. 7 includes/module.inc
    6. 8 core/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

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. // Update the theme registry to include it.
  404. drupal_theme_rebuild();
  405. // Clear entity cache.
  406. entity_info_cache_clear();
  407. // Now install the module if necessary.
  408. if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
  409. drupal_install_schema($module);
  410. // Set the schema version to the number of the last update provided
  411. // by the module.
  412. $versions = drupal_get_schema_versions($module);
  413. $version = $versions ? max($versions) : SCHEMA_INSTALLED;
  414. // If the module has no current updates, but has some that were
  415. // previously removed, set the version to the value of
  416. // hook_update_last_removed().
  417. if ($last_removed = module_invoke($module, 'update_last_removed')) {
  418. $version = max($version, $last_removed);
  419. }
  420. drupal_set_installed_schema_version($module, $version);
  421. // Allow the module to perform install tasks.
  422. module_invoke($module, 'install');
  423. // Record the fact that it was installed.
  424. $modules_installed[] = $module;
  425. watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
  426. }
  427. // Enable the module.
  428. module_invoke($module, 'enable');
  429. // Record the fact that it was enabled.
  430. $modules_enabled[] = $module;
  431. watchdog('system', '%module module enabled.', array('%module' => $module), WATCHDOG_INFO);
  432. }
  433. }
  434. // If any modules were newly installed, invoke hook_modules_installed().
  435. if (!empty($modules_installed)) {
  436. module_invoke_all('modules_installed', $modules_installed);
  437. }
  438. // If any modules were newly enabled, invoke hook_modules_enabled().
  439. if (!empty($modules_enabled)) {
  440. module_invoke_all('modules_enabled', $modules_enabled);
  441. }
  442. return TRUE;
  443. }
  444. /**
  445. * Disable a given set of modules.
  446. *
  447. * @param $module_list
  448. * An array of module names.
  449. * @param $disable_dependents
  450. * If TRUE, dependent modules will automatically be added and disabled in the
  451. * correct order. This incurs a significant performance cost, so use FALSE
  452. * if you know $module_list is already complete and in the correct order.
  453. */
  454. function module_disable($module_list, $disable_dependents = TRUE) {
  455. if ($disable_dependents) {
  456. // Get all module data so we can find dependents and sort.
  457. $module_data = system_rebuild_module_data();
  458. // Create an associative array with weights as values.
  459. $module_list = array_flip(array_values($module_list));
  460. $profile = drupal_get_profile();
  461. while (list($module) = each($module_list)) {
  462. if (!isset($module_data[$module]) || !$module_data[$module]->status) {
  463. // This module doesn't exist or is already disabled, skip it.
  464. unset($module_list[$module]);
  465. continue;
  466. }
  467. $module_list[$module] = $module_data[$module]->sort;
  468. // Add dependent modules to the list, with a placeholder weight.
  469. // The new modules will be processed as the while loop continues.
  470. foreach ($module_data[$module]->required_by as $dependent => $dependent_data) {
  471. if (!isset($module_list[$dependent]) && $dependent != $profile) {
  472. $module_list[$dependent] = 0;
  473. }
  474. }
  475. }
  476. // Sort the module list by pre-calculated weights.
  477. asort($module_list);
  478. $module_list = array_keys($module_list);
  479. }
  480. $invoke_modules = array();
  481. foreach ($module_list as $module) {
  482. if (module_exists($module)) {
  483. // Check if node_access table needs rebuilding.
  484. if (!node_access_needs_rebuild() && module_hook($module, 'node_grants')) {
  485. node_access_needs_rebuild(TRUE);
  486. }
  487. module_load_install($module);
  488. module_invoke($module, 'disable');
  489. db_update('system')
  490. ->fields(array('status' => 0))
  491. ->condition('type', 'module')
  492. ->condition('name', $module)
  493. ->execute();
  494. $invoke_modules[] = $module;
  495. watchdog('system', '%module module disabled.', array('%module' => $module), WATCHDOG_INFO);
  496. }
  497. }
  498. if (!empty($invoke_modules)) {
  499. // Refresh the module list to exclude the disabled modules.
  500. system_list_reset();
  501. module_list(TRUE);
  502. module_implements('', FALSE, TRUE);
  503. entity_info_cache_clear();
  504. // Invoke hook_modules_disabled before disabling modules,
  505. // so we can still call module hooks to get information.
  506. module_invoke_all('modules_disabled', $invoke_modules);
  507. // Update the registry to remove the newly-disabled module.
  508. registry_update();
  509. _system_update_bootstrap_status();
  510. // Update the theme registry to remove the newly-disabled module.
  511. drupal_theme_rebuild();
  512. }
  513. // If there remains no more node_access module, rebuilding will be
  514. // straightforward, we can do it right now.
  515. if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
  516. node_access_rebuild();
  517. }
  518. }
  519. /**
  520. * @defgroup hooks Hooks
  521. * @{
  522. * Allow modules to interact with the Drupal core.
  523. *
  524. * Drupal's module system is based on the concept of "hooks". A hook is a PHP
  525. * function that is named foo_bar(), where "foo" is the name of the module
  526. * (whose filename is thus foo.module) and "bar" is the name of the hook. Each
  527. * hook has a defined set of parameters and a specified result type.
  528. *
  529. * To extend Drupal, a module need simply implement a hook. When Drupal wishes
  530. * to allow intervention from modules, it determines which modules implement a
  531. * hook and calls that hook in all enabled modules that implement it.
  532. *
  533. * The available hooks to implement are explained here in the Hooks section of
  534. * the developer documentation. The string "hook" is used as a placeholder for
  535. * the module name in the hook definitions. For example, if the module file is
  536. * called example.module, then hook_help() as implemented by that module would
  537. * be defined as example_help().
  538. *
  539. * The example functions included are not part of the Drupal core, they are
  540. * just models that you can modify. Only the hooks implemented within modules
  541. * are executed when running Drupal.
  542. *
  543. * See also @link themeable the themeable group page. @endlink
  544. */
  545. /**
  546. * Determine whether a module implements a hook.
  547. *
  548. * @param $module
  549. * The name of the module (without the .module extension).
  550. * @param $hook
  551. * The name of the hook (e.g. "help" or "menu").
  552. *
  553. * @return
  554. * TRUE if the module is both installed and enabled, and the hook is
  555. * implemented in that module.
  556. */
  557. function module_hook($module, $hook) {
  558. $function = $module . '_' . $hook;
  559. if (function_exists($function)) {
  560. return TRUE;
  561. }
  562. // If the hook implementation does not exist, check whether it may live in an
  563. // optional include file registered via hook_hook_info().
  564. $hook_info = module_hook_info();
  565. if (isset($hook_info[$hook]['group'])) {
  566. module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  567. if (function_exists($function)) {
  568. return TRUE;
  569. }
  570. }
  571. return FALSE;
  572. }
  573. /**
  574. * Determine which modules are implementing a hook.
  575. *
  576. * @param $hook
  577. * The name of the hook (e.g. "help" or "menu").
  578. * @param $sort
  579. * By default, modules are ordered by weight and filename, settings this option
  580. * to TRUE, module list will be ordered by module name.
  581. * @param $reset
  582. * For internal use only: Whether to force the stored list of hook
  583. * implementations to be regenerated (such as after enabling a new module,
  584. * before processing hook_enable).
  585. *
  586. * @return
  587. * An array with the names of the modules which are implementing this hook.
  588. *
  589. * @see module_implements_write_cache()
  590. */
  591. function module_implements($hook, $sort = FALSE, $reset = FALSE) {
  592. // Use the advanced drupal_static() pattern, since this is called very often.
  593. static $drupal_static_fast;
  594. if (!isset($drupal_static_fast)) {
  595. $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  596. }
  597. $implementations = &$drupal_static_fast['implementations'];
  598. // We maintain a persistent cache of hook implementations in addition to the
  599. // static cache to avoid looping through every module and every hook on each
  600. // request. Benchmarks show that the benefit of this caching outweighs the
  601. // additional database hit even when using the default database caching
  602. // backend and only a small number of modules are enabled. The cost of the
  603. // cache_get() is more or less constant and reduced further when non-database
  604. // caching backends are used, so there will be more significant gains when a
  605. // large number of modules are installed or hooks invoked, since this can
  606. // quickly lead to module_hook() being called several thousand times
  607. // per request.
  608. if ($reset) {
  609. $implementations = array();
  610. cache_set('module_implements', array(), 'cache_bootstrap');
  611. drupal_static_reset('module_hook_info');
  612. drupal_static_reset('drupal_alter');
  613. cache_clear_all('hook_info', 'cache_bootstrap');
  614. return;
  615. }
  616. // Fetch implementations from cache.
  617. if (empty($implementations)) {
  618. $implementations = cache_get('module_implements', 'cache_bootstrap');
  619. if ($implementations === FALSE) {
  620. $implementations = array();
  621. }
  622. else {
  623. $implementations = $implementations->data;
  624. }
  625. }
  626. if (!isset($implementations[$hook])) {
  627. // The hook is not cached, so ensure that whether or not it has
  628. // implementations, that the cache is updated at the end of the request.
  629. $implementations['#write_cache'] = TRUE;
  630. $hook_info = module_hook_info();
  631. $implementations[$hook] = array();
  632. $list = module_list(FALSE, FALSE, $sort);
  633. foreach ($list as $module) {
  634. $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  635. // Since module_hook() may needlessly try to load the include file again,
  636. // function_exists() is used directly here.
  637. if (function_exists($module . '_' . $hook)) {
  638. $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  639. }
  640. }
  641. // Allow modules to change the weight of specific implementations but avoid
  642. // an infinite loop.
  643. if ($hook != 'module_implements_alter') {
  644. drupal_alter('module_implements', $implementations[$hook], $hook);
  645. }
  646. }
  647. else {
  648. foreach ($implementations[$hook] as $module => $group) {
  649. // If this hook implementation is stored in a lazy-loaded file, so include
  650. // that file first.
  651. if ($group) {
  652. module_load_include('inc', $module, "$module.$group");
  653. }
  654. // It is possible that a module removed a hook implementation without the
  655. // implementations cache being rebuilt yet, so we check whether the
  656. // function exists on each request to avoid undefined function errors.
  657. // Since module_hook() may needlessly try to load the include file again,
  658. // function_exists() is used directly here.
  659. if (!function_exists($module . '_' . $hook)) {
  660. // Clear out the stale implementation from the cache and force a cache
  661. // refresh to forget about no longer existing hook implementations.
  662. unset($implementations[$hook][$module]);
  663. $implementations['#write_cache'] = TRUE;
  664. }
  665. }
  666. }
  667. return array_keys($implementations[$hook]);
  668. }
  669. /**
  670. * Retrieve a list of what hooks are explicitly declared.
  671. */
  672. function module_hook_info() {
  673. // This function is indirectly invoked from bootstrap_invoke_all(), in which
  674. // case common.inc, subsystems, and modules are not loaded yet, so it does not
  675. // make sense to support hook groups resp. lazy-loaded include files prior to
  676. // full bootstrap.
  677. if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
  678. return array();
  679. }
  680. $hook_info = &drupal_static(__FUNCTION__);
  681. if (!isset($hook_info)) {
  682. $hook_info = array();
  683. $cache = cache_get('hook_info', 'cache_bootstrap');
  684. if ($cache === FALSE) {
  685. // Rebuild the cache and save it.
  686. // We can't use module_invoke_all() here or it would cause an infinite
  687. // loop.
  688. foreach (module_list() as $module) {
  689. $function = $module . '_hook_info';
  690. if (function_exists($function)) {
  691. $result = $function();
  692. if (isset($result) && is_array($result)) {
  693. $hook_info = array_merge_recursive($hook_info, $result);
  694. }
  695. }
  696. }
  697. // We can't use drupal_alter() for the same reason as above.
  698. foreach (module_list() as $module) {
  699. $function = $module . '_hook_info_alter';
  700. if (function_exists($function)) {
  701. $function($hook_info);
  702. }
  703. }
  704. cache_set('hook_info', $hook_info, 'cache_bootstrap');
  705. }
  706. else {
  707. $hook_info = $cache->data;
  708. }
  709. }
  710. return $hook_info;
  711. }
  712. /**
  713. * Writes the hook implementation cache.
  714. *
  715. * @see module_implements()
  716. */
  717. function module_implements_write_cache() {
  718. $implementations = &drupal_static('module_implements');
  719. // Check whether we need to write the cache. We do not want to cache hooks
  720. // which are only invoked on HTTP POST requests since these do not need to be
  721. // optimized as tightly, and not doing so keeps the cache entry smaller.
  722. if (isset($implementations['#write_cache']) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')) {
  723. unset($implementations['#write_cache']);
  724. cache_set('module_implements', $implementations, 'cache_bootstrap');
  725. }
  726. }
  727. /**
  728. * Invoke a hook in a particular module.
  729. *
  730. * @param $module
  731. * The name of the module (without the .module extension).
  732. * @param $hook
  733. * The name of the hook to invoke.
  734. * @param ...
  735. * Arguments to pass to the hook implementation.
  736. *
  737. * @return
  738. * The return value of the hook implementation.
  739. */
  740. function module_invoke($module, $hook) {
  741. $args = func_get_args();
  742. // Remove $module and $hook from the arguments.
  743. unset($args[0], $args[1]);
  744. if (module_hook($module, $hook)) {
  745. return call_user_func_array($module . '_' . $hook, $args);
  746. }
  747. }
  748. /**
  749. * Invoke a hook in all enabled modules that implement it.
  750. *
  751. * @param $hook
  752. * The name of the hook to invoke.
  753. * @param ...
  754. * Arguments to pass to the hook.
  755. *
  756. * @return
  757. * An array of return values of the hook implementations. If modules return
  758. * arrays from their implementations, those are merged into one array.
  759. */
  760. function module_invoke_all($hook) {
  761. $args = func_get_args();
  762. // Remove $hook from the arguments.
  763. unset($args[0]);
  764. $return = array();
  765. foreach (module_implements($hook) as $module) {
  766. $function = $module . '_' . $hook;
  767. if (function_exists($function)) {
  768. $result = call_user_func_array($function, $args);
  769. if (isset($result) && is_array($result)) {
  770. $return = array_merge_recursive($return, $result);
  771. }
  772. elseif (isset($result)) {
  773. $return[] = $result;
  774. }
  775. }
  776. }
  777. return $return;
  778. }
  779. /**
  780. * @} End of "defgroup hooks".
  781. */
  782. /**
  783. * Array of modules required by core.
  784. */
  785. function drupal_required_modules() {
  786. $files = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', 'modules', 'name', 0);
  787. $required = array();
  788. // An install profile is required and one must always be loaded.
  789. $required[] = drupal_get_profile();
  790. foreach ($files as $name => $file) {
  791. $info = drupal_parse_info_file($file->uri);
  792. if (!empty($info) && !empty($info['required']) && $info['required']) {
  793. $required[] = $name;
  794. }
  795. }
  796. return $required;
  797. }
  798. /**
  799. * Hands off alterable variables to type-specific *_alter implementations.
  800. *
  801. * This dispatch function hands off the passed-in variables to type-specific
  802. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  803. * interface for all altering operations.
  804. *
  805. * A maximum of 2 alterable arguments is supported. In case more arguments need
  806. * to be passed and alterable, modules provide additional variables assigned by
  807. * reference in the last $context argument:
  808. * @code
  809. * $context = array(
  810. * 'alterable' => &$alterable,
  811. * 'unalterable' => $unalterable,
  812. * 'foo' => 'bar',
  813. * );
  814. * drupal_alter('mymodule_data', $alterable1, $alterable2, $context);
  815. * @endcode
  816. *
  817. * Note that objects are always passed by reference in PHP5. If it is absolutely
  818. * required that no implementation alters a passed object in $context, then an
  819. * object needs to be cloned:
  820. * @code
  821. * $context = array(
  822. * 'unalterable_object' => clone $object,
  823. * );
  824. * drupal_alter('mymodule_data', $data, $context);
  825. * @endcode
  826. *
  827. * @param $type
  828. * A string describing the type of the alterable $data. 'form', 'links',
  829. * 'node_content', and so on are several examples. Alternatively can be an
  830. * array, in which case hook_TYPE_alter() is invoked for each value in the
  831. * array, ordered first by module, and then for each module, in the order of
  832. * values in $type. For example, when Form API is using drupal_alter() to
  833. * execute both hook_form_alter() and hook_form_FORM_ID_alter()
  834. * implementations, it passes array('form', 'form_' . $form_id) for $type.
  835. * @param $data
  836. * The variable that will be passed to hook_TYPE_alter() implementations to be
  837. * altered. The type of this variable depends on the value of the $type
  838. * argument. For example, when altering a 'form', $data will be a structured
  839. * array. When altering a 'profile', $data will be an object.
  840. * @param $context1
  841. * (optional) An additional variable that is passed by reference.
  842. * @param $context2
  843. * (optional) An additional variable that is passed by reference. If more
  844. * context needs to be provided to implementations, then this should be an
  845. * associative array as described above.
  846. */
  847. function drupal_alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
  848. // Use the advanced drupal_static() pattern, since this is called very often.
  849. static $drupal_static_fast;
  850. if (!isset($drupal_static_fast)) {
  851. $drupal_static_fast['functions'] = &drupal_static(__FUNCTION__);
  852. }
  853. $functions = &$drupal_static_fast['functions'];
  854. // Most of the time, $type is passed as a string, so for performance,
  855. // normalize it to that. When passed as an array, usually the first item in
  856. // the array is a generic type, and additional items in the array are more
  857. // specific variants of it, as in the case of array('form', 'form_FORM_ID').
  858. if (is_array($type)) {
  859. $cid = implode(',', $type);
  860. $extra_types = $type;
  861. $type = array_shift($extra_types);
  862. // Allow if statements in this function to use the faster isset() rather
  863. // than !empty() both when $type is passed as a string, or as an array with
  864. // one item.
  865. if (empty($extra_types)) {
  866. unset($extra_types);
  867. }
  868. }
  869. else {
  870. $cid = $type;
  871. }
  872. // Some alter hooks are invoked many times per page request, so statically
  873. // cache the list of functions to call, and on subsequent calls, iterate
  874. // through them quickly.
  875. if (!isset($functions[$cid])) {
  876. $functions[$cid] = array();
  877. $hook = $type . '_alter';
  878. $modules = module_implements($hook);
  879. if (!isset($extra_types)) {
  880. // For the more common case of a single hook, we do not need to call
  881. // function_exists(), since module_implements() returns only modules with
  882. // implementations.
  883. foreach ($modules as $module) {
  884. $functions[$cid][] = $module . '_' . $hook;
  885. }
  886. }
  887. else {
  888. // For multiple hooks, we need $modules to contain every module that
  889. // implements at least one of them.
  890. $extra_modules = array();
  891. foreach ($extra_types as $extra_type) {
  892. $extra_modules = array_merge($extra_modules, module_implements($extra_type . '_alter'));
  893. }
  894. // If any modules implement one of the extra hooks that do not implement
  895. // the primary hook, we need to add them to the $modules array in their
  896. // appropriate order. module_implements() can only return ordered
  897. // implementations of a single hook. To get the ordered implementations
  898. // of multiple hooks, we mimic the module_implements() logic of first
  899. // ordering by module_list(), and then calling
  900. // drupal_alter('module_implements').
  901. if (array_diff($extra_modules, $modules)) {
  902. // Merge the arrays and order by module_list().
  903. $modules = array_intersect(module_list(), array_merge($modules, $extra_modules));
  904. // Since module_implements() already took care of loading the necessary
  905. // include files, we can safely pass FALSE for the array values.
  906. $implementations = array_fill_keys($modules, FALSE);
  907. // Let modules adjust the order solely based on the primary hook. This
  908. // ensures the same module order regardless of whether this if block
  909. // runs. Calling drupal_alter() recursively in this way does not result
  910. // in an infinite loop, because this call is for a single $type, so we
  911. // won't end up in this code block again.
  912. drupal_alter('module_implements', $implementations, $hook);
  913. $modules = array_keys($implementations);
  914. }
  915. foreach ($modules as $module) {
  916. // Since $modules is a merged array, for any given module, we do not
  917. // know whether it has any particular implementation, so we need a
  918. // function_exists().
  919. $function = $module . '_' . $hook;
  920. if (function_exists($function)) {
  921. $functions[$cid][] = $function;
  922. }
  923. foreach ($extra_types as $extra_type) {
  924. $function = $module . '_' . $extra_type . '_alter';
  925. if (function_exists($function)) {
  926. $functions[$cid][] = $function;
  927. }
  928. }
  929. }
  930. }
  931. // Allow the theme to alter variables after the theme system has been
  932. // initialized.
  933. global $theme, $base_theme_info;
  934. if (isset($theme)) {
  935. $theme_keys = array();
  936. foreach ($base_theme_info as $base) {
  937. $theme_keys[] = $base->name;
  938. }
  939. $theme_keys[] = $theme;
  940. foreach ($theme_keys as $theme_key) {
  941. $function = $theme_key . '_' . $hook;
  942. if (function_exists($function)) {
  943. $functions[$cid][] = $function;
  944. }
  945. if (isset($extra_types)) {
  946. foreach ($extra_types as $extra_type) {
  947. $function = $theme_key . '_' . $extra_type . '_alter';
  948. if (function_exists($function)) {
  949. $functions[$cid][] = $function;
  950. }
  951. }
  952. }
  953. }
  954. }
  955. }
  956. foreach ($functions[$cid] as $function) {
  957. $function($data, $context1, $context2);
  958. }
  959. }
Login or register to post comments