module.inc 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. foreach ($lists['theme'] as $key => $theme) {
  174. if (!empty($theme->info['base theme'])) {
  175. // Make a list of the theme's base themes.
  176. $lists['theme'][$key]->base_themes = drupal_find_base_themes($lists['theme'], $key);
  177. // Don't proceed if there was a problem with the root base theme.
  178. if (!current($lists['theme'][$key]->base_themes)) {
  179. continue;
  180. }
  181. // Determine the root base theme.
  182. $base_key = key($lists['theme'][$key]->base_themes);
  183. // Add to the list of sub-themes for each of the theme's base themes.
  184. foreach (array_keys($lists['theme'][$key]->base_themes) as $base_theme) {
  185. $lists['theme'][$base_theme]->sub_themes[$key] = $lists['theme'][$key]->info['name'];
  186. }
  187. // Add the base theme's theme engine info.
  188. $lists['theme'][$key]->info['engine'] = isset($lists['theme'][$base_key]->info['engine']) ? $lists['theme'][$base_key]->info['engine'] : 'theme';
  189. }
  190. else {
  191. // A plain theme is its own engine.
  192. $base_key = $key;
  193. if (!isset($lists['theme'][$key]->info['engine'])) {
  194. $lists['theme'][$key]->info['engine'] = 'theme';
  195. }
  196. }
  197. // Set the theme engine prefix.
  198. $lists['theme'][$key]->prefix = ($lists['theme'][$key]->info['engine'] == 'theme') ? $base_key : $lists['theme'][$key]->info['engine'];
  199. }
  200. cache_set('system_list', $lists, 'cache_bootstrap');
  201. }
  202. // To avoid a separate database lookup for the filepath, prime the
  203. // drupal_get_filename() static cache with all enabled modules and themes.
  204. foreach ($lists['filepaths'] as $item) {
  205. drupal_get_filename($item['type'], $item['name'], $item['filepath']);
  206. }
  207. }
  208. return $lists[$type];
  209. }
  210. /**
  211. * Reset all system_list() caches.
  212. */
  213. function system_list_reset() {
  214. drupal_static_reset('system_list');
  215. drupal_static_reset('system_rebuild_module_data');
  216. drupal_static_reset('list_themes');
  217. cache_clear_all('bootstrap_modules', 'cache_bootstrap');
  218. cache_clear_all('system_list', 'cache_bootstrap');
  219. }
  220. /**
  221. * Find dependencies any level deep and fill in required by information too.
  222. *
  223. * @param $files
  224. * The array of filesystem objects used to rebuild the cache.
  225. *
  226. * @return
  227. * The same array with the new keys for each module:
  228. * - requires: An array with the keys being the modules that this module
  229. * requires.
  230. * - required_by: An array with the keys being the modules that will not work
  231. * without this module.
  232. */
  233. function _module_build_dependencies($files) {
  234. require_once DRUPAL_ROOT . '/includes/graph.inc';
  235. foreach ($files as $filename => $file) {
  236. $graph[$file->name]['edges'] = array();
  237. if (isset($file->info['dependencies']) && is_array($file->info['dependencies'])) {
  238. foreach ($file->info['dependencies'] as $dependency) {
  239. $dependency_data = drupal_parse_dependency($dependency);
  240. $graph[$file->name]['edges'][$dependency_data['name']] = $dependency_data;
  241. }
  242. }
  243. }
  244. drupal_depth_first_search($graph);
  245. foreach ($graph as $module => $data) {
  246. $files[$module]->required_by = isset($data['reverse_paths']) ? $data['reverse_paths'] : array();
  247. $files[$module]->requires = isset($data['paths']) ? $data['paths'] : array();
  248. $files[$module]->sort = $data['weight'];
  249. }
  250. return $files;
  251. }
  252. /**
  253. * Determine whether a given module exists.
  254. *
  255. * @param $module
  256. * The name of the module (without the .module extension).
  257. *
  258. * @return
  259. * TRUE if the module is both installed and enabled.
  260. */
  261. function module_exists($module) {
  262. $list = module_list();
  263. return isset($list[$module]);
  264. }
  265. /**
  266. * Load a module's installation hooks.
  267. *
  268. * @param $module
  269. * The name of the module (without the .module extension).
  270. *
  271. * @return
  272. * The name of the module's install file, if successful; FALSE otherwise.
  273. */
  274. function module_load_install($module) {
  275. // Make sure the installation API is available
  276. include_once DRUPAL_ROOT . '/includes/install.inc';
  277. return module_load_include('install', $module);
  278. }
  279. /**
  280. * Load a module include file.
  281. *
  282. * Examples:
  283. * @code
  284. * // Load node.admin.inc from the node module.
  285. * module_load_include('inc', 'node', 'node.admin');
  286. * // Load content_types.inc from the node module.
  287. * module_load_include('inc', 'node', 'content_types');
  288. * @endcode
  289. *
  290. * Do not use this function to load an install file, use module_load_install()
  291. * instead. Do not use this function in a global context since it requires
  292. * Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file'
  293. * instead.
  294. *
  295. * @param $type
  296. * The include file's type (file extension).
  297. * @param $module
  298. * The module to which the include file belongs.
  299. * @param $name
  300. * (optional) The base file name (without the $type extension). If omitted,
  301. * $module is used; i.e., resulting in "$module.$type" by default.
  302. *
  303. * @return
  304. * The name of the included file, if successful; FALSE otherwise.
  305. */
  306. function module_load_include($type, $module, $name = NULL) {
  307. if (!isset($name)) {
  308. $name = $module;
  309. }
  310. if (function_exists('drupal_get_path')) {
  311. $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
  312. if (is_file($file)) {
  313. require_once $file;
  314. return $file;
  315. }
  316. }
  317. return FALSE;
  318. }
  319. /**
  320. * Load an include file for each of the modules that have been enabled in
  321. * 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. * Disable 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 also @link themeable the themeable group page. @endlink
  571. */
  572. /**
  573. * Determine whether a module implements a hook.
  574. *
  575. * @param $module
  576. * The name of the module (without the .module extension).
  577. * @param $hook
  578. * The name of the hook (e.g. "help" or "menu").
  579. *
  580. * @return
  581. * TRUE if the module is both installed and enabled, and the hook is
  582. * implemented in that module.
  583. */
  584. function module_hook($module, $hook) {
  585. $function = $module . '_' . $hook;
  586. if (function_exists($function)) {
  587. return TRUE;
  588. }
  589. // If the hook implementation does not exist, check whether it may live in an
  590. // optional include file registered via hook_hook_info().
  591. $hook_info = module_hook_info();
  592. if (isset($hook_info[$hook]['group'])) {
  593. module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  594. if (function_exists($function)) {
  595. return TRUE;
  596. }
  597. }
  598. return FALSE;
  599. }
  600. /**
  601. * Determine which modules are implementing a hook.
  602. *
  603. * @param $hook
  604. * The name of the hook (e.g. "help" or "menu").
  605. * @param $sort
  606. * By default, modules are ordered by weight and filename, settings this option
  607. * to TRUE, module list will be ordered by module name.
  608. * @param $reset
  609. * For internal use only: Whether to force the stored list of hook
  610. * implementations to be regenerated (such as after enabling a new module,
  611. * before processing hook_enable).
  612. *
  613. * @return
  614. * An array with the names of the modules which are implementing this hook.
  615. *
  616. * @see module_implements_write_cache()
  617. */
  618. function module_implements($hook, $sort = FALSE, $reset = FALSE) {
  619. // Use the advanced drupal_static() pattern, since this is called very often.
  620. static $drupal_static_fast;
  621. if (!isset($drupal_static_fast)) {
  622. $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  623. }
  624. $implementations = &$drupal_static_fast['implementations'];
  625. // We maintain a persistent cache of hook implementations in addition to the
  626. // static cache to avoid looping through every module and every hook on each
  627. // request. Benchmarks show that the benefit of this caching outweighs the
  628. // additional database hit even when using the default database caching
  629. // backend and only a small number of modules are enabled. The cost of the
  630. // cache_get() is more or less constant and reduced further when non-database
  631. // caching backends are used, so there will be more significant gains when a
  632. // large number of modules are installed or hooks invoked, since this can
  633. // quickly lead to module_hook() being called several thousand times
  634. // per request.
  635. if ($reset) {
  636. $implementations = array();
  637. cache_set('module_implements', array(), 'cache_bootstrap');
  638. drupal_static_reset('module_hook_info');
  639. drupal_static_reset('drupal_alter');
  640. cache_clear_all('hook_info', 'cache_bootstrap');
  641. return;
  642. }
  643. // Fetch implementations from cache.
  644. if (empty($implementations)) {
  645. $implementations = cache_get('module_implements', 'cache_bootstrap');
  646. if ($implementations === FALSE) {
  647. $implementations = array();
  648. }
  649. else {
  650. $implementations = $implementations->data;
  651. }
  652. }
  653. if (!isset($implementations[$hook])) {
  654. // The hook is not cached, so ensure that whether or not it has
  655. // implementations, that the cache is updated at the end of the request.
  656. $implementations['#write_cache'] = TRUE;
  657. $hook_info = module_hook_info();
  658. $implementations[$hook] = array();
  659. $list = module_list(FALSE, FALSE, $sort);
  660. foreach ($list as $module) {
  661. $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  662. // Since module_hook() may needlessly try to load the include file again,
  663. // function_exists() is used directly here.
  664. if (function_exists($module . '_' . $hook)) {
  665. $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  666. }
  667. }
  668. // Allow modules to change the weight of specific implementations but avoid
  669. // an infinite loop.
  670. if ($hook != 'module_implements_alter') {
  671. drupal_alter('module_implements', $implementations[$hook], $hook);
  672. }
  673. }
  674. else {
  675. foreach ($implementations[$hook] as $module => $group) {
  676. // If this hook implementation is stored in a lazy-loaded file, so include
  677. // that file first.
  678. if ($group) {
  679. module_load_include('inc', $module, "$module.$group");
  680. }
  681. // It is possible that a module removed a hook implementation without the
  682. // implementations cache being rebuilt yet, so we check whether the
  683. // function exists on each request to avoid undefined function errors.
  684. // Since module_hook() may needlessly try to load the include file again,
  685. // function_exists() is used directly here.
  686. if (!function_exists($module . '_' . $hook)) {
  687. // Clear out the stale implementation from the cache and force a cache
  688. // refresh to forget about no longer existing hook implementations.
  689. unset($implementations[$hook][$module]);
  690. $implementations['#write_cache'] = TRUE;
  691. }
  692. }
  693. }
  694. return array_keys($implementations[$hook]);
  695. }
  696. /**
  697. * Retrieve a list of what hooks are explicitly declared.
  698. */
  699. function module_hook_info() {
  700. // This function is indirectly invoked from bootstrap_invoke_all(), in which
  701. // case common.inc, subsystems, and modules are not loaded yet, so it does not
  702. // make sense to support hook groups resp. lazy-loaded include files prior to
  703. // full bootstrap.
  704. if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
  705. return array();
  706. }
  707. $hook_info = &drupal_static(__FUNCTION__);
  708. if (!isset($hook_info)) {
  709. $hook_info = array();
  710. $cache = cache_get('hook_info', 'cache_bootstrap');
  711. if ($cache === FALSE) {
  712. // Rebuild the cache and save it.
  713. // We can't use module_invoke_all() here or it would cause an infinite
  714. // loop.
  715. foreach (module_list() as $module) {
  716. $function = $module . '_hook_info';
  717. if (function_exists($function)) {
  718. $result = $function();
  719. if (isset($result) && is_array($result)) {
  720. $hook_info = array_merge_recursive($hook_info, $result);
  721. }
  722. }
  723. }
  724. // We can't use drupal_alter() for the same reason as above.
  725. foreach (module_list() as $module) {
  726. $function = $module . '_hook_info_alter';
  727. if (function_exists($function)) {
  728. $function($hook_info);
  729. }
  730. }
  731. cache_set('hook_info', $hook_info, 'cache_bootstrap');
  732. }
  733. else {
  734. $hook_info = $cache->data;
  735. }
  736. }
  737. return $hook_info;
  738. }
  739. /**
  740. * Writes the hook implementation cache.
  741. *
  742. * @see module_implements()
  743. */
  744. function module_implements_write_cache() {
  745. $implementations = &drupal_static('module_implements');
  746. // Check whether we need to write the cache. We do not want to cache hooks
  747. // which are only invoked on HTTP POST requests since these do not need to be
  748. // optimized as tightly, and not doing so keeps the cache entry smaller.
  749. if (isset($implementations['#write_cache']) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')) {
  750. unset($implementations['#write_cache']);
  751. cache_set('module_implements', $implementations, 'cache_bootstrap');
  752. }
  753. }
  754. /**
  755. * Invoke a hook in a particular module.
  756. *
  757. * @param $module
  758. * The name of the module (without the .module extension).
  759. * @param $hook
  760. * The name of the hook to invoke.
  761. * @param ...
  762. * Arguments to pass to the hook implementation.
  763. *
  764. * @return
  765. * The return value of the hook implementation.
  766. */
  767. function module_invoke($module, $hook) {
  768. $args = func_get_args();
  769. // Remove $module and $hook from the arguments.
  770. unset($args[0], $args[1]);
  771. if (module_hook($module, $hook)) {
  772. return call_user_func_array($module . '_' . $hook, $args);
  773. }
  774. }
  775. /**
  776. * Invoke a hook in all enabled modules that implement it.
  777. *
  778. * @param $hook
  779. * The name of the hook to invoke.
  780. * @param ...
  781. * Arguments to pass to the hook.
  782. *
  783. * @return
  784. * An array of return values of the hook implementations. If modules return
  785. * arrays from their implementations, those are merged into one array.
  786. */
  787. function module_invoke_all($hook) {
  788. $args = func_get_args();
  789. // Remove $hook from the arguments.
  790. unset($args[0]);
  791. $return = array();
  792. foreach (module_implements($hook) as $module) {
  793. $function = $module . '_' . $hook;
  794. if (function_exists($function)) {
  795. $result = call_user_func_array($function, $args);
  796. if (isset($result) && is_array($result)) {
  797. $return = array_merge_recursive($return, $result);
  798. }
  799. elseif (isset($result)) {
  800. $return[] = $result;
  801. }
  802. }
  803. }
  804. return $return;
  805. }
  806. /**
  807. * @} End of "defgroup hooks".
  808. */
  809. /**
  810. * Array of modules required by core.
  811. */
  812. function drupal_required_modules() {
  813. $files = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', 'modules', 'name', 0);
  814. $required = array();
  815. // An install profile is required and one must always be loaded.
  816. $required[] = drupal_get_profile();
  817. foreach ($files as $name => $file) {
  818. $info = drupal_parse_info_file($file->uri);
  819. if (!empty($info) && !empty($info['required']) && $info['required']) {
  820. $required[] = $name;
  821. }
  822. }
  823. return $required;
  824. }
  825. /**
  826. * Hands off alterable variables to type-specific *_alter implementations.
  827. *
  828. * This dispatch function hands off the passed-in variables to type-specific
  829. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  830. * interface for all altering operations.
  831. *
  832. * A maximum of 2 alterable arguments is supported. In case more arguments need
  833. * to be passed and alterable, modules provide additional variables assigned by
  834. * reference in the last $context argument:
  835. * @code
  836. * $context = array(
  837. * 'alterable' => &$alterable,
  838. * 'unalterable' => $unalterable,
  839. * 'foo' => 'bar',
  840. * );
  841. * drupal_alter('mymodule_data', $alterable1, $alterable2, $context);
  842. * @endcode
  843. *
  844. * Note that objects are always passed by reference in PHP5. If it is absolutely
  845. * required that no implementation alters a passed object in $context, then an
  846. * object needs to be cloned:
  847. * @code
  848. * $context = array(
  849. * 'unalterable_object' => clone $object,
  850. * );
  851. * drupal_alter('mymodule_data', $data, $context);
  852. * @endcode
  853. *
  854. * @param $type
  855. * A string describing the type of the alterable $data. 'form', 'links',
  856. * 'node_content', and so on are several examples. Alternatively can be an
  857. * array, in which case hook_TYPE_alter() is invoked for each value in the
  858. * array, ordered first by module, and then for each module, in the order of
  859. * values in $type. For example, when Form API is using drupal_alter() to
  860. * execute both hook_form_alter() and hook_form_FORM_ID_alter()
  861. * implementations, it passes array('form', 'form_' . $form_id) for $type.
  862. * @param $data
  863. * The variable that will be passed to hook_TYPE_alter() implementations to be
  864. * altered. The type of this variable depends on the value of the $type
  865. * argument. For example, when altering a 'form', $data will be a structured
  866. * array. When altering a 'profile', $data will be an object.
  867. * @param $context1
  868. * (optional) An additional variable that is passed by reference.
  869. * @param $context2
  870. * (optional) An additional variable that is passed by reference. If more
  871. * context needs to be provided to implementations, then this should be an
  872. * associative array as described above.
  873. */
  874. function drupal_alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
  875. // Use the advanced drupal_static() pattern, since this is called very often.
  876. static $drupal_static_fast;
  877. if (!isset($drupal_static_fast)) {
  878. $drupal_static_fast['functions'] = &drupal_static(__FUNCTION__);
  879. }
  880. $functions = &$drupal_static_fast['functions'];
  881. // Most of the time, $type is passed as a string, so for performance,
  882. // normalize it to that. When passed as an array, usually the first item in
  883. // the array is a generic type, and additional items in the array are more
  884. // specific variants of it, as in the case of array('form', 'form_FORM_ID').
  885. if (is_array($type)) {
  886. $cid = implode(',', $type);
  887. $extra_types = $type;
  888. $type = array_shift($extra_types);
  889. // Allow if statements in this function to use the faster isset() rather
  890. // than !empty() both when $type is passed as a string, or as an array with
  891. // one item.
  892. if (empty($extra_types)) {
  893. unset($extra_types);
  894. }
  895. }
  896. else {
  897. $cid = $type;
  898. }
  899. // Some alter hooks are invoked many times per page request, so statically
  900. // cache the list of functions to call, and on subsequent calls, iterate
  901. // through them quickly.
  902. if (!isset($functions[$cid])) {
  903. $functions[$cid] = array();
  904. $hook = $type . '_alter';
  905. $modules = module_implements($hook);
  906. if (!isset($extra_types)) {
  907. // For the more common case of a single hook, we do not need to call
  908. // function_exists(), since module_implements() returns only modules with
  909. // implementations.
  910. foreach ($modules as $module) {
  911. $functions[$cid][] = $module . '_' . $hook;
  912. }
  913. }
  914. else {
  915. // For multiple hooks, we need $modules to contain every module that
  916. // implements at least one of them.
  917. $extra_modules = array();
  918. foreach ($extra_types as $extra_type) {
  919. $extra_modules = array_merge($extra_modules, module_implements($extra_type . '_alter'));
  920. }
  921. // If any modules implement one of the extra hooks that do not implement
  922. // the primary hook, we need to add them to the $modules array in their
  923. // appropriate order. module_implements() can only return ordered
  924. // implementations of a single hook. To get the ordered implementations
  925. // of multiple hooks, we mimic the module_implements() logic of first
  926. // ordering by module_list(), and then calling
  927. // drupal_alter('module_implements').
  928. if (array_diff($extra_modules, $modules)) {
  929. // Merge the arrays and order by module_list().
  930. $modules = array_intersect(module_list(), array_merge($modules, $extra_modules));
  931. // Since module_implements() already took care of loading the necessary
  932. // include files, we can safely pass FALSE for the array values.
  933. $implementations = array_fill_keys($modules, FALSE);
  934. // Let modules adjust the order solely based on the primary hook. This
  935. // ensures the same module order regardless of whether this if block
  936. // runs. Calling drupal_alter() recursively in this way does not result
  937. // in an infinite loop, because this call is for a single $type, so we
  938. // won't end up in this code block again.
  939. drupal_alter('module_implements', $implementations, $hook);
  940. $modules = array_keys($implementations);
  941. }
  942. foreach ($modules as $module) {
  943. // Since $modules is a merged array, for any given module, we do not
  944. // know whether it has any particular implementation, so we need a
  945. // function_exists().
  946. $function = $module . '_' . $hook;
  947. if (function_exists($function)) {
  948. $functions[$cid][] = $function;
  949. }
  950. foreach ($extra_types as $extra_type) {
  951. $function = $module . '_' . $extra_type . '_alter';
  952. if (function_exists($function)) {
  953. $functions[$cid][] = $function;
  954. }
  955. }
  956. }
  957. }
  958. // Allow the theme to alter variables after the theme system has been
  959. // initialized.
  960. global $theme, $base_theme_info;
  961. if (isset($theme)) {
  962. $theme_keys = array();
  963. foreach ($base_theme_info as $base) {
  964. $theme_keys[] = $base->name;
  965. }
  966. $theme_keys[] = $theme;
  967. foreach ($theme_keys as $theme_key) {
  968. $function = $theme_key . '_' . $hook;
  969. if (function_exists($function)) {
  970. $functions[$cid][] = $function;
  971. }
  972. if (isset($extra_types)) {
  973. foreach ($extra_types as $extra_type) {
  974. $function = $theme_key . '_' . $extra_type . '_alter';
  975. if (function_exists($function)) {
  976. $functions[$cid][] = $function;
  977. }
  978. }
  979. }
  980. }
  981. }
  982. }
  983. foreach ($functions[$cid] as $function) {
  984. $function($data, $context1, $context2);
  985. }
  986. }