module.inc 39 KB

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