system.api.php

  1. drupal
    1. 7 modules/system/system.api.php
    2. 8 core/modules/system/system.api.php

Hooks provided by Drupal core and the System module.

Functions & methods

NameDescription
hook_actions_deleteExecutes code after an action is deleted.
hook_action_infoDeclares information about actions.
hook_action_info_alterAlters the actions declared by another module.
hook_admin_pathsDefine administrative paths.
hook_admin_paths_alterRedefine administrative paths defined by other modules.
hook_ajax_render_alterAlter the commands that are sent to the user through the Ajax framework.
hook_archiver_infoDeclare archivers to the system.
hook_archiver_info_alterAlter archiver information declared by other modules.
hook_batch_alterAlter batch information before a batch is processed.
hook_bootPerform setup tasks for all page requests.
hook_cache_flushFlush all persistent and static caches.
hook_countries_alterAlter the default country list.
hook_cronPerform periodic actions.
hook_css_alterAlter CSS files before they are output on the page.
hook_custom_themeReturn the machine-readable name of the theme to use for the current page.
hook_date_formatsDefine additional date formats.
hook_date_formats_alterAlter date formats declared by another module.
hook_date_format_typesDefine additional date types.
hook_date_format_types_alterModify existing date types.
hook_disablePerform necessary actions before module is disabled.
hook_drupal_goto_alterChange the page the user is sent to by drupal_goto().
hook_element_infoAllows modules to declare their own Forms API element types and specify their default values.
hook_element_info_alterAlter the element type information returned from modules.
hook_enablePerform necessary actions after module is enabled.
hook_exitPerform cleanup tasks.
hook_filetransfer_infoRegister information about FileTransfer classes provided by a module.
hook_filetransfer_info_alterAlter the FileTransfer class registry.
hook_file_copyRespond to a file that has been copied.
hook_file_deleteRespond to file deletion.
hook_file_downloadControl access to private file downloads and specify HTTP headers.
hook_file_insertRespond to a file being added.
hook_file_loadLoad additional information into file objects.
hook_file_mimetype_mapping_alterAlter MIME type mappings used to determine MIME type from a file extension.
hook_file_moveRespond to a file that has been moved.
hook_file_predeleteAct prior to file deletion.
hook_file_presaveAct on a file being inserted or updated.
hook_file_updateRespond to a file being updated.
hook_file_url_alterAlter the URL to a file.
hook_file_validateCheck that files meet a given criteria.
hook_formsMap form_ids to form builder functions.
hook_form_alterPerform alterations before a form is rendered.
hook_form_BASE_FORM_ID_alterProvide a form-specific alteration for shared ('base') forms.
hook_form_FORM_ID_alterProvide a form-specific alteration instead of the global hook_form_alter().
hook_hook_infoDefines one or more hooks that are exposed by a module.
hook_hook_info_alterAlter information from hook_hook_info().
hook_html_head_alterAlter XHTML HEAD tags before they are rendered by drupal_get_html_head().
hook_image_toolkitsDefine image toolkits provided by this module.
hook_initPerform setup tasks for non-cached page requests.
hook_installPerform setup tasks when the module is installed.
hook_install_tasksReturn an array of tasks to be performed by an installation profile.
hook_install_tasks_alterAlter the full list of installation tasks.
hook_js_alterPerform necessary alterations to the JavaScript before it is presented on the page.
hook_library_infoRegisters JavaScript/CSS libraries associated with a module.
hook_library_info_alterAlters the JavaScript/CSS library registry.
hook_mailPrepare a message based on parameters; called from drupal_mail().
hook_mail_alterAlter an email message created with the drupal_mail() function.
hook_menuDefine menu items and page callbacks.
hook_menu_alterAlter the data being saved to the {menu_router} table after hook_menu is invoked.
hook_menu_breadcrumb_alterAlter links in the active trail before it is rendered as the breadcrumb.
hook_menu_contextual_links_alterAlter contextual links before they are rendered.
hook_menu_get_item_alterAlter a menu router item right after it has been retrieved from the database or cache.
hook_menu_link_alterAlter the data being saved to the {menu_links} table by menu_link_save().
hook_menu_link_deleteInform modules that a menu link has been deleted.
hook_menu_link_insertInform modules that a menu link has been created.
hook_menu_link_updateInform modules that a menu link has been updated.
hook_menu_local_tasks_alterAlter tabs and actions displayed on the page before they are rendered.
hook_menu_site_status_alterControl site status before menu dispatching.
hook_modules_disabledPerform necessary actions after modules are disabled.
hook_modules_enabledPerform necessary actions after modules are enabled.
hook_modules_installedPerform necessary actions after modules are installed.
hook_modules_preenablePerform necessary actions before modules are enabled.
hook_modules_preinstallPerform necessary actions before modules are installed.
hook_modules_uninstalledPerform necessary actions after modules are uninstalled.
hook_module_implements_alterAlter the registry of modules implementing a hook.
hook_page_alterPerform alterations before a page is rendered.
hook_page_buildAdd elements to a page before it is rendered.
hook_page_delivery_callback_alterAlters the delivery callback used to send the result of the page callback to the browser.
hook_permissionDefine user permissions.
hook_query_alterPerform alterations to a structured query.
hook_query_TAG_alterPerform alterations to a structured query for a given tag.
hook_queue_infoDeclare queues holding items that need to be run periodically.
hook_queue_info_alterAlter cron queue information before cron runs.
hook_rebuildRebuild data based upon refreshed caches.
hook_registry_files_alterPerform necessary alterations to the list of files parsed by the registry.
hook_requirementsCheck installation requirements and do status reporting.
hook_schemaDefine the current version of the database schema.
hook_schema_alterPerform alterations to existing database schemas.
hook_stream_wrappersRegisters PHP stream wrapper implementations associated with a module.
hook_stream_wrappers_alterAlters the list of PHP stream wrapper implementations.
hook_system_info_alterAlter the information parsed from module and theme .info files
hook_system_themes_page_alterAlters theme operation links.
hook_system_theme_infoReturn additional themes provided by modules.
hook_themeRegister a module (or theme's) theme implementations.
hook_theme_registry_alterAlter the theme registry information returned from hook_theme().
hook_tokensProvide replacement values for placeholder tokens.
hook_tokens_alterAlter replacement values for placeholder tokens.
hook_token_infoProvide information about available placeholder tokens and token types.
hook_token_info_alterAlter the metadata about available placeholder tokens and token types.
hook_translated_menu_link_alterAlter a menu link after it has been translated and before it is rendered.
hook_uninstallRemove any information that the module sets.
hook_updater_infoProvide information on Updaters (classes that can update Drupal).
hook_updater_info_alterAlter the Updater information array.
hook_update_dependenciesReturn an array of information about module update dependencies.
hook_update_last_removedReturn a number which is no longer available as hook_update_N().
hook_update_NPerform a single update.
hook_url_inbound_alterAlters inbound URL requests.
hook_url_outbound_alterAlters outbound URLs.
hook_watchdogLog an event message.
hook_xmlrpcRegister XML-RPC callbacks.
hook_xmlrpc_alterAlters the definition of XML-RPC methods before they are called.

File

core/modules/system/system.api.php
View source
  1. <?php
  2. /**
  3. * @file
  4. * Hooks provided by Drupal core and the System module.
  5. */
  6. /**
  7. * @addtogroup hooks
  8. * @{
  9. */
  10. /**
  11. * Defines one or more hooks that are exposed by a module.
  12. *
  13. * Normally hooks do not need to be explicitly defined. However, by declaring a
  14. * hook explicitly, a module may define a "group" for it. Modules that implement
  15. * a hook may then place their implementation in either $module.module or in
  16. * $module.$group.inc. If the hook is located in $module.$group.inc, then that
  17. * file will be automatically loaded when needed.
  18. * In general, hooks that are rarely invoked and/or are very large should be
  19. * placed in a separate include file, while hooks that are very short or very
  20. * frequently called should be left in the main module file so that they are
  21. * always available.
  22. *
  23. * @return
  24. * An associative array whose keys are hook names and whose values are an
  25. * associative array containing:
  26. * - group: A string defining the group to which the hook belongs. The module
  27. * system will determine whether a file with the name $module.$group.inc
  28. * exists, and automatically load it when required.
  29. *
  30. * See system_hook_info() for all hook groups defined by Drupal core.
  31. *
  32. * @see hook_hook_info_alter().
  33. */
  34. function hook_hook_info() {
  35. $hooks['token_info'] = array(
  36. 'group' => 'tokens',
  37. );
  38. $hooks['tokens'] = array(
  39. 'group' => 'tokens',
  40. );
  41. return $hooks;
  42. }
  43. /**
  44. * Alter information from hook_hook_info().
  45. *
  46. * @param $hooks
  47. * Information gathered by module_hook_info() from other modules'
  48. * implementations of hook_hook_info(). Alter this array directly.
  49. * See hook_hook_info() for information on what this may contain.
  50. */
  51. function hook_hook_info_alter(&$hooks) {
  52. // Our module wants to completely override the core tokens, so make
  53. // sure the core token hooks are not found.
  54. $hooks['token_info']['group'] = 'mytokens';
  55. $hooks['tokens']['group'] = 'mytokens';
  56. }
  57. /**
  58. * Define administrative paths.
  59. *
  60. * Modules may specify whether or not the paths they define in hook_menu() are
  61. * to be considered administrative. Other modules may use this information to
  62. * display those pages differently (e.g. in a modal overlay, or in a different
  63. * theme).
  64. *
  65. * To change the administrative status of menu items defined in another module's
  66. * hook_menu(), modules should implement hook_admin_paths_alter().
  67. *
  68. * @return
  69. * An associative array. For each item, the key is the path in question, in
  70. * a format acceptable to drupal_match_path(). The value for each item should
  71. * be TRUE (for paths considered administrative) or FALSE (for non-
  72. * administrative paths).
  73. *
  74. * @see hook_menu()
  75. * @see drupal_match_path()
  76. * @see hook_admin_paths_alter()
  77. */
  78. function hook_admin_paths() {
  79. $paths = array(
  80. 'mymodule/*/add' => TRUE,
  81. 'mymodule/*/edit' => TRUE,
  82. );
  83. return $paths;
  84. }
  85. /**
  86. * Redefine administrative paths defined by other modules.
  87. *
  88. * @param $paths
  89. * An associative array of administrative paths, as defined by implementations
  90. * of hook_admin_paths().
  91. *
  92. * @see hook_admin_paths()
  93. */
  94. function hook_admin_paths_alter(&$paths) {
  95. // Treat all user pages as administrative.
  96. $paths['user'] = TRUE;
  97. $paths['user/*'] = TRUE;
  98. // Treat the forum topic node form as a non-administrative page.
  99. $paths['node/add/forum'] = FALSE;
  100. }
  101. /**
  102. * Perform periodic actions.
  103. *
  104. * Modules that require some commands to be executed periodically can
  105. * implement hook_cron(). The engine will then call the hook whenever a cron
  106. * run happens, as defined by the administrator. Typical tasks managed by
  107. * hook_cron() are database maintenance, backups, recalculation of settings
  108. * or parameters, automated mailing, and retrieving remote data.
  109. *
  110. * Short-running or non-resource-intensive tasks can be executed directly in
  111. * the hook_cron() implementation.
  112. *
  113. * Long-running tasks and tasks that could time out, such as retrieving remote
  114. * data, sending email, and intensive file tasks, should use the queue API
  115. * instead of executing the tasks directly. To do this, first define one or
  116. * more queues via hook_queue_info(). Then, add items that need to be
  117. * processed to the defined queues.
  118. */
  119. function hook_cron() {
  120. // Short-running operation example, not using a queue:
  121. // Delete all expired records since the last cron run.
  122. $expires = variable_get('mymodule_cron_last_run', REQUEST_TIME);
  123. db_delete('mymodule_table')
  124. ->condition('expires', $expires, '>=')
  125. ->execute();
  126. variable_set('mymodule_cron_last_run', REQUEST_TIME);
  127. // Long-running operation example, leveraging a queue:
  128. // Fetch feeds from other sites.
  129. $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < :time AND refresh <> :never', array(
  130. ':time' => REQUEST_TIME,
  131. ':never' => AGGREGATOR_CLEAR_NEVER,
  132. ));
  133. $queue = queue('aggregator_feeds');
  134. foreach ($result as $feed) {
  135. $queue->createItem($feed);
  136. }
  137. }
  138. /**
  139. * Declare queues holding items that need to be run periodically.
  140. *
  141. * While there can be only one hook_cron() process running at the same time,
  142. * there can be any number of processes defined here running. Because of
  143. * this, long running tasks are much better suited for this API. Items queued
  144. * in hook_cron() might be processed in the same cron run if there are not many
  145. * items in the queue, otherwise it might take several requests, which can be
  146. * run in parallel.
  147. *
  148. * You can create queues, add items to them, claim them, etc without declaring
  149. * the queue in this hook if you want, however, you need to take care of
  150. * processing the items in the queue in that case.
  151. *
  152. * @return
  153. * An associative array where the key is the queue name and the value is
  154. * again an associative array. Possible keys are:
  155. * - 'worker callback': The name of the function to call. It will be called
  156. * with one argument, the item created via
  157. * Drupal\Core\Queue\QueueInterface::createItem() in hook_cron().
  158. * - 'cron': (optional) An associative array containing the optional key:
  159. * - 'time': (optional) How much time Drupal cron should spend on calling
  160. * this worker in seconds. Defaults to 15.
  161. * If the cron key is not defined, the queue will not be processed by cron,
  162. * and must be processed by other means.
  163. *
  164. * @see hook_cron()
  165. * @see hook_queue_info_alter()
  166. */
  167. function hook_queue_info() {
  168. $queues['aggregator_feeds'] = array(
  169. 'title' => t('Aggregator refresh'),
  170. 'worker callback' => 'aggregator_refresh',
  171. // Only needed if this queue should be processed by cron.
  172. 'cron' => array(
  173. 'time' => 60,
  174. ),
  175. );
  176. return $queues;
  177. }
  178. /**
  179. * Alter cron queue information before cron runs.
  180. *
  181. * Called by drupal_cron_run() to allow modules to alter cron queue settings
  182. * before any jobs are processesed.
  183. *
  184. * @param array $queues
  185. * An array of cron queue information.
  186. *
  187. * @see hook_queue_info()
  188. * @see drupal_cron_run()
  189. */
  190. function hook_queue_info_alter(&$queues) {
  191. // This site has many feeds so let's spend 90 seconds on each cron run
  192. // updating feeds instead of the default 60.
  193. $queues['aggregator_feeds']['cron']['time'] = 90;
  194. }
  195. /**
  196. * Allows modules to declare their own Forms API element types and specify their
  197. * default values.
  198. *
  199. * This hook allows modules to declare their own form element types and to
  200. * specify their default values. The values returned by this hook will be
  201. * merged with the elements returned by hook_form() implementations and so
  202. * can return defaults for any Form APIs keys in addition to those explicitly
  203. * mentioned below.
  204. *
  205. * Each of the form element types defined by this hook is assumed to have
  206. * a matching theme function, e.g. theme_elementtype(), which should be
  207. * registered with hook_theme() as normal.
  208. *
  209. * For more information about custom element types see the explanation at
  210. * http://drupal.org/node/169815.
  211. *
  212. * @return
  213. * An associative array describing the element types being defined. The array
  214. * contains a sub-array for each element type, with the machine-readable type
  215. * name as the key. Each sub-array has a number of possible attributes:
  216. * - "#input": boolean indicating whether or not this element carries a value
  217. * (even if it's hidden).
  218. * - "#process": array of callback functions taking $element, $form_state,
  219. * and $complete_form.
  220. * - "#after_build": array of callback functions taking $element and $form_state.
  221. * - "#validate": array of callback functions taking $form and $form_state.
  222. * - "#element_validate": array of callback functions taking $element and
  223. * $form_state.
  224. * - "#pre_render": array of callback functions taking $element and $form_state.
  225. * - "#post_render": array of callback functions taking $element and $form_state.
  226. * - "#submit": array of callback functions taking $form and $form_state.
  227. * - "#title_display": optional string indicating if and how #title should be
  228. * displayed, see theme_form_element() and theme_form_element_label().
  229. *
  230. * @see hook_element_info_alter()
  231. * @see system_element_info()
  232. */
  233. function hook_element_info() {
  234. $types['filter_format'] = array(
  235. '#input' => TRUE,
  236. );
  237. return $types;
  238. }
  239. /**
  240. * Alter the element type information returned from modules.
  241. *
  242. * A module may implement this hook in order to alter the element type defaults
  243. * defined by a module.
  244. *
  245. * @param $type
  246. * All element type defaults as collected by hook_element_info().
  247. *
  248. * @see hook_element_info()
  249. */
  250. function hook_element_info_alter(&$type) {
  251. // Decrease the default size of textfields.
  252. if (isset($type['textfield']['#size'])) {
  253. $type['textfield']['#size'] = 40;
  254. }
  255. }
  256. /**
  257. * Perform cleanup tasks.
  258. *
  259. * This hook is run at the end of each page request. It is often used for
  260. * page logging and specialized cleanup. This hook MUST NOT print anything.
  261. *
  262. * Only use this hook if your code must run even for cached page views.
  263. * If you have code which must run once on all non-cached pages, use
  264. * hook_init() instead. That is the usual case. If you implement this hook
  265. * and see an error like 'Call to undefined function', it is likely that
  266. * you are depending on the presence of a module which has not been loaded yet.
  267. * It is not loaded because Drupal is still in bootstrap mode.
  268. *
  269. * @param $destination
  270. * If this hook is invoked as part of a drupal_goto() call, then this argument
  271. * will be a fully-qualified URL that is the destination of the redirect.
  272. */
  273. function hook_exit($destination = NULL) {
  274. db_update('counter')
  275. ->expression('hits', 'hits + 1')
  276. ->condition('type', 1)
  277. ->execute();
  278. }
  279. /**
  280. * Perform necessary alterations to the JavaScript before it is presented on
  281. * the page.
  282. *
  283. * @param $javascript
  284. * An array of all JavaScript being presented on the page.
  285. *
  286. * @see drupal_add_js()
  287. * @see drupal_get_js()
  288. * @see drupal_js_defaults()
  289. */
  290. function hook_js_alter(&$javascript) {
  291. // Swap out jQuery to use an updated version of the library.
  292. $javascript['core/misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
  293. }
  294. /**
  295. * Registers JavaScript/CSS libraries associated with a module.
  296. *
  297. * Modules implementing this return an array of arrays. The key to each
  298. * sub-array is the machine readable name of the library. Each library may
  299. * contain the following items:
  300. *
  301. * - 'title': The human readable name of the library.
  302. * - 'website': The URL of the library's web site.
  303. * - 'version': A string specifying the version of the library; intentionally
  304. * not a float because a version like "1.2.3" is not a valid float. Use PHP's
  305. * version_compare() to compare different versions.
  306. * - 'js': An array of JavaScript elements; each element's key is used as $data
  307. * argument, each element's value is used as $options array for
  308. * drupal_add_js(). To add library-specific (not module-specific) JavaScript
  309. * settings, the key may be skipped, the value must specify
  310. * 'type' => 'setting', and the actual settings must be contained in a 'data'
  311. * element of the value.
  312. * - 'css': Like 'js', an array of CSS elements passed to drupal_add_css().
  313. * - 'dependencies': An array of libraries that are required for a library. Each
  314. * element is an array listing the module and name of another library. Note
  315. * that all dependencies for each dependent library will also be added when
  316. * this library is added.
  317. *
  318. * Registered information for a library should contain re-usable data only.
  319. * Module- or implementation-specific data and integration logic should be added
  320. * separately.
  321. *
  322. * @return
  323. * An array defining libraries associated with a module.
  324. *
  325. * @see system_library_info()
  326. * @see drupal_add_library()
  327. * @see drupal_get_library()
  328. */
  329. function hook_library_info() {
  330. // Library One.
  331. $libraries['library-1'] = array(
  332. 'title' => 'Library One',
  333. 'website' => 'http://example.com/library-1',
  334. 'version' => '1.2',
  335. 'js' => array(
  336. drupal_get_path('module', 'my_module') . '/library-1.js' => array(),
  337. ),
  338. 'css' => array(
  339. drupal_get_path('module', 'my_module') . '/library-2.css' => array(
  340. 'type' => 'file',
  341. 'media' => 'screen',
  342. ),
  343. ),
  344. );
  345. // Library Two.
  346. $libraries['library-2'] = array(
  347. 'title' => 'Library Two',
  348. 'website' => 'http://example.com/library-2',
  349. 'version' => '3.1-beta1',
  350. 'js' => array(
  351. // JavaScript settings may use the 'data' key.
  352. array(
  353. 'type' => 'setting',
  354. 'data' => array('library2' => TRUE),
  355. ),
  356. ),
  357. 'dependencies' => array(
  358. // Require jQuery UI core by System module.
  359. array('system', 'ui'),
  360. // Require our other library.
  361. array('my_module', 'library-1'),
  362. // Require another library.
  363. array('other_module', 'library-3'),
  364. ),
  365. );
  366. return $libraries;
  367. }
  368. /**
  369. * Alters the JavaScript/CSS library registry.
  370. *
  371. * Allows certain, contributed modules to update libraries to newer versions
  372. * while ensuring backwards compatibility. In general, such manipulations should
  373. * only be done by designated modules, since most modules that integrate with a
  374. * certain library also depend on the API of a certain library version.
  375. *
  376. * @param $libraries
  377. * The JavaScript/CSS libraries provided by $module. Keyed by internal library
  378. * name and passed by reference.
  379. * @param $module
  380. * The name of the module that registered the libraries.
  381. *
  382. * @see hook_library_info()
  383. */
  384. function hook_library_info_alter(&$libraries, $module) {
  385. // Update Farbtastic to version 2.0.
  386. if ($module == 'system' && isset($libraries['farbtastic'])) {
  387. // Verify existing version is older than the one we are updating to.
  388. if (version_compare($libraries['farbtastic']['version'], '2.0', '<')) {
  389. // Update the existing Farbtastic to version 2.0.
  390. $libraries['farbtastic']['version'] = '2.0';
  391. $libraries['farbtastic']['js'] = array(
  392. drupal_get_path('module', 'farbtastic_update') . '/farbtastic-2.0.js' => array(),
  393. );
  394. }
  395. }
  396. }
  397. /**
  398. * Alter CSS files before they are output on the page.
  399. *
  400. * @param $css
  401. * An array of all CSS items (files and inline CSS) being requested on the page.
  402. *
  403. * @see drupal_add_css()
  404. * @see drupal_get_css()
  405. */
  406. function hook_css_alter(&$css) {
  407. // Remove defaults.css file.
  408. unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
  409. }
  410. /**
  411. * Alter the commands that are sent to the user through the Ajax framework.
  412. *
  413. * @param $commands
  414. * An array of all commands that will be sent to the user.
  415. *
  416. * @see ajax_render()
  417. */
  418. function hook_ajax_render_alter($commands) {
  419. // Inject any new status messages into the content area.
  420. $commands[] = ajax_command_prepend('#block-system-main .content', theme('status_messages'));
  421. }
  422. /**
  423. * Add elements to a page before it is rendered.
  424. *
  425. * Use this hook when you want to add elements at the page level. For your
  426. * additions to be printed, they have to be placed below a top level array key
  427. * of the $page array that has the name of a region of the active theme.
  428. *
  429. * By default, valid region keys are 'page_top', 'header', 'sidebar_first',
  430. * 'content', 'sidebar_second' and 'page_bottom'. To get a list of all regions
  431. * of the active theme, use system_region_list($theme). Note that $theme is a
  432. * global variable.
  433. *
  434. * If you want to alter the elements added by other modules or if your module
  435. * depends on the elements of other modules, use hook_page_alter() instead which
  436. * runs after this hook.
  437. *
  438. * @param $page
  439. * Nested array of renderable elements that make up the page.
  440. *
  441. * @see hook_page_alter()
  442. * @see drupal_render_page()
  443. */
  444. function hook_page_build(&$page) {
  445. if (menu_get_object('node', 1)) {
  446. // We are on a node detail page. Append a standard disclaimer to the
  447. // content region.
  448. $page['content']['disclaimer'] = array(
  449. '#markup' => t('Acme, Inc. is not responsible for the contents of this sample code.'),
  450. '#weight' => 25,
  451. );
  452. }
  453. }
  454. /**
  455. * Alter a menu router item right after it has been retrieved from the database or cache.
  456. *
  457. * This hook is invoked by menu_get_item() and allows for run-time alteration of router
  458. * information (page_callback, title, and so on) before it is translated and checked for
  459. * access. The passed-in $router_item is statically cached for the current request, so this
  460. * hook is only invoked once for any router item that is retrieved via menu_get_item().
  461. *
  462. * Usually, modules will only want to inspect the router item and conditionally
  463. * perform other actions (such as preparing a state for the current request).
  464. * Note that this hook is invoked for any router item that is retrieved by
  465. * menu_get_item(), which may or may not be called on the path itself, so implementations
  466. * should check the $path parameter if the alteration should fire for the current request
  467. * only.
  468. *
  469. * @param $router_item
  470. * The menu router item for $path.
  471. * @param $path
  472. * The originally passed path, for which $router_item is responsible.
  473. * @param $original_map
  474. * The path argument map, as contained in $path.
  475. *
  476. * @see menu_get_item()
  477. */
  478. function hook_menu_get_item_alter(&$router_item, $path, $original_map) {
  479. // When retrieving the router item for the current path...
  480. if ($path == current_path()) {
  481. // ...call a function that prepares something for this request.
  482. mymodule_prepare_something();
  483. }
  484. }
  485. /**
  486. * Define menu items and page callbacks.
  487. *
  488. * This hook enables modules to register paths in order to define how URL
  489. * requests are handled. Paths may be registered for URL handling only, or they
  490. * can register a link to be placed in a menu (usually the Navigation menu). A
  491. * path and its associated information is commonly called a "menu router item".
  492. * This hook is rarely called (for example, when modules are enabled), and
  493. * its results are cached in the database.
  494. *
  495. * hook_menu() implementations return an associative array whose keys define
  496. * paths and whose values are an associative array of properties for each
  497. * path. (The complete list of properties is in the return value section below.)
  498. *
  499. * The definition for each path may include a page callback function, which is
  500. * invoked when the registered path is requested. If there is no other
  501. * registered path that fits the requested path better, any further path
  502. * components are passed to the callback function. For example, your module
  503. * could register path 'abc/def':
  504. * @code
  505. * function mymodule_menu() {
  506. * $items['abc/def'] = array(
  507. * 'page callback' => 'mymodule_abc_view',
  508. * );
  509. * return $items;
  510. * }
  511. *
  512. * function mymodule_abc_view($ghi = 0, $jkl = '') {
  513. * // ...
  514. * }
  515. * @endcode
  516. * When path 'abc/def' is requested, no further path components are in the
  517. * request, and no additional arguments are passed to the callback function (so
  518. * $ghi and $jkl would take the default values as defined in the function
  519. * signature). When 'abc/def/123/foo' is requested, $ghi will be '123' and
  520. * $jkl will be 'foo'. Note that this automatic passing of optional path
  521. * arguments applies only to page and theme callback functions.
  522. *
  523. * In addition to optional path arguments, the page callback and other callback
  524. * functions may specify argument lists as arrays. These argument lists may
  525. * contain both fixed/hard-coded argument values and integers that correspond
  526. * to path components. When integers are used and the callback function is
  527. * called, the corresponding path components will be substituted for the
  528. * integers. That is, the integer 0 in an argument list will be replaced with
  529. * the first path component, integer 1 with the second, and so on (path
  530. * components are numbered starting from zero). To pass an integer without it
  531. * being replaced with its respective path component, use the string value of
  532. * the integer (e.g., '1') as the argument value. This substitution feature
  533. * allows you to re-use a callback function for several different paths. For
  534. * example:
  535. * @code
  536. * function mymodule_menu() {
  537. * $items['abc/def'] = array(
  538. * 'page callback' => 'mymodule_abc_view',
  539. * 'page arguments' => array(1, 'foo'),
  540. * );
  541. * return $items;
  542. * }
  543. * @endcode
  544. * When path 'abc/def' is requested, the page callback function will get 'def'
  545. * as the first argument and (always) 'foo' as the second argument.
  546. *
  547. * If a page callback function uses an argument list array, and its path is
  548. * requested with optional path arguments, then the list array's arguments are
  549. * passed to the callback function first, followed by the optional path
  550. * arguments. Using the above example, when path 'abc/def/bar/baz' is requested,
  551. * mymodule_abc_view() will be called with 'def', 'foo', 'bar' and 'baz' as
  552. * arguments, in that order.
  553. *
  554. * Special care should be taken for the page callback drupal_get_form(), because
  555. * your specific form callback function will always receive $form and
  556. * &$form_state as the first function arguments:
  557. * @code
  558. * function mymodule_abc_form($form, &$form_state) {
  559. * // ...
  560. * return $form;
  561. * }
  562. * @endcode
  563. * See @link form_api Form API documentation @endlink for details.
  564. *
  565. * Wildcards within paths also work with integer substitution. For example,
  566. * your module could register path 'my-module/%/edit':
  567. * @code
  568. * $items['my-module/%/edit'] = array(
  569. * 'page callback' => 'mymodule_abc_edit',
  570. * 'page arguments' => array(1),
  571. * );
  572. * @endcode
  573. * When path 'my-module/foo/edit' is requested, integer 1 will be replaced
  574. * with 'foo' and passed to the callback function. Note that wildcards may not
  575. * be used as the first component.
  576. *
  577. * Registered paths may also contain special "auto-loader" wildcard components
  578. * in the form of '%mymodule_abc', where the '%' part means that this path
  579. * component is a wildcard, and the 'mymodule_abc' part defines the prefix for a
  580. * load function, which here would be named mymodule_abc_load(). When a matching
  581. * path is requested, your load function will receive as its first argument the
  582. * path component in the position of the wildcard; load functions may also be
  583. * passed additional arguments (see "load arguments" in the return value
  584. * section below). For example, your module could register path
  585. * 'my-module/%mymodule_abc/edit':
  586. * @code
  587. * $items['my-module/%mymodule_abc/edit'] = array(
  588. * 'page callback' => 'mymodule_abc_edit',
  589. * 'page arguments' => array(1),
  590. * );
  591. * @endcode
  592. * When path 'my-module/123/edit' is requested, your load function
  593. * mymodule_abc_load() will be invoked with the argument '123', and should
  594. * load and return an "abc" object with internal id 123:
  595. * @code
  596. * function mymodule_abc_load($abc_id) {
  597. * return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  598. * }
  599. * @endcode
  600. * This 'abc' object will then be passed into the callback functions defined
  601. * for the menu item, such as the page callback function mymodule_abc_edit()
  602. * to replace the integer 1 in the argument array. Note that a load function
  603. * should return FALSE when it is unable to provide a loadable object. For
  604. * example, the node_load() function for the 'node/%node/edit' menu item will
  605. * return FALSE for the path 'node/999/edit' if a node with a node ID of 999
  606. * does not exist. The menu routing system will return a 404 error in this case.
  607. *
  608. * You can also define a %wildcard_to_arg() function (for the example menu
  609. * entry above this would be 'mymodule_abc_to_arg()'). The _to_arg() function
  610. * is invoked to retrieve a value that is used in the path in place of the
  611. * wildcard. A good example is user.module, which defines
  612. * user_uid_optional_to_arg() (corresponding to the menu entry
  613. * 'user/%user_uid_optional'). This function returns the user ID of the
  614. * current user.
  615. *
  616. * The _to_arg() function will get called with three arguments:
  617. * - $arg: A string representing whatever argument may have been supplied by
  618. * the caller (this is particularly useful if you want the _to_arg()
  619. * function only supply a (default) value if no other value is specified,
  620. * as in the case of user_uid_optional_to_arg().
  621. * - $map: An array of all path fragments (e.g. array('node','123','edit') for
  622. * 'node/123/edit').
  623. * - $index: An integer indicating which element of $map corresponds to $arg.
  624. *
  625. * _load() and _to_arg() functions may seem similar at first glance, but they
  626. * have different purposes and are called at different times. _load()
  627. * functions are called when the menu system is collecting arguments to pass
  628. * to the callback functions defined for the menu item. _to_arg() functions
  629. * are called when the menu system is generating links to related paths, such
  630. * as the tabs for a set of MENU_LOCAL_TASK items.
  631. *
  632. * You can also make groups of menu items to be rendered (by default) as tabs
  633. * on a page. To do that, first create one menu item of type MENU_NORMAL_ITEM,
  634. * with your chosen path, such as 'foo'. Then duplicate that menu item, using a
  635. * subdirectory path, such as 'foo/tab1', and changing the type to
  636. * MENU_DEFAULT_LOCAL_TASK to make it the default tab for the group. Then add
  637. * the additional tab items, with paths such as "foo/tab2" etc., with type
  638. * MENU_LOCAL_TASK. Example:
  639. * @code
  640. * // Make "Foo settings" appear on the admin Config page
  641. * $items['admin/config/system/foo'] = array(
  642. * 'title' => 'Foo settings',
  643. * 'type' => MENU_NORMAL_ITEM,
  644. * // Page callback, etc. need to be added here.
  645. * );
  646. * // Make "Tab 1" the main tab on the "Foo settings" page
  647. * $items['admin/config/system/foo/tab1'] = array(
  648. * 'title' => 'Tab 1',
  649. * 'type' => MENU_DEFAULT_LOCAL_TASK,
  650. * // Access callback, page callback, and theme callback will be inherited
  651. * // from 'admin/config/system/foo', if not specified here to override.
  652. * );
  653. * // Make an additional tab called "Tab 2" on "Foo settings"
  654. * $items['admin/config/system/foo/tab2'] = array(
  655. * 'title' => 'Tab 2',
  656. * 'type' => MENU_LOCAL_TASK,
  657. * // Page callback and theme callback will be inherited from
  658. * // 'admin/config/system/foo', if not specified here to override.
  659. * // Need to add access callback or access arguments.
  660. * );
  661. * @endcode
  662. *
  663. * @return
  664. * An array of menu items. Each menu item has a key corresponding to the
  665. * Drupal path being registered. The corresponding array value is an
  666. * associative array that may contain the following key-value pairs:
  667. * - "title": Required. The untranslated title of the menu item.
  668. * - "title callback": Function to generate the title; defaults to t().
  669. * If you require only the raw string to be output, set this to FALSE.
  670. * - "title arguments": Arguments to send to t() or your custom callback,
  671. * with path component substitution as described above.
  672. * - "description": The untranslated description of the menu item.
  673. * - "page callback": The function to call to display a web page when the user
  674. * visits the path. If omitted, the parent menu item's callback will be used
  675. * instead.
  676. * - "page arguments": An array of arguments to pass to the page callback
  677. * function, with path component substitution as described above.
  678. * - "delivery callback": The function to call to package the result of the
  679. * page callback function and send it to the browser. Defaults to
  680. * drupal_deliver_html_page() unless a value is inherited from a parent menu
  681. * item. Note that this function is called even if the access checks fail,
  682. * so any custom delivery callback function should take that into account.
  683. * See drupal_deliver_html_page() for an example.
  684. * - "access callback": A function returning TRUE if the user has access
  685. * rights to this menu item, and FALSE if not. It can also be a boolean
  686. * constant instead of a function, and you can also use numeric values
  687. * (will be cast to boolean). Defaults to user_access() unless a value is
  688. * inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items
  689. * can inherit access callbacks. To use the user_access() default callback,
  690. * you must specify the permission to check as 'access arguments' (see
  691. * below).
  692. * - "access arguments": An array of arguments to pass to the access callback
  693. * function, with path component substitution as described above. If the
  694. * access callback is inherited (see above), the access arguments will be
  695. * inherited with it, unless overridden in the child menu item.
  696. * - "theme callback": (optional) A function returning the machine-readable
  697. * name of the theme that will be used to render the page. If not provided,
  698. * the value will be inherited from a parent menu item. If there is no
  699. * theme callback, or if the function does not return the name of a current
  700. * active theme on the site, the theme for this page will be determined by
  701. * either hook_custom_theme() or the default theme instead. As a general
  702. * rule, the use of theme callback functions should be limited to pages
  703. * whose functionality is very closely tied to a particular theme, since
  704. * they can only be overridden by modules which specifically target those
  705. * pages in hook_menu_alter(). Modules implementing more generic theme
  706. * switching functionality (for example, a module which allows the theme to
  707. * be set dynamically based on the current user's role) should use
  708. * hook_custom_theme() instead.
  709. * - "theme arguments": An array of arguments to pass to the theme callback
  710. * function, with path component substitution as described above.
  711. * - "file": A file that will be included before the page callback is called;
  712. * this allows page callback functions to be in separate files. The file
  713. * should be relative to the implementing module's directory unless
  714. * otherwise specified by the "file path" option. Does not apply to other
  715. * callbacks (only page callback).
  716. * - "file path": The path to the directory containing the file specified in
  717. * "file". This defaults to the path to the module implementing the hook.
  718. * - "load arguments": An array of arguments to be passed to each of the
  719. * wildcard object loaders in the path, after the path argument itself.
  720. * For example, if a module registers path node/%node/revisions/%/view
  721. * with load arguments set to array(3), the '%node' in the path indicates
  722. * that the loader function node_load() will be called with the second
  723. * path component as the first argument. The 3 in the load arguments
  724. * indicates that the fourth path component will also be passed to
  725. * node_load() (numbering of path components starts at zero). So, if path
  726. * node/12/revisions/29/view is requested, node_load(12, 29) will be called.
  727. * There are also two "magic" values that can be used in load arguments.
  728. * "%index" indicates the index of the wildcard path component. "%map"
  729. * indicates the path components as an array. For example, if a module
  730. * registers for several paths of the form 'user/%user_category/edit/*', all
  731. * of them can use the same load function user_category_load(), by setting
  732. * the load arguments to array('%map', '%index'). For instance, if the user
  733. * is editing category 'foo' by requesting path 'user/32/edit/foo', the load
  734. * function user_category_load() will be called with 32 as its first
  735. * argument, the array ('user', 32, 'edit', 'foo') as the map argument,
  736. * and 1 as the index argument (because %user_category is the second path
  737. * component and numbering starts at zero). user_category_load() can then
  738. * use these values to extract the information that 'foo' is the category
  739. * being requested.
  740. * - "weight": An integer that determines the relative position of items in
  741. * the menu; higher-weighted items sink. Defaults to 0. Menu items with the
  742. * same weight are ordered alphabetically.
  743. * - "menu_name": Optional. Set this to a custom menu if you don't want your
  744. * item to be placed in Navigation.
  745. * - "context": (optional) Defines the context a tab may appear in. By
  746. * default, all tabs are only displayed as local tasks when being rendered
  747. * in a page context. All tabs that should be accessible as contextual links
  748. * in page region containers outside of the parent menu item's primary page
  749. * context should be registered using one of the following contexts:
  750. * - MENU_CONTEXT_PAGE: (default) The tab is displayed as local task for the
  751. * page context only.
  752. * - MENU_CONTEXT_INLINE: The tab is displayed as contextual link outside of
  753. * the primary page context only.
  754. * Contexts can be combined. For example, to display a tab both on a page
  755. * and inline, a menu router item may specify:
  756. * @code
  757. * 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  758. * @endcode
  759. * - "tab_parent": For local task menu items, the path of the task's parent
  760. * item; defaults to the same path without the last component (e.g., the
  761. * default parent for 'admin/people/create' is 'admin/people').
  762. * - "tab_root": For local task menu items, the path of the closest non-tab
  763. * item; same default as "tab_parent".
  764. * - "position": Position of the block ('left' or 'right') on the system
  765. * administration page for this item.
  766. * - "type": A bitmask of flags describing properties of the menu item.
  767. * Many shortcut bitmasks are provided as constants in menu.inc:
  768. * - MENU_NORMAL_ITEM: Normal menu items show up in the menu tree and can be
  769. * moved/hidden by the administrator.
  770. * - MENU_CALLBACK: Callbacks simply register a path so that the correct
  771. * information is generated when the path is accessed.
  772. * - MENU_SUGGESTED_ITEM: Modules may "suggest" menu items that the
  773. * administrator may enable.
  774. * - MENU_LOCAL_ACTION: Local actions are menu items that describe actions
  775. * on the parent item such as adding a new user or block, and are
  776. * rendered in the action-links list in your theme.
  777. * - MENU_LOCAL_TASK: Local tasks are menu items that describe different
  778. * displays of data, and are generally rendered as tabs.
  779. * - MENU_DEFAULT_LOCAL_TASK: Every set of local tasks should provide one
  780. * "default" task, which should display the same page as the parent item.
  781. * If the "type" element is omitted, MENU_NORMAL_ITEM is assumed.
  782. * - "options": An array of options to be passed to l() when generating a link
  783. * from this menu item. Note that the "options" parameter has no effect on
  784. * MENU_LOCAL_TASK, MENU_DEFAULT_LOCAL_TASK, and MENU_LOCAL_ACTION items.
  785. *
  786. * For a detailed usage example, see page_example.module.
  787. * For comprehensive documentation on the menu system, see
  788. * http://drupal.org/node/102338.
  789. */
  790. function hook_menu() {
  791. $items['example'] = array(
  792. 'title' => 'Example Page',
  793. 'page callback' => 'example_page',
  794. 'access arguments' => array('access content'),
  795. 'type' => MENU_SUGGESTED_ITEM,
  796. );
  797. $items['example/feed'] = array(
  798. 'title' => 'Example RSS feed',
  799. 'page callback' => 'example_feed',
  800. 'access arguments' => array('access content'),
  801. 'type' => MENU_CALLBACK,
  802. );
  803. return $items;
  804. }
  805. /**
  806. * Alter the data being saved to the {menu_router} table after hook_menu is invoked.
  807. *
  808. * This hook is invoked by menu_router_build(). The menu definitions are passed
  809. * in by reference. Each element of the $items array is one item returned
  810. * by a module from hook_menu. Additional items may be added, or existing items
  811. * altered.
  812. *
  813. * @param $items
  814. * Associative array of menu router definitions returned from hook_menu().
  815. */
  816. function hook_menu_alter(&$items) {
  817. // Example - disable the page at node/add
  818. $items['node/add']['access callback'] = FALSE;
  819. }
  820. /**
  821. * Alter the data being saved to the {menu_links} table by menu_link_save().
  822. *
  823. * @param $item
  824. * Associative array defining a menu link as passed into menu_link_save().
  825. *
  826. * @see hook_translated_menu_link_alter()
  827. */
  828. function hook_menu_link_alter(&$item) {
  829. // Make all new admin links hidden (a.k.a disabled).
  830. if (strpos($item['link_path'], 'admin') === 0 && empty($item['mlid'])) {
  831. $item['hidden'] = 1;
  832. }
  833. // Flag a link to be altered by hook_translated_menu_link_alter().
  834. if ($item['link_path'] == 'devel/cache/clear') {
  835. $item['options']['alter'] = TRUE;
  836. }
  837. // Flag a link to be altered by hook_translated_menu_link_alter(), but only
  838. // if it is derived from a menu router item; i.e., do not alter a custom
  839. // menu link pointing to the same path that has been created by a user.
  840. if ($item['link_path'] == 'user' && $item['module'] == 'system') {
  841. $item['options']['alter'] = TRUE;
  842. }
  843. }
  844. /**
  845. * Alter a menu link after it has been translated and before it is rendered.
  846. *
  847. * This hook is invoked from _menu_link_translate() after a menu link has been
  848. * translated; i.e., after dynamic path argument placeholders (%) have been
  849. * replaced with actual values, the user access to the link's target page has
  850. * been checked, and the link has been localized. It is only invoked if
  851. * $item['options']['alter'] has been set to a non-empty value (e.g., TRUE).
  852. * This flag should be set using hook_menu_link_alter().
  853. *
  854. * Implementations of this hook are able to alter any property of the menu link.
  855. * For example, this hook may be used to add a page-specific query string to all
  856. * menu links, or hide a certain link by setting:
  857. * @code
  858. * 'hidden' => 1,
  859. * @endcode
  860. *
  861. * @param $item
  862. * Associative array defining a menu link after _menu_link_translate()
  863. * @param $map
  864. * Associative array containing the menu $map (path parts and/or objects).
  865. *
  866. * @see hook_menu_link_alter()
  867. */
  868. function hook_translated_menu_link_alter(&$item, $map) {
  869. if ($item['href'] == 'devel/cache/clear') {
  870. $item['localized_options']['query'] = drupal_get_destination();
  871. }
  872. }
  873. /**
  874. * Inform modules that a menu link has been created.
  875. *
  876. * This hook is used to notify modules that menu items have been
  877. * created. Contributed modules may use the information to perform
  878. * actions based on the information entered into the menu system.
  879. *
  880. * @param $link
  881. * Associative array defining a menu link as passed into menu_link_save().
  882. *
  883. * @see hook_menu_link_update()
  884. * @see hook_menu_link_delete()
  885. */
  886. function hook_menu_link_insert($link) {
  887. // In our sample case, we track menu items as editing sections
  888. // of the site. These are stored in our table as 'disabled' items.
  889. $record['mlid'] = $link['mlid'];
  890. $record['menu_name'] = $link['menu_name'];
  891. $record['status'] = 0;
  892. drupal_write_record('menu_example', $record);
  893. }
  894. /**
  895. * Inform modules that a menu link has been updated.
  896. *
  897. * This hook is used to notify modules that menu items have been
  898. * updated. Contributed modules may use the information to perform
  899. * actions based on the information entered into the menu system.
  900. *
  901. * @param $link
  902. * Associative array defining a menu link as passed into menu_link_save().
  903. *
  904. * @see hook_menu_link_insert()
  905. * @see hook_menu_link_delete()
  906. */
  907. function hook_menu_link_update($link) {
  908. // If the parent menu has changed, update our record.
  909. $menu_name = db_query("SELECT menu_name FROM {menu_example} WHERE mlid = :mlid", array(':mlid' => $link['mlid']))->fetchField();
  910. if ($menu_name != $link['menu_name']) {
  911. db_update('menu_example')
  912. ->fields(array('menu_name' => $link['menu_name']))
  913. ->condition('mlid', $link['mlid'])
  914. ->execute();
  915. }
  916. }
  917. /**
  918. * Inform modules that a menu link has been deleted.
  919. *
  920. * This hook is used to notify modules that menu items have been
  921. * deleted. Contributed modules may use the information to perform
  922. * actions based on the information entered into the menu system.
  923. *
  924. * @param $link
  925. * Associative array defining a menu link as passed into menu_link_save().
  926. *
  927. * @see hook_menu_link_insert()
  928. * @see hook_menu_link_update()
  929. */
  930. function hook_menu_link_delete($link) {
  931. // Delete the record from our table.
  932. db_delete('menu_example')
  933. ->condition('mlid', $link['mlid'])
  934. ->execute();
  935. }
  936. /**
  937. * Alter tabs and actions displayed on the page before they are rendered.
  938. *
  939. * This hook is invoked by menu_local_tasks(). The system-determined tabs and
  940. * actions are passed in by reference. Additional tabs or actions may be added,
  941. * or existing items altered.
  942. *
  943. * Each tab or action is an associative array containing:
  944. * - #theme: The theme function to use to render.
  945. * - #link: An associative array containing:
  946. * - title: The localized title of the link.
  947. * - href: The system path to link to.
  948. * - localized_options: An array of options to pass to url().
  949. * - #active: Whether the link should be marked as 'active'.
  950. *
  951. * @param $data
  952. * An associative array containing:
  953. * - actions: An associative array containing:
  954. * - count: The amount of actions determined by the menu system, which can
  955. * be ignored.
  956. * - output: A list of of actions, each one being an associative array
  957. * as described above.
  958. * - tabs: An indexed array (list) of tab levels (up to 2 levels), each
  959. * containing an associative array:
  960. * - count: The amount of tabs determined by the menu system. This value
  961. * does not need to be altered if there is more than one tab.
  962. * - output: A list of of tabs, each one being an associative array as
  963. * described above.
  964. * @param $router_item
  965. * The menu system router item of the page.
  966. * @param $root_path
  967. * The path to the root item for this set of tabs.
  968. */
  969. function hook_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  970. // Add an action linking to node/add to all pages.
  971. $data['actions']['output'][] = array(
  972. '#theme' => 'menu_local_task',
  973. '#link' => array(
  974. 'title' => t('Add new content'),
  975. 'href' => 'node/add',
  976. 'localized_options' => array(
  977. 'attributes' => array(
  978. 'title' => t('Add new content'),
  979. ),
  980. ),
  981. ),
  982. );
  983. // Add a tab linking to node/add to all pages.
  984. $data['tabs'][0]['output'][] = array(
  985. '#theme' => 'menu_local_task',
  986. '#link' => array(
  987. 'title' => t('Example tab'),
  988. 'href' => 'node/add',
  989. 'localized_options' => array(
  990. 'attributes' => array(
  991. 'title' => t('Add new content'),
  992. ),
  993. ),
  994. ),
  995. // Define whether this link is active. This can be omitted for
  996. // implementations that add links to pages outside of the current page
  997. // context.
  998. '#active' => ($router_item['path'] == $root_path),
  999. );
  1000. }
  1001. /**
  1002. * Alter links in the active trail before it is rendered as the breadcrumb.
  1003. *
  1004. * This hook is invoked by menu_get_active_breadcrumb() and allows alteration
  1005. * of the breadcrumb links for the current page, which may be preferred instead
  1006. * of setting a custom breadcrumb via drupal_set_breadcrumb().
  1007. *
  1008. * Implementations should take into account that menu_get_active_breadcrumb()
  1009. * subsequently performs the following adjustments to the active trail *after*
  1010. * this hook has been invoked:
  1011. * - The last link in $active_trail is removed, if its 'href' is identical to
  1012. * the 'href' of $item. This happens, because the breadcrumb normally does
  1013. * not contain a link to the current page.
  1014. * - The (second to) last link in $active_trail is removed, if the current $item
  1015. * is a MENU_DEFAULT_LOCAL_TASK. This happens in order to do not show a link
  1016. * to the current page, when being on the path for the default local task;
  1017. * e.g. when being on the path node/%/view, the breadcrumb should not contain
  1018. * a link to node/%.
  1019. *
  1020. * Each link in the active trail must contain:
  1021. * - title: The localized title of the link.
  1022. * - href: The system path to link to.
  1023. * - localized_options: An array of options to pass to url().
  1024. *
  1025. * @param $active_trail
  1026. * An array containing breadcrumb links for the current page.
  1027. * @param $item
  1028. * The menu router item of the current page.
  1029. *
  1030. * @see drupal_set_breadcrumb()
  1031. * @see menu_get_active_breadcrumb()
  1032. * @see menu_get_active_trail()
  1033. * @see menu_set_active_trail()
  1034. */
  1035. function hook_menu_breadcrumb_alter(&$active_trail, $item) {
  1036. // Always display a link to the current page by duplicating the last link in
  1037. // the active trail. This means that menu_get_active_breadcrumb() will remove
  1038. // the last link (for the current page), but since it is added once more here,
  1039. // it will appear.
  1040. if (!drupal_is_front_page()) {
  1041. $end = end($active_trail);
  1042. if ($item['href'] == $end['href']) {
  1043. $active_trail[] = $end;
  1044. }
  1045. }
  1046. }
  1047. /**
  1048. * Alter contextual links before they are rendered.
  1049. *
  1050. * This hook is invoked by menu_contextual_links(). The system-determined
  1051. * contextual links are passed in by reference. Additional links may be added
  1052. * or existing links can be altered.
  1053. *
  1054. * Each contextual link must at least contain:
  1055. * - title: The localized title of the link.
  1056. * - href: The system path to link to.
  1057. * - localized_options: An array of options to pass to url().
  1058. *
  1059. * @param $links
  1060. * An associative array containing contextual links for the given $root_path,
  1061. * as described above. The array keys are used to build CSS class names for
  1062. * contextual links and must therefore be unique for each set of contextual
  1063. * links.
  1064. * @param $router_item
  1065. * The menu router item belonging to the $root_path being requested.
  1066. * @param $root_path
  1067. * The (parent) path that has been requested to build contextual links for.
  1068. * This is a normalized path, which means that an originally passed path of
  1069. * 'node/123' became 'node/%'.
  1070. *
  1071. * @see hook_contextual_links_view_alter()
  1072. * @see menu_contextual_links()
  1073. * @see hook_menu()
  1074. * @see contextual_preprocess()
  1075. */
  1076. function hook_menu_contextual_links_alter(&$links, $router_item, $root_path) {
  1077. // Add a link to all contextual links for nodes.
  1078. if ($root_path == 'node/%') {
  1079. $links['foo'] = array(
  1080. 'title' => t('Do fu'),
  1081. 'href' => 'foo/do',
  1082. 'localized_options' => array(
  1083. 'query' => array(
  1084. 'foo' => 'bar',
  1085. ),
  1086. ),
  1087. );
  1088. }
  1089. }
  1090. /**
  1091. * Perform alterations before a page is rendered.
  1092. *
  1093. * Use this hook when you want to remove or alter elements at the page
  1094. * level, or add elements at the page level that depend on an other module's
  1095. * elements (this hook runs after hook_page_build().
  1096. *
  1097. * If you are making changes to entities such as forms, menus, or user
  1098. * profiles, use those objects' native alter hooks instead (hook_form_alter(),
  1099. * for example).
  1100. *
  1101. * The $page array contains top level elements for each block region:
  1102. * @code
  1103. * $page['page_top']
  1104. * $page['header']
  1105. * $page['sidebar_first']
  1106. * $page['content']
  1107. * $page['sidebar_second']
  1108. * $page['page_bottom']
  1109. * @endcode
  1110. *
  1111. * The 'content' element contains the main content of the current page, and its
  1112. * structure will vary depending on what module is responsible for building the
  1113. * page. Some legacy modules may not return structured content at all: their
  1114. * pre-rendered markup will be located in $page['content']['main']['#markup'].
  1115. *
  1116. * Pages built by Drupal's core Node module use a standard structure:
  1117. *
  1118. * @code
  1119. * // Node body.
  1120. * $page['content']['system_main']['nodes'][$nid]['body']
  1121. * // Array of links attached to the node (add comments, read more).
  1122. * $page['content']['system_main']['nodes'][$nid]['links']
  1123. * // The node entity itself.
  1124. * $page['content']['system_main']['nodes'][$nid]['#node']
  1125. * // The results pager.
  1126. * $page['content']['system_main']['pager']
  1127. * @endcode
  1128. *
  1129. * Blocks may be referenced by their module/delta pair within a region:
  1130. * @code
  1131. * // The login block in the first sidebar region.
  1132. * $page['sidebar_first']['user_login']['#block'];
  1133. * @endcode
  1134. *
  1135. * @param $page
  1136. * Nested array of renderable elements that make up the page.
  1137. *
  1138. * @see hook_page_build()
  1139. * @see drupal_render_page()
  1140. */
  1141. function hook_page_alter(&$page) {
  1142. // Add help text to the user login block.
  1143. $page['sidebar_first']['user_login']['help'] = array(
  1144. '#weight' => -10,
  1145. '#markup' => t('To post comments or add new content, you first have to log in.'),
  1146. );
  1147. }
  1148. /**
  1149. * Perform alterations before a form is rendered.
  1150. *
  1151. * One popular use of this hook is to add form elements to the node form. When
  1152. * altering a node form, the node entity can be accessed at $form['#node'].
  1153. *
  1154. * In addition to hook_form_alter(), which is called for all forms, there are
  1155. * two more specific form hooks available. The first,
  1156. * hook_form_BASE_FORM_ID_alter(), allows targeting of a form/forms via a base
  1157. * form (if one exists). The second, hook_form_FORM_ID_alter(), can be used to
  1158. * target a specific form directly.
  1159. *
  1160. * The call order is as follows: all existing form alter functions are called
  1161. * for module A, then all for module B, etc., followed by all for any base
  1162. * theme(s), and finally for the theme itself. The module order is determined
  1163. * by system weight, then by module name.
  1164. *
  1165. * Within each module, form alter hooks are called in the following order:
  1166. * first, hook_form_alter(); second, hook_form_BASE_FORM_ID_alter(); third,
  1167. * hook_form_FORM_ID_alter(). So, for each module, the more general hooks are
  1168. * called first followed by the more specific.
  1169. *
  1170. * @param $form
  1171. * Nested array of form elements that comprise the form.
  1172. * @param $form_state
  1173. * A keyed array containing the current state of the form. The arguments
  1174. * that drupal_get_form() was originally called with are available in the
  1175. * array $form_state['build_info']['args'].
  1176. * @param $form_id
  1177. * String representing the name of the form itself. Typically this is the
  1178. * name of the function that generated the form.
  1179. *
  1180. * @see hook_form_BASE_FORM_ID_alter()
  1181. * @see hook_form_FORM_ID_alter()
  1182. */
  1183. function hook_form_alter(&$form, &$form_state, $form_id) {
  1184. if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
  1185. $form['workflow']['upload_' . $form['type']['#value']] = array(
  1186. '#type' => 'radios',
  1187. '#title' => t('Attachments'),
  1188. '#default_value' => variable_get('upload_' . $form['type']['#value'], 1),
  1189. '#options' => array(t('Disabled'), t('Enabled')),
  1190. );
  1191. }
  1192. }
  1193. /**
  1194. * Provide a form-specific alteration instead of the global hook_form_alter().
  1195. *
  1196. * Modules can implement hook_form_FORM_ID_alter() to modify a specific form,
  1197. * rather than implementing hook_form_alter() and checking the form ID, or
  1198. * using long switch statements to alter multiple forms.
  1199. *
  1200. * Form alter hooks are called in the following order: hook_form_alter(),
  1201. * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  1202. * hook_form_alter() for more details.
  1203. *
  1204. * @param $form
  1205. * Nested array of form elements that comprise the form.
  1206. * @param $form_state
  1207. * A keyed array containing the current state of the form. The arguments
  1208. * that drupal_get_form() was originally called with are available in the
  1209. * array $form_state['build_info']['args'].
  1210. * @param $form_id
  1211. * String representing the name of the form itself. Typically this is the
  1212. * name of the function that generated the form.
  1213. *
  1214. * @see hook_form_alter()
  1215. * @see hook_form_BASE_FORM_ID_alter()
  1216. * @see drupal_prepare_form()
  1217. */
  1218. function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  1219. // Modification for the form with the given form ID goes here. For example, if
  1220. // FORM_ID is "user_register_form" this code would run only on the user
  1221. // registration form.
  1222. // Add a checkbox to registration form about agreeing to terms of use.
  1223. $form['terms_of_use'] = array(
  1224. '#type' => 'checkbox',
  1225. '#title' => t("I agree with the website's terms and conditions."),
  1226. '#required' => TRUE,
  1227. );
  1228. }
  1229. /**
  1230. * Provide a form-specific alteration for shared ('base') forms.
  1231. *
  1232. * By default, when drupal_get_form() is called, Drupal looks for a function
  1233. * with the same name as the form ID, and uses that function to build the form.
  1234. * In contrast, base forms allow multiple form IDs to be mapped to a single base
  1235. * (also called 'factory') form function.
  1236. *
  1237. * Modules can implement hook_form_BASE_FORM_ID_alter() to modify a specific
  1238. * base form, rather than implementing hook_form_alter() and checking for
  1239. * conditions that would identify the shared form constructor.
  1240. *
  1241. * To identify the base form ID for a particular form (or to determine whether
  1242. * one exists) check the $form_state. The base form ID is stored under
  1243. * $form_state['build_info']['base_form_id'].
  1244. *
  1245. * See hook_forms() for more information on how to implement base forms in
  1246. * Drupal.
  1247. *
  1248. * Form alter hooks are called in the following order: hook_form_alter(),
  1249. * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  1250. * hook_form_alter() for more details.
  1251. *
  1252. * @param $form
  1253. * Nested array of form elements that comprise the form.
  1254. * @param $form_state
  1255. * A keyed array containing the current state of the form.
  1256. * @param $form_id
  1257. * String representing the name of the form itself. Typically this is the
  1258. * name of the function that generated the form.
  1259. *
  1260. * @see hook_form_alter()
  1261. * @see hook_form_FORM_ID_alter()
  1262. * @see drupal_prepare_form()
  1263. * @see hook_forms()
  1264. */
  1265. function hook_form_BASE_FORM_ID_alter(&$form, &$form_state, $form_id) {
  1266. // Modification for the form with the given BASE_FORM_ID goes here. For
  1267. // example, if BASE_FORM_ID is "node_form", this code would run on every
  1268. // node form, regardless of node type.
  1269. // Add a checkbox to the node form about agreeing to terms of use.
  1270. $form['terms_of_use'] = array(
  1271. '#type' => 'checkbox',
  1272. '#title' => t("I agree with the website's terms and conditions."),
  1273. '#required' => TRUE,
  1274. );
  1275. }
  1276. /**
  1277. * Map form_ids to form builder functions.
  1278. *
  1279. * By default, when drupal_get_form() is called, the system will look for a
  1280. * function with the same name as the form ID, and use that function to build
  1281. * the form. If no such function is found, Drupal calls this hook. Modules
  1282. * implementing this hook can then provide their own instructions for mapping
  1283. * form IDs to constructor functions. As a result, you can easily map multiple
  1284. * form IDs to a single form constructor (referred to as a 'base' form).
  1285. *
  1286. * Using a base form can help to avoid code duplication, by allowing many
  1287. * similar forms to use the same code base. Another benefit is that it becomes
  1288. * much easier for other modules to apply a general change to the group of
  1289. * forms; hook_form_BASE_FORM_ID_alter() can be used to easily alter multiple
  1290. * forms at once by directly targeting the shared base form.
  1291. *
  1292. * Two example use cases where base forms may be useful are given below.
  1293. *
  1294. * First, you can use this hook to tell the form system to use a different
  1295. * function to build certain forms in your module; this is often used to define
  1296. * a form "factory" function that is used to build several similar forms. In
  1297. * this case, your hook implementation will likely ignore all of the input
  1298. * arguments. See node_forms() for an example of this. Note, node_forms() is the
  1299. * hook_forms() implementation; the base form itself is defined in node_form().
  1300. *
  1301. * Second, you could use this hook to define how to build a form with a
  1302. * dynamically-generated form ID. In this case, you would need to verify that
  1303. * the $form_id input matched your module's format for dynamically-generated
  1304. * form IDs, and if so, act appropriately.
  1305. *
  1306. * @param $form_id
  1307. * The unique string identifying the desired form.
  1308. * @param $args
  1309. * An array containing the original arguments provided to drupal_get_form()
  1310. * or drupal_form_submit(). These are always passed to the form builder and
  1311. * do not have to be specified manually in 'callback arguments'.
  1312. *
  1313. * @return
  1314. * An associative array whose keys define form_ids and whose values are an
  1315. * associative array defining the following keys:
  1316. * - callback: The name of the form builder function to invoke. This will be
  1317. * used for the base form ID, for example, to target a base form using
  1318. * hook_form_BASE_FORM_ID_alter().
  1319. * - callback arguments: (optional) Additional arguments to pass to the
  1320. * function defined in 'callback', which are prepended to $args.
  1321. * - wrapper_callback: (optional) The name of a form builder function to
  1322. * invoke before the form builder defined in 'callback' is invoked. This
  1323. * wrapper callback may prepopulate the $form array with form elements,
  1324. * which will then be already contained in the $form that is passed on to
  1325. * the form builder defined in 'callback'. For example, a wrapper callback
  1326. * could setup wizard-alike form buttons that are the same for a variety of
  1327. * forms that belong to the wizard, which all share the same wrapper
  1328. * callback.
  1329. */
  1330. function hook_forms($form_id, $args) {
  1331. // Simply reroute the (non-existing) $form_id 'mymodule_first_form' to
  1332. // 'mymodule_main_form'.
  1333. $forms['mymodule_first_form'] = array(
  1334. 'callback' => 'mymodule_main_form',
  1335. );
  1336. // Reroute the $form_id and prepend an additional argument that gets passed to
  1337. // the 'mymodule_main_form' form builder function.
  1338. $forms['mymodule_second_form'] = array(
  1339. 'callback' => 'mymodule_main_form',
  1340. 'callback arguments' => array('some parameter'),
  1341. );
  1342. // Reroute the $form_id, but invoke the form builder function
  1343. // 'mymodule_main_form_wrapper' first, so we can prepopulate the $form array
  1344. // that is passed to the actual form builder 'mymodule_main_form'.
  1345. $forms['mymodule_wrapped_form'] = array(
  1346. 'callback' => 'mymodule_main_form',
  1347. 'wrapper_callback' => 'mymodule_main_form_wrapper',
  1348. );
  1349. return $forms;
  1350. }
  1351. /**
  1352. * Perform setup tasks for all page requests.
  1353. *
  1354. * This hook is run at the beginning of the page request. It is typically
  1355. * used to set up global parameters that are needed later in the request.
  1356. *
  1357. * Only use this hook if your code must run even for cached page views. This
  1358. * hook is called before the theme, modules, or most include files are loaded
  1359. * into memory. It happens while Drupal is still in bootstrap mode.
  1360. *
  1361. * @see hook_init()
  1362. */
  1363. function hook_boot() {
  1364. // We need user_access() in the shutdown function. Make sure it gets loaded.
  1365. drupal_load('module', 'user');
  1366. drupal_register_shutdown_function('devel_shutdown');
  1367. }
  1368. /**
  1369. * Perform setup tasks for non-cached page requests.
  1370. *
  1371. * This hook is run at the beginning of the page request. It is typically
  1372. * used to set up global parameters that are needed later in the request.
  1373. * When this hook is called, the theme and all modules are already loaded in
  1374. * memory.
  1375. *
  1376. * This hook is not run on cached pages.
  1377. *
  1378. * To add CSS or JS that should be present on all pages, modules should not
  1379. * implement this hook, but declare these files in their .info file.
  1380. *
  1381. * @see hook_boot()
  1382. */
  1383. function hook_init() {
  1384. // Since this file should only be loaded on the front page, it cannot be
  1385. // declared in the info file.
  1386. if (drupal_is_front_page()) {
  1387. drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  1388. }
  1389. }
  1390. /**
  1391. * Define image toolkits provided by this module.
  1392. *
  1393. * The file which includes each toolkit's functions must be declared as part of
  1394. * the files array in the module .info file so that the registry will find and
  1395. * parse it.
  1396. *
  1397. * The toolkit's functions must be named image_toolkitname_operation().
  1398. * where the operation may be:
  1399. * - 'load': Required. See image_gd_load() for usage.
  1400. * - 'save': Required. See image_gd_save() for usage.
  1401. * - 'settings': Optional. See image_gd_settings() for usage.
  1402. * - 'resize': Optional. See image_gd_resize() for usage.
  1403. * - 'rotate': Optional. See image_gd_rotate() for usage.
  1404. * - 'crop': Optional. See image_gd_crop() for usage.
  1405. * - 'desaturate': Optional. See image_gd_desaturate() for usage.
  1406. *
  1407. * @return
  1408. * An array with the toolkit name as keys and sub-arrays with these keys:
  1409. * - 'title': A string with the toolkit's title.
  1410. * - 'available': A Boolean value to indicate that the toolkit is operating
  1411. * properly, e.g. all required libraries exist.
  1412. *
  1413. * @see system_image_toolkits()
  1414. */
  1415. function hook_image_toolkits() {
  1416. return array(
  1417. 'working' => array(
  1418. 'title' => t('A toolkit that works.'),
  1419. 'available' => TRUE,
  1420. ),
  1421. 'broken' => array(
  1422. 'title' => t('A toolkit that is "broken" and will not be listed.'),
  1423. 'available' => FALSE,
  1424. ),
  1425. );
  1426. }
  1427. /**
  1428. * Alter an email message created with the drupal_mail() function.
  1429. *
  1430. * hook_mail_alter() allows modification of email messages created and sent
  1431. * with drupal_mail(). Usage examples include adding and/or changing message
  1432. * text, message fields, and message headers.
  1433. *
  1434. * Email messages sent using functions other than drupal_mail() will not
  1435. * invoke hook_mail_alter(). For example, a contributed module directly
  1436. * calling the drupal_mail_system()->mail() or PHP mail() function
  1437. * will not invoke this hook. All core modules use drupal_mail() for
  1438. * messaging, it is best practice but not mandatory in contributed modules.
  1439. *
  1440. * @param $message
  1441. * An array containing the message data. Keys in this array include:
  1442. * - 'id':
  1443. * The drupal_mail() id of the message. Look at module source code or
  1444. * drupal_mail() for possible id values.
  1445. * - 'to':
  1446. * The address or addresses the message will be sent to. The
  1447. * formatting of this string must comply with RFC 2822.
  1448. * - 'from':
  1449. * The address the message will be marked as being from, which is
  1450. * either a custom address or the site-wide default email address.
  1451. * - 'subject':
  1452. * Subject of the email to be sent. This must not contain any newline
  1453. * characters, or the email may not be sent properly.
  1454. * - 'body':
  1455. * An array of strings containing the message text. The message body is
  1456. * created by concatenating the individual array strings into a single text
  1457. * string using "\n\n" as a separator.
  1458. * - 'headers':
  1459. * Associative array containing mail headers, such as From, Sender,
  1460. * MIME-Version, Content-Type, etc.
  1461. * - 'params':
  1462. * An array of optional parameters supplied by the caller of drupal_mail()
  1463. * that is used to build the message before hook_mail_alter() is invoked.
  1464. * - 'language':
  1465. * The language object used to build the message before hook_mail_alter()
  1466. * is invoked.
  1467. * - 'send':
  1468. * Set to FALSE to abort sending this email message.
  1469. *
  1470. * @see drupal_mail()
  1471. */
  1472. function hook_mail_alter(&$message) {
  1473. if ($message['id'] == 'modulename_messagekey') {
  1474. if (!example_notifications_optin($message['to'], $message['id'])) {
  1475. // If the recipient has opted to not receive such messages, cancel
  1476. // sending.
  1477. $message['send'] = FALSE;
  1478. return;
  1479. }
  1480. $message['body'][] = "--\nMail sent out from " . variable_get('site_name', t('Drupal'));
  1481. }
  1482. }
  1483. /**
  1484. * Alter the registry of modules implementing a hook.
  1485. *
  1486. * This hook is invoked during module_implements(). A module may implement this
  1487. * hook in order to reorder the implementing modules, which are otherwise
  1488. * ordered by the module's system weight.
  1489. *
  1490. * Note that hooks invoked using drupal_alter() can have multiple variations
  1491. * (such as hook_form_alter() and hook_form_FORM_ID_alter()). drupal_alter()
  1492. * will call all such variants defined by a single module in turn. For the
  1493. * purposes of hook_module_implements_alter(), these variants are treated as
  1494. * a single hook. Thus, to ensure that your implementation of
  1495. * hook_form_FORM_ID_alter() is called at the right time, you will have to
  1496. * have to change the order of hook_form_alter() implementation in
  1497. * hook_module_implements_alter().
  1498. *
  1499. * @param $implementations
  1500. * An array keyed by the module's name. The value of each item corresponds
  1501. * to a $group, which is usually FALSE, unless the implementation is in a
  1502. * file named $module.$group.inc.
  1503. * @param $hook
  1504. * The name of the module hook being implemented.
  1505. */
  1506. function hook_module_implements_alter(&$implementations, $hook) {
  1507. if ($hook == 'rdf_mapping') {
  1508. // Move my_module_rdf_mapping() to the end of the list. module_implements()
  1509. // iterates through $implementations with a foreach loop which PHP iterates
  1510. // in the order that the items were added, so to move an item to the end of
  1511. // the array, we remove it and then add it.
  1512. $group = $implementations['my_module'];
  1513. unset($implementations['my_module']);
  1514. $implementations['my_module'] = $group;
  1515. }
  1516. }
  1517. /**
  1518. * Return additional themes provided by modules.
  1519. *
  1520. * Only use this hook for testing purposes. Use a hidden MYMODULE_test.module
  1521. * to implement this hook. Testing themes should be hidden, too.
  1522. *
  1523. * This hook is invoked from _system_rebuild_theme_data() and allows modules to
  1524. * register additional themes outside of the regular 'themes' directories of a
  1525. * Drupal installation.
  1526. *
  1527. * @return
  1528. * An associative array. Each key is the system name of a theme and each value
  1529. * is the corresponding path to the theme's .info file.
  1530. */
  1531. function hook_system_theme_info() {
  1532. $themes['mymodule_test_theme'] = drupal_get_path('module', 'mymodule') . '/mymodule_test_theme/mymodule_test_theme.info';
  1533. return $themes;
  1534. }
  1535. /**
  1536. * Alter the information parsed from module and theme .info files
  1537. *
  1538. * This hook is invoked in _system_rebuild_module_data() and in
  1539. * _system_rebuild_theme_data(). A module may implement this hook in order to
  1540. * add to or alter the data generated by reading the .info file with
  1541. * drupal_parse_info_file().
  1542. *
  1543. * @param $info
  1544. * The .info file contents, passed by reference so that it can be altered.
  1545. * @param $file
  1546. * Full information about the module or theme, including $file->name, and
  1547. * $file->filename
  1548. * @param $type
  1549. * Either 'module' or 'theme', depending on the type of .info file that was
  1550. * passed.
  1551. */
  1552. function hook_system_info_alter(&$info, $file, $type) {
  1553. // Only fill this in if the .info file does not define a 'datestamp'.
  1554. if (empty($info['datestamp'])) {
  1555. $info['datestamp'] = filemtime($file->filename);
  1556. }
  1557. }
  1558. /**
  1559. * Define user permissions.
  1560. *
  1561. * This hook can supply permissions that the module defines, so that they
  1562. * can be selected on the user permissions page and used to grant or restrict
  1563. * access to actions the module performs.
  1564. *
  1565. * Permissions are checked using user_access().
  1566. *
  1567. * For a detailed usage example, see page_example.module.
  1568. *
  1569. * @return
  1570. * An array whose keys are permission names and whose corresponding values
  1571. * are arrays containing the following key-value pairs:
  1572. * - title: The human-readable name of the permission, to be shown on the
  1573. * permission administration page. This should be wrapped in the t()
  1574. * function so it can be translated.
  1575. * - description: (optional) A description of what the permission does. This
  1576. * should be wrapped in the t() function so it can be translated.
  1577. * - restrict access: (optional) A boolean which can be set to TRUE to
  1578. * indicate that site administrators should restrict access to this
  1579. * permission to trusted users. This should be used for permissions that
  1580. * have inherent security risks across a variety of potential use cases
  1581. * (for example, the "administer filters" and "bypass node access"
  1582. * permissions provided by Drupal core). When set to TRUE, a standard
  1583. * warning message defined in user_admin_permissions() and output via
  1584. * theme_user_permission_description() will be associated with the
  1585. * permission and displayed with it on the permission administration page.
  1586. * Defaults to FALSE.
  1587. * - warning: (optional) A translated warning message to display for this
  1588. * permission on the permission administration page. This warning overrides
  1589. * the automatic warning generated by 'restrict access' being set to TRUE.
  1590. * This should rarely be used, since it is important for all permissions to
  1591. * have a clear, consistent security warning that is the same across the
  1592. * site. Use the 'description' key instead to provide any information that
  1593. * is specific to the permission you are defining.
  1594. *
  1595. * @see theme_user_permission_description()
  1596. */
  1597. function hook_permission() {
  1598. return array(
  1599. 'administer my module' => array(
  1600. 'title' => t('Administer my module'),
  1601. 'description' => t('Perform administration tasks for my module.'),
  1602. ),
  1603. );
  1604. }
  1605. /**
  1606. * Register a module (or theme's) theme implementations.
  1607. *
  1608. * The implementations declared by this hook have two purposes: either they
  1609. * specify how a particular render array is to be rendered as HTML (this is
  1610. * usually the case if the theme function is assigned to the render array's
  1611. * #theme property), or they return the HTML that should be returned by an
  1612. * invocation of theme().
  1613. *
  1614. * The following parameters are all optional.
  1615. *
  1616. * @param array $existing
  1617. * An array of existing implementations that may be used for override
  1618. * purposes. This is primarily useful for themes that may wish to examine
  1619. * existing implementations to extract data (such as arguments) so that
  1620. * it may properly register its own, higher priority implementations.
  1621. * @param $type
  1622. * Whether a theme, module, etc. is being processed. This is primarily useful
  1623. * so that themes tell if they are the actual theme being called or a parent
  1624. * theme. May be one of:
  1625. * - 'module': A module is being checked for theme implementations.
  1626. * - 'base_theme_engine': A theme engine is being checked for a theme that is
  1627. * a parent of the actual theme being used.
  1628. * - 'theme_engine': A theme engine is being checked for the actual theme
  1629. * being used.
  1630. * - 'base_theme': A base theme is being checked for theme implementations.
  1631. * - 'theme': The actual theme in use is being checked.
  1632. * @param $theme
  1633. * The actual name of theme, module, etc. that is being being processed.
  1634. * @param $path
  1635. * The directory path of the theme or module, so that it doesn't need to be
  1636. * looked up.
  1637. *
  1638. * @return array
  1639. * An associative array of theme hook information. The keys on the outer
  1640. * array are the internal names of the hooks, and the values are arrays
  1641. * containing information about the hook. Each information array must contain
  1642. * either a 'variables' element or a 'render element' element, but not both.
  1643. * Use 'render element' if you are theming a single element or element tree
  1644. * composed of elements, such as a form array, a page array, or a single
  1645. * checkbox element. Use 'variables' if your theme implementation is
  1646. * intended to be called directly through theme() and has multiple arguments
  1647. * for the data and style; in this case, the variables not supplied by the
  1648. * calling function will be given default values and passed to the template
  1649. * or theme function. The returned theme information array can contain the
  1650. * following key/value pairs:
  1651. * - variables: (see above) Each array key is the name of the variable, and
  1652. * the value given is used as the default value if the function calling
  1653. * theme() does not supply it. Template implementations receive each array
  1654. * key as a variable in the template file (so they must be legal PHP
  1655. * variable names). Function implementations are passed the variables in a
  1656. * single $variables function argument.
  1657. * - render element: (see above) The name of the renderable element or element
  1658. * tree to pass to the theme function. This name is used as the name of the
  1659. * variable that holds the renderable element or tree in preprocess and
  1660. * process functions.
  1661. * - file: The file the implementation resides in. This file will be included
  1662. * prior to the theme being rendered, to make sure that the function or
  1663. * preprocess function (as needed) is actually loaded; this makes it
  1664. * possible to split theme functions out into separate files quite easily.
  1665. * - path: Override the path of the file to be used. Ordinarily the module or
  1666. * theme path will be used, but if the file will not be in the default
  1667. * path, include it here. This path should be relative to the Drupal root
  1668. * directory.
  1669. * - template: If specified, this theme implementation is a template, and
  1670. * this is the template file without an extension. Do not put .tpl.php on
  1671. * this file; that extension will be added automatically by the default
  1672. * rendering engine (which is PHPTemplate). If 'path', above, is specified,
  1673. * the template should also be in this path.
  1674. * - function: If specified, this will be the function name to invoke for
  1675. * this implementation. If neither 'template' nor 'function' is specified,
  1676. * a default function name will be assumed. For example, if a module
  1677. * registers the 'node' theme hook, 'theme_node' will be assigned to its
  1678. * function. If the chameleon theme registers the node hook, it will be
  1679. * assigned 'chameleon_node' as its function.
  1680. * - pattern: A regular expression pattern to be used to allow this theme
  1681. * implementation to have a dynamic name. The convention is to use __ to
  1682. * differentiate the dynamic portion of the theme. For example, to allow
  1683. * forums to be themed individually, the pattern might be: 'forum__'. Then,
  1684. * when the forum is themed, call:
  1685. * @code
  1686. * theme(array('forum__' . $tid, 'forum'), $forum)
  1687. * @endcode
  1688. * - preprocess functions: A list of functions used to preprocess this data.
  1689. * Ordinarily this won't be used; it's automatically filled in. By default,
  1690. * for a module this will be filled in as template_preprocess_HOOK. For
  1691. * a theme this will be filled in as phptemplate_preprocess and
  1692. * phptemplate_preprocess_HOOK as well as themename_preprocess and
  1693. * themename_preprocess_HOOK.
  1694. * - override preprocess functions: Set to TRUE when a theme does NOT want
  1695. * the standard preprocess functions to run. This can be used to give a
  1696. * theme FULL control over how variables are set. For example, if a theme
  1697. * wants total control over how certain variables in the page.tpl.php are
  1698. * set, this can be set to true. Please keep in mind that when this is used
  1699. * by a theme, that theme becomes responsible for making sure necessary
  1700. * variables are set.
  1701. * - type: (automatically derived) Where the theme hook is defined:
  1702. * 'module', 'theme_engine', or 'theme'.
  1703. * - theme path: (automatically derived) The directory path of the theme or
  1704. * module, so that it doesn't need to be looked up.
  1705. */
  1706. function hook_theme($existing, $type, $theme, $path) {
  1707. return array(
  1708. 'forum_display' => array(
  1709. 'variables' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
  1710. ),
  1711. 'forum_list' => array(
  1712. 'variables' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
  1713. ),
  1714. 'forum_topic_list' => array(
  1715. 'variables' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
  1716. ),
  1717. 'forum_icon' => array(
  1718. 'variables' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0),
  1719. ),
  1720. 'status_report' => array(
  1721. 'render element' => 'requirements',
  1722. 'file' => 'system.admin.inc',
  1723. ),
  1724. 'system_date_time_settings' => array(
  1725. 'render element' => 'form',
  1726. 'file' => 'system.admin.inc',
  1727. ),
  1728. );
  1729. }
  1730. /**
  1731. * Alter the theme registry information returned from hook_theme().
  1732. *
  1733. * The theme registry stores information about all available theme hooks,
  1734. * including which callback functions those hooks will call when triggered,
  1735. * what template files are exposed by these hooks, and so on.
  1736. *
  1737. * Note that this hook is only executed as the theme cache is re-built.
  1738. * Changes here will not be visible until the next cache clear.
  1739. *
  1740. * The $theme_registry array is keyed by theme hook name, and contains the
  1741. * information returned from hook_theme(), as well as additional properties
  1742. * added by _theme_process_registry().
  1743. *
  1744. * For example:
  1745. * @code
  1746. * $theme_registry['user_profile'] = array(
  1747. * 'variables' => array(
  1748. * 'account' => NULL,
  1749. * ),
  1750. * 'template' => 'core/modules/user/user-profile',
  1751. * 'file' => 'core/modules/user/user.pages.inc',
  1752. * 'type' => 'module',
  1753. * 'theme path' => 'core/modules/user',
  1754. * 'preprocess functions' => array(
  1755. * 0 => 'template_preprocess',
  1756. * 1 => 'template_preprocess_user_profile',
  1757. * ),
  1758. * );
  1759. * @endcode
  1760. *
  1761. * @param $theme_registry
  1762. * The entire cache of theme registry information, post-processing.
  1763. *
  1764. * @see hook_theme()
  1765. * @see _theme_process_registry()
  1766. */
  1767. function hook_theme_registry_alter(&$theme_registry) {
  1768. // Kill the next/previous forum topic navigation links.
  1769. foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
  1770. if ($value == 'template_preprocess_forum_topic_navigation') {
  1771. unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
  1772. }
  1773. }
  1774. }
  1775. /**
  1776. * Return the machine-readable name of the theme to use for the current page.
  1777. *
  1778. * This hook can be used to dynamically set the theme for the current page
  1779. * request. It should be used by modules which need to override the theme
  1780. * based on dynamic conditions (for example, a module which allows the theme to
  1781. * be set based on the current user's role). The return value of this hook will
  1782. * be used on all pages except those which have a valid per-page or per-section
  1783. * theme set via a theme callback function in hook_menu(); the themes on those
  1784. * pages can only be overridden using hook_menu_alter().
  1785. *
  1786. * Note that returning different themes for the same path may not work with page
  1787. * caching. This is most likely to be a problem if an anonymous user on a given
  1788. * path could have different themes returned under different conditions.
  1789. *
  1790. * Since only one theme can be used at a time, the last (i.e., highest
  1791. * weighted) module which returns a valid theme name from this hook will
  1792. * prevail.
  1793. *
  1794. * @return
  1795. * The machine-readable name of the theme that should be used for the current
  1796. * page request. The value returned from this function will only have an
  1797. * effect if it corresponds to a currently-active theme on the site.
  1798. */
  1799. function hook_custom_theme() {
  1800. // Allow the user to request a particular theme via a query parameter.
  1801. if (isset($_GET['theme'])) {
  1802. return $_GET['theme'];
  1803. }
  1804. }
  1805. /**
  1806. * Register XML-RPC callbacks.
  1807. *
  1808. * This hook lets a module register callback functions to be called when
  1809. * particular XML-RPC methods are invoked by a client.
  1810. *
  1811. * @return
  1812. * An array which maps XML-RPC methods to Drupal functions. Each array
  1813. * element is either a pair of method => function or an array with four
  1814. * entries:
  1815. * - The XML-RPC method name (for example, module.function).
  1816. * - The Drupal callback function (for example, module_function).
  1817. * - The method signature is an array of XML-RPC types. The first element
  1818. * of this array is the type of return value and then you should write a
  1819. * list of the types of the parameters. XML-RPC types are the following
  1820. * (See the types at http://www.xmlrpc.com/spec):
  1821. * - "boolean": 0 (false) or 1 (true).
  1822. * - "double": a floating point number (for example, -12.214).
  1823. * - "int": a integer number (for example, -12).
  1824. * - "array": an array without keys (for example, array(1, 2, 3)).
  1825. * - "struct": an associative array or an object (for example,
  1826. * array('one' => 1, 'two' => 2)).
  1827. * - "date": when you return a date, then you may either return a
  1828. * timestamp (time(), mktime() etc.) or an ISO8601 timestamp. When
  1829. * date is specified as an input parameter, then you get an object,
  1830. * which is described in the function xmlrpc_date
  1831. * - "base64": a string containing binary data, automatically
  1832. * encoded/decoded automatically.
  1833. * - "string": anything else, typically a string.
  1834. * - A descriptive help string, enclosed in a t() function for translation
  1835. * purposes.
  1836. * Both forms are shown in the example.
  1837. */
  1838. function hook_xmlrpc() {
  1839. return array(
  1840. 'drupal.login' => 'drupal_login',
  1841. array(
  1842. 'drupal.site.ping',
  1843. 'drupal_directory_ping',
  1844. array('boolean', 'string', 'string', 'string', 'string', 'string'),
  1845. t('Handling ping request'))
  1846. );
  1847. }
  1848. /**
  1849. * Alters the definition of XML-RPC methods before they are called.
  1850. *
  1851. * This hook allows modules to modify the callback definition of declared
  1852. * XML-RPC methods, right before they are invoked by a client. Methods may be
  1853. * added, or existing methods may be altered.
  1854. *
  1855. * Note that hook_xmlrpc() supports two distinct and incompatible formats to
  1856. * define a callback, so care must be taken when altering other methods.
  1857. *
  1858. * @param $methods
  1859. * An asssociative array of method callback definitions, as returned from
  1860. * hook_xmlrpc() implementations.
  1861. *
  1862. * @see hook_xmlrpc()
  1863. * @see xmlrpc_server()
  1864. */
  1865. function hook_xmlrpc_alter(&$methods) {
  1866. // Directly change a simple method.
  1867. $methods['drupal.login'] = 'mymodule_login';
  1868. // Alter complex definitions.
  1869. foreach ($methods as $key => &$method) {
  1870. // Skip simple method definitions.
  1871. if (!is_int($key)) {
  1872. continue;
  1873. }
  1874. // Perform the wanted manipulation.
  1875. if ($method[0] == 'drupal.site.ping') {
  1876. $method[1] = 'mymodule_directory_ping';
  1877. }
  1878. }
  1879. }
  1880. /**
  1881. * Log an event message.
  1882. *
  1883. * This hook allows modules to route log events to custom destinations, such as
  1884. * SMS, Email, pager, syslog, ...etc.
  1885. *
  1886. * @param array $log_entry
  1887. * An associative array containing the following keys:
  1888. * - type: The type of message for this entry.
  1889. * - user: The user object for the user who was logged in when the event
  1890. * happened.
  1891. * - request_uri: The request URI for the page the event happened in.
  1892. * - referer: The page that referred the user to the page where the event
  1893. * occurred.
  1894. * - ip: The IP address where the request for the page came from.
  1895. * - timestamp: The UNIX timestamp of the date/time the event occurred.
  1896. * - severity: The severity of the message; one of the following values as
  1897. * defined in @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
  1898. * - WATCHDOG_EMERGENCY: Emergency, system is unusable.
  1899. * - WATCHDOG_ALERT: Alert, action must be taken immediately.
  1900. * - WATCHDOG_CRITICAL: Critical conditions.
  1901. * - WATCHDOG_ERROR: Error conditions.
  1902. * - WATCHDOG_WARNING: Warning conditions.
  1903. * - WATCHDOG_NOTICE: Normal but significant conditions.
  1904. * - WATCHDOG_INFO: Informational messages.
  1905. * - WATCHDOG_DEBUG: Debug-level messages.
  1906. * - link: An optional link provided by the module that called the watchdog()
  1907. * function.
  1908. * - message: The text of the message to be logged. Variables in the message
  1909. * are indicated by using placeholder strings alongside the variables
  1910. * argument to declare the value of the placeholders. See t() for
  1911. * documentation on how the message and variable parameters interact.
  1912. * - variables: An array of variables to be inserted into the message on
  1913. * display. Will be NULL or missing if a message is already translated or if
  1914. * the message is not possible to translate.
  1915. */
  1916. function hook_watchdog(array $log_entry) {
  1917. global $base_url, $language_interface;
  1918. $severity_list = array(
  1919. WATCHDOG_EMERGENCY => t('Emergency'),
  1920. WATCHDOG_ALERT => t('Alert'),
  1921. WATCHDOG_CRITICAL => t('Critical'),
  1922. WATCHDOG_ERROR => t('Error'),
  1923. WATCHDOG_WARNING => t('Warning'),
  1924. WATCHDOG_NOTICE => t('Notice'),
  1925. WATCHDOG_INFO => t('Info'),
  1926. WATCHDOG_DEBUG => t('Debug'),
  1927. );
  1928. $to = 'someone@example.com';
  1929. $params = array();
  1930. $params['subject'] = t('[@site_name] @severity_desc: Alert from your web site', array(
  1931. '@site_name' => variable_get('site_name', 'Drupal'),
  1932. '@severity_desc' => $severity_list[$log_entry['severity']],
  1933. ));
  1934. $params['message'] = "\nSite: @base_url";
  1935. $params['message'] .= "\nSeverity: (@severity) @severity_desc";
  1936. $params['message'] .= "\nTimestamp: @timestamp";
  1937. $params['message'] .= "\nType: @type";
  1938. $params['message'] .= "\nIP Address: @ip";
  1939. $params['message'] .= "\nRequest URI: @request_uri";
  1940. $params['message'] .= "\nReferrer URI: @referer_uri";
  1941. $params['message'] .= "\nUser: (@uid) @name";
  1942. $params['message'] .= "\nLink: @link";
  1943. $params['message'] .= "\nMessage: \n\n@message";
  1944. $params['message'] = t($params['message'], array(
  1945. '@base_url' => $base_url,
  1946. '@severity' => $log_entry['severity'],
  1947. '@severity_desc' => $severity_list[$log_entry['severity']],
  1948. '@timestamp' => format_date($log_entry['timestamp']),
  1949. '@type' => $log_entry['type'],
  1950. '@ip' => $log_entry['ip'],
  1951. '@request_uri' => $log_entry['request_uri'],
  1952. '@referer_uri' => $log_entry['referer'],
  1953. '@uid' => $log_entry['user']->uid,
  1954. '@name' => $log_entry['user']->name,
  1955. '@link' => strip_tags($log_entry['link']),
  1956. '@message' => strip_tags($log_entry['message']),
  1957. ));
  1958. drupal_mail('emaillog', 'entry', $to, $language_interface, $params);
  1959. }
  1960. /**
  1961. * Prepare a message based on parameters; called from drupal_mail().
  1962. *
  1963. * Note that hook_mail(), unlike hook_mail_alter(), is only called on the
  1964. * $module argument to drupal_mail(), not all modules.
  1965. *
  1966. * @param $key
  1967. * An identifier of the mail.
  1968. * @param $message
  1969. * An array to be filled in. Elements in this array include:
  1970. * - id: An ID to identify the mail sent. Look at module source code
  1971. * or drupal_mail() for possible id values.
  1972. * - to: The address or addresses the message will be sent to. The
  1973. * formatting of this string must comply with RFC 2822.
  1974. * - subject: Subject of the e-mail to be sent. This must not contain any
  1975. * newline characters, or the mail may not be sent properly. drupal_mail()
  1976. * sets this to an empty string when the hook is invoked.
  1977. * - body: An array of lines containing the message to be sent. Drupal will
  1978. * format the correct line endings for you. drupal_mail() sets this to an
  1979. * empty array when the hook is invoked.
  1980. * - from: The address the message will be marked as being from, which is
  1981. * set by drupal_mail() to either a custom address or the site-wide
  1982. * default email address when the hook is invoked.
  1983. * - headers: Associative array containing mail headers, such as From,
  1984. * Sender, MIME-Version, Content-Type, etc. drupal_mail() pre-fills
  1985. * several headers in this array.
  1986. * @param $params
  1987. * An array of parameters supplied by the caller of drupal_mail().
  1988. */
  1989. function hook_mail($key, &$message, $params) {
  1990. $account = $params['account'];
  1991. $context = $params['context'];
  1992. $variables = array(
  1993. '%site_name' => variable_get('site_name', 'Drupal'),
  1994. '%username' => user_format_name($account),
  1995. );
  1996. if ($context['hook'] == 'taxonomy') {
  1997. $entity = $params['entity'];
  1998. $vocabulary = taxonomy_vocabulary_load($entity->vid);
  1999. $variables += array(
  2000. '%term_name' => $entity->name,
  2001. '%term_description' => $entity->description,
  2002. '%term_id' => $entity->tid,
  2003. '%vocabulary_name' => $vocabulary->name,
  2004. '%vocabulary_description' => $vocabulary->description,
  2005. '%vocabulary_id' => $vocabulary->vid,
  2006. );
  2007. }
  2008. // Node-based variable translation is only available if we have a node.
  2009. if (isset($params['node'])) {
  2010. $node = $params['node'];
  2011. $variables += array(
  2012. '%uid' => $node->uid,
  2013. '%node_url' => url('node/' . $node->nid, array('absolute' => TRUE)),
  2014. '%node_type' => node_type_get_name($node),
  2015. '%title' => $node->title,
  2016. '%teaser' => $node->teaser,
  2017. '%body' => $node->body,
  2018. );
  2019. }
  2020. $subject = strtr($context['subject'], $variables);
  2021. $body = strtr($context['message'], $variables);
  2022. $message['subject'] .= str_replace(array("\r", "\n"), '', $subject);
  2023. $message['body'][] = drupal_html_to_text($body);
  2024. }
  2025. /**
  2026. * Flush all persistent and static caches.
  2027. *
  2028. * This hook asks your module to clear all of its persistent (database) and
  2029. * static caches, in order to ensure a clean environment for subsequently
  2030. * invoked data rebuilds.
  2031. *
  2032. * Do NOT use this hook for rebuilding information. Only use it to flush custom
  2033. * caches and return the names of additional cache bins to flush.
  2034. *
  2035. * Static caches using drupal_static() do not need to be reset manually.
  2036. * However, all other static variables that do not use drupal_static() must be
  2037. * manually reset.
  2038. *
  2039. * This hook is invoked by drupal_flush_all_caches(). It runs before module data
  2040. * is updated and before hook_rebuild().
  2041. *
  2042. * @return array
  2043. * An array of cache bins to be flushed.
  2044. *
  2045. * @see drupal_flush_all_caches()
  2046. * @see hook_rebuild()
  2047. */
  2048. function hook_cache_flush() {
  2049. return array('example');
  2050. }
  2051. /**
  2052. * Rebuild data based upon refreshed caches.
  2053. *
  2054. * This hook allows your module to rebuild its data based on the latest/current
  2055. * module data. It runs after hook_cache_flush() and after all module data has
  2056. * been updated.
  2057. *
  2058. * This hook is only invoked after the system has been completely cleared;
  2059. * i.e., all previously cached data is known to be gone and every API in the
  2060. * system is known to return current information, so your module can safely rely
  2061. * on all available data to rebuild its own.
  2062. *
  2063. * The menu router is the only exception regarding rebuilt data; it is only
  2064. * rebuilt after all hook_rebuild() implementations have been invoked. That
  2065. * ensures that hook_menu() implementations and the final router rebuild can
  2066. * rely on all data being returned by all modules.
  2067. *
  2068. * @see hook_cache_flush()
  2069. * @see drupal_flush_all_caches()
  2070. */
  2071. function hook_rebuild() {
  2072. // Rehash blocks for active themes. We don't use list_themes() here,
  2073. // because if MAINTENANCE_MODE is defined it skips reading the database,
  2074. // and we can't tell which themes are active.
  2075. $themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
  2076. foreach ($themes as $theme) {
  2077. _block_rehash($theme->name);
  2078. }
  2079. }
  2080. /**
  2081. * Perform necessary actions before modules are installed.
  2082. *
  2083. * This function allows all modules to react prior to a module being installed.
  2084. *
  2085. * @param $modules
  2086. * An array of modules about to be installed.
  2087. */
  2088. function hook_modules_preinstall($modules) {
  2089. mymodule_cache_clear();
  2090. }
  2091. /**
  2092. * Perform necessary actions before modules are enabled.
  2093. *
  2094. * This function allows all modules to react prior to a module being enabled.
  2095. *
  2096. * @param $module
  2097. * An array of modules about to be enabled.
  2098. */
  2099. function hook_modules_preenable($modules) {
  2100. mymodule_cache_clear();
  2101. }
  2102. /**
  2103. * Perform necessary actions after modules are installed.
  2104. *
  2105. * This function differs from hook_install() in that it gives all other modules
  2106. * a chance to perform actions when a module is installed, whereas
  2107. * hook_install() is only called on the module actually being installed. See
  2108. * module_enable() for a detailed description of the order in which install and
  2109. * enable hooks are invoked.
  2110. *
  2111. * @param $modules
  2112. * An array of the modules that were installed.
  2113. *
  2114. * @see module_enable()
  2115. * @see hook_modules_enabled()
  2116. * @see hook_install()
  2117. */
  2118. function hook_modules_installed($modules) {
  2119. if (in_array('lousy_module', $modules)) {
  2120. variable_set('lousy_module_conflicting_variable', FALSE);
  2121. }
  2122. }
  2123. /**
  2124. * Perform necessary actions after modules are enabled.
  2125. *
  2126. * This function differs from hook_enable() in that it gives all other modules a
  2127. * chance to perform actions when modules are enabled, whereas hook_enable() is
  2128. * only called on the module actually being enabled. See module_enable() for a
  2129. * detailed description of the order in which install and enable hooks are
  2130. * invoked.
  2131. *
  2132. * @param $modules
  2133. * An array of the modules that were enabled.
  2134. *
  2135. * @see hook_enable()
  2136. * @see hook_modules_installed()
  2137. * @see module_enable()
  2138. */
  2139. function hook_modules_enabled($modules) {
  2140. if (in_array('lousy_module', $modules)) {
  2141. drupal_set_message(t('mymodule is not compatible with lousy_module'), 'error');
  2142. mymodule_disable_functionality();
  2143. }
  2144. }
  2145. /**
  2146. * Perform necessary actions after modules are disabled.
  2147. *
  2148. * This function differs from hook_disable() in that it gives all other modules
  2149. * a chance to perform actions when modules are disabled, whereas hook_disable()
  2150. * is only called on the module actually being disabled.
  2151. *
  2152. * @param $modules
  2153. * An array of the modules that were disabled.
  2154. *
  2155. * @see hook_disable()
  2156. * @see hook_modules_uninstalled()
  2157. */
  2158. function hook_modules_disabled($modules) {
  2159. if (in_array('lousy_module', $modules)) {
  2160. mymodule_enable_functionality();
  2161. }
  2162. }
  2163. /**
  2164. * Perform necessary actions after modules are uninstalled.
  2165. *
  2166. * This function differs from hook_uninstall() in that it gives all other
  2167. * modules a chance to perform actions when a module is uninstalled, whereas
  2168. * hook_uninstall() is only called on the module actually being uninstalled.
  2169. *
  2170. * It is recommended that you implement this hook if your module stores
  2171. * data that may have been set by other modules.
  2172. *
  2173. * @param $modules
  2174. * An array of the modules that were uninstalled.
  2175. *
  2176. * @see hook_uninstall()
  2177. * @see hook_modules_disabled()
  2178. */
  2179. function hook_modules_uninstalled($modules) {
  2180. foreach ($modules as $module) {
  2181. db_delete('mymodule_table')
  2182. ->condition('module', $module)
  2183. ->execute();
  2184. }
  2185. mymodule_cache_rebuild();
  2186. }
  2187. /**
  2188. * Registers PHP stream wrapper implementations associated with a module.
  2189. *
  2190. * Provide a facility for managing and querying user-defined stream wrappers
  2191. * in PHP. PHP's internal stream_get_wrappers() doesn't return the class
  2192. * registered to handle a stream, which we need to be able to find the handler
  2193. * for class instantiation.
  2194. *
  2195. * If a module registers a scheme that is already registered with PHP, it will
  2196. * be unregistered and replaced with the specified class.
  2197. *
  2198. * @return
  2199. * A nested array, keyed first by scheme name ("public" for "public://"),
  2200. * then keyed by the following values:
  2201. * - 'name' A short string to name the wrapper.
  2202. * - 'class' A string specifying the PHP class that implements the
  2203. * Drupal\Core\StreamWrapper\StreamWrapperInterface interface.
  2204. * - 'description' A string with a short description of what the wrapper does.
  2205. * - 'type' (Optional) A bitmask of flags indicating what type of streams this
  2206. * wrapper will access - local or remote, readable and/or writeable, etc.
  2207. * Many shortcut constants are defined in file.inc. Defaults to
  2208. * STREAM_WRAPPERS_NORMAL which includes all of these bit flags:
  2209. * - STREAM_WRAPPERS_READ
  2210. * - STREAM_WRAPPERS_WRITE
  2211. * - STREAM_WRAPPERS_VISIBLE
  2212. *
  2213. * @see file_get_stream_wrappers()
  2214. * @see hook_stream_wrappers_alter()
  2215. * @see system_stream_wrappers()
  2216. */
  2217. function hook_stream_wrappers() {
  2218. return array(
  2219. 'public' => array(
  2220. 'name' => t('Public files'),
  2221. 'class' => 'Drupal\Core\StreamWrapper\PublicStream',
  2222. 'description' => t('Public local files served by the webserver.'),
  2223. 'type' => STREAM_WRAPPERS_LOCAL_NORMAL,
  2224. ),
  2225. 'private' => array(
  2226. 'name' => t('Private files'),
  2227. 'class' => 'Drupal\Core\StreamWrapper\PrivateStream',
  2228. 'description' => t('Private local files served by Drupal.'),
  2229. 'type' => STREAM_WRAPPERS_LOCAL_NORMAL,
  2230. ),
  2231. 'temp' => array(
  2232. 'name' => t('Temporary files'),
  2233. 'class' => 'Drupal\Core\StreamWrapper\TemporaryStream',
  2234. 'description' => t('Temporary local files for upload and previews.'),
  2235. 'type' => STREAM_WRAPPERS_LOCAL_HIDDEN,
  2236. ),
  2237. 'cdn' => array(
  2238. 'name' => t('Content delivery network files'),
  2239. // @todo: Fix the name of this class when we decide on module PSR-0 usage.
  2240. 'class' => 'MyModuleCDNStream',
  2241. 'description' => t('Files served by a content delivery network.'),
  2242. // 'type' can be omitted to use the default of STREAM_WRAPPERS_NORMAL
  2243. ),
  2244. 'youtube' => array(
  2245. 'name' => t('YouTube video'),
  2246. // @todo: Fix the name of this class when we decide on module PSR-0 usage.
  2247. 'class' => 'MyModuleYouTubeStream',
  2248. 'description' => t('Video streamed from YouTube.'),
  2249. // A module implementing YouTube integration may decide to support using
  2250. // the YouTube API for uploading video, but here, we assume that this
  2251. // particular module only supports playing YouTube video.
  2252. 'type' => STREAM_WRAPPERS_READ_VISIBLE,
  2253. ),
  2254. );
  2255. }
  2256. /**
  2257. * Alters the list of PHP stream wrapper implementations.
  2258. *
  2259. * @see file_get_stream_wrappers()
  2260. * @see hook_stream_wrappers()
  2261. */
  2262. function hook_stream_wrappers_alter(&$wrappers) {
  2263. // Change the name of private files to reflect the performance.
  2264. $wrappers['private']['name'] = t('Slow files');
  2265. }
  2266. /**
  2267. * Load additional information into file objects.
  2268. *
  2269. * file_load_multiple() calls this hook to allow modules to load
  2270. * additional information into each file.
  2271. *
  2272. * @param $files
  2273. * An array of file objects, indexed by fid.
  2274. *
  2275. * @see file_load_multiple()
  2276. * @see file_load()
  2277. */
  2278. function hook_file_load($files) {
  2279. // Add the upload specific data into the file object.
  2280. $result = db_query('SELECT * FROM {upload} u WHERE u.fid IN (:fids)', array(':fids' => array_keys($files)))->fetchAll(PDO::FETCH_ASSOC);
  2281. foreach ($result as $record) {
  2282. foreach ($record as $key => $value) {
  2283. $files[$record['fid']]->$key = $value;
  2284. }
  2285. }
  2286. }
  2287. /**
  2288. * Check that files meet a given criteria.
  2289. *
  2290. * This hook lets modules perform additional validation on files. They're able
  2291. * to report a failure by returning one or more error messages.
  2292. *
  2293. * @param $file
  2294. * The file object being validated.
  2295. * @return
  2296. * An array of error messages. If there are no problems with the file return
  2297. * an empty array.
  2298. *
  2299. * @see file_validate()
  2300. */
  2301. function hook_file_validate($file) {
  2302. $errors = array();
  2303. if (empty($file->filename)) {
  2304. $errors[] = t("The file's name is empty. Please give a name to the file.");
  2305. }
  2306. if (strlen($file->filename) > 255) {
  2307. $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  2308. }
  2309. return $errors;
  2310. }
  2311. /**
  2312. * Act on a file being inserted or updated.
  2313. *
  2314. * This hook is called when a file has been added to the database. The hook
  2315. * doesn't distinguish between files created as a result of a copy or those
  2316. * created by an upload.
  2317. *
  2318. * @param $file
  2319. * The file that has just been created.
  2320. *
  2321. * @see file_save()
  2322. */
  2323. function hook_file_presave($file) {
  2324. // Change the file timestamp to an hour prior.
  2325. $file->timestamp -= 3600;
  2326. }
  2327. /**
  2328. * Respond to a file being added.
  2329. *
  2330. * This hook is called after a file has been added to the database. The hook
  2331. * doesn't distinguish between files created as a result of a copy or those
  2332. * created by an upload.
  2333. *
  2334. * @param $file
  2335. * The file that has been added.
  2336. *
  2337. * @see file_save()
  2338. */
  2339. function hook_file_insert($file) {
  2340. // Add a message to the log, if the file is a jpg
  2341. $validate = file_validate_extensions($file, 'jpg');
  2342. if (empty($validate)) {
  2343. watchdog('file', 'A jpg has been added.');
  2344. }
  2345. }
  2346. /**
  2347. * Respond to a file being updated.
  2348. *
  2349. * This hook is called when file_save() is called on an existing file.
  2350. *
  2351. * @param $file
  2352. * The file that has just been updated.
  2353. *
  2354. * @see file_save()
  2355. */
  2356. function hook_file_update($file) {
  2357. }
  2358. /**
  2359. * Respond to a file that has been copied.
  2360. *
  2361. * @param $file
  2362. * The newly copied file object.
  2363. * @param $source
  2364. * The original file before the copy.
  2365. *
  2366. * @see file_copy()
  2367. */
  2368. function hook_file_copy($file, $source) {
  2369. }
  2370. /**
  2371. * Respond to a file that has been moved.
  2372. *
  2373. * @param $file
  2374. * The updated file object after the move.
  2375. * @param $source
  2376. * The original file object before the move.
  2377. *
  2378. * @see file_move()
  2379. */
  2380. function hook_file_move($file, $source) {
  2381. }
  2382. /**
  2383. * Act prior to file deletion.
  2384. *
  2385. * This hook is invoked from file_delete() before the file is removed from the
  2386. * filesystem and before its records are removed from the database.
  2387. *
  2388. * @param $file
  2389. * The file that is about to be deleted.
  2390. *
  2391. * @see hook_file_delete()
  2392. * @see file_delete()
  2393. * @see upload_file_delete()
  2394. */
  2395. function hook_file_predelete($file) {
  2396. // Delete all information associated with the file.
  2397. db_delete('upload')->condition('fid', $file->fid)->execute();
  2398. }
  2399. /**
  2400. * Respond to file deletion.
  2401. *
  2402. * This hook is invoked from file_delete() after the file has been removed from
  2403. * the filesystem and after its records have been removed from the database.
  2404. *
  2405. * @param $file
  2406. * The file that has just been deleted.
  2407. *
  2408. * @see hook_file_predelete()
  2409. * @see file_delete()
  2410. */
  2411. function hook_file_delete($file) {
  2412. // Delete all information associated with the file.
  2413. db_delete('upload')->condition('fid', $file->fid)->execute();
  2414. }
  2415. /**
  2416. * Control access to private file downloads and specify HTTP headers.
  2417. *
  2418. * This hook allows modules enforce permissions on file downloads when the
  2419. * private file download method is selected. Modules can also provide headers
  2420. * to specify information like the file's name or MIME type.
  2421. *
  2422. * @param $uri
  2423. * The URI of the file.
  2424. * @return
  2425. * If the user does not have permission to access the file, return -1. If the
  2426. * user has permission, return an array with the appropriate headers. If the
  2427. * file is not controlled by the current module, the return value should be
  2428. * NULL.
  2429. *
  2430. * @see file_download()
  2431. */
  2432. function hook_file_download($uri) {
  2433. // Check if the file is controlled by the current module.
  2434. if (!file_prepare_directory($uri)) {
  2435. $uri = FALSE;
  2436. }
  2437. if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
  2438. if (!user_access('access user profiles')) {
  2439. // Access to the file is denied.
  2440. return -1;
  2441. }
  2442. else {
  2443. $info = image_get_info($uri);
  2444. return array('Content-Type' => $info['mime_type']);
  2445. }
  2446. }
  2447. }
  2448. /**
  2449. * Alter the URL to a file.
  2450. *
  2451. * This hook is called from file_create_url(), and is called fairly
  2452. * frequently (10+ times per page), depending on how many files there are in a
  2453. * given page.
  2454. * If CSS and JS aggregation are disabled, this can become very frequently
  2455. * (50+ times per page) so performance is critical.
  2456. *
  2457. * This function should alter the URI, if it wants to rewrite the file URL.
  2458. *
  2459. * @param $uri
  2460. * The URI to a file for which we need an external URL, or the path to a
  2461. * shipped file.
  2462. */
  2463. function hook_file_url_alter(&$uri) {
  2464. global $user;
  2465. // User 1 will always see the local file in this example.
  2466. if ($user->uid == 1) {
  2467. return;
  2468. }
  2469. $cdn1 = 'http://cdn1.example.com';
  2470. $cdn2 = 'http://cdn2.example.com';
  2471. $cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png');
  2472. // Most CDNs don't support private file transfers without a lot of hassle,
  2473. // so don't support this in the common case.
  2474. $schemes = array('public');
  2475. $scheme = file_uri_scheme($uri);
  2476. // Only serve shipped files and public created files from the CDN.
  2477. if (!$scheme || in_array($scheme, $schemes)) {
  2478. // Shipped files.
  2479. if (!$scheme) {
  2480. $path = $uri;
  2481. }
  2482. // Public created files.
  2483. else {
  2484. $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
  2485. $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
  2486. }
  2487. // Clean up Windows paths.
  2488. $path = str_replace('\\', '/', $path);
  2489. // Serve files with one of the CDN extensions from CDN 1, all others from
  2490. // CDN 2.
  2491. $pathinfo = pathinfo($path);
  2492. if (isset($pathinfo['extension']) && in_array($pathinfo['extension'], $cdn_extensions)) {
  2493. $uri = $cdn1 . '/' . $path;
  2494. }
  2495. else {
  2496. $uri = $cdn2 . '/' . $path;
  2497. }
  2498. }
  2499. }
  2500. /**
  2501. * Check installation requirements and do status reporting.
  2502. *
  2503. * This hook has three closely related uses, determined by the $phase argument:
  2504. * - Checking installation requirements ($phase == 'install').
  2505. * - Checking update requirements ($phase == 'update').
  2506. * - Status reporting ($phase == 'runtime').
  2507. *
  2508. * Note that this hook, like all others dealing with installation and updates,
  2509. * must reside in a module_name.install file, or it will not properly abort
  2510. * the installation of the module if a critical requirement is missing.
  2511. *
  2512. * During the 'install' phase, modules can for example assert that
  2513. * library or server versions are available or sufficient.
  2514. * Note that the installation of a module can happen during installation of
  2515. * Drupal itself (by install.php) with an installation profile or later by hand.
  2516. * As a consequence, install-time requirements must be checked without access
  2517. * to the full Drupal API, because it is not available during install.php.
  2518. * For localization you should for example use $t = get_t() to
  2519. * retrieve the appropriate localization function name (t() or st()).
  2520. * If a requirement has a severity of REQUIREMENT_ERROR, install.php will abort
  2521. * or at least the module will not install.
  2522. * Other severity levels have no effect on the installation.
  2523. * Module dependencies do not belong to these installation requirements,
  2524. * but should be defined in the module's .info file.
  2525. *
  2526. * The 'runtime' phase is not limited to pure installation requirements
  2527. * but can also be used for more general status information like maintenance
  2528. * tasks and security issues.
  2529. * The returned 'requirements' will be listed on the status report in the
  2530. * administration section, with indication of the severity level.
  2531. * Moreover, any requirement with a severity of REQUIREMENT_ERROR severity will
  2532. * result in a notice on the the administration overview page.
  2533. *
  2534. * @param $phase
  2535. * The phase in which requirements are checked:
  2536. * - install: The module is being installed.
  2537. * - update: The module is enabled and update.php is run.
  2538. * - runtime: The runtime requirements are being checked and shown on the
  2539. * status report page.
  2540. *
  2541. * @return
  2542. * A keyed array of requirements. Each requirement is itself an array with
  2543. * the following items:
  2544. * - title: The name of the requirement.
  2545. * - value: The current value (e.g., version, time, level, etc). During
  2546. * install phase, this should only be used for version numbers, do not set
  2547. * it if not applicable.
  2548. * - description: The description of the requirement/status.
  2549. * - severity: The requirement's result/severity level, one of:
  2550. * - REQUIREMENT_INFO: For info only.
  2551. * - REQUIREMENT_OK: The requirement is satisfied.
  2552. * - REQUIREMENT_WARNING: The requirement failed with a warning.
  2553. * - REQUIREMENT_ERROR: The requirement failed with an error.
  2554. */
  2555. function hook_requirements($phase) {
  2556. $requirements = array();
  2557. // Ensure translations don't break at install time
  2558. $t = get_t();
  2559. // Report Drupal version
  2560. if ($phase == 'runtime') {
  2561. $requirements['drupal'] = array(
  2562. 'title' => $t('Drupal'),
  2563. 'value' => VERSION,
  2564. 'severity' => REQUIREMENT_INFO
  2565. );
  2566. }
  2567. // Test PHP version
  2568. $requirements['php'] = array(
  2569. 'title' => $t('PHP'),
  2570. 'value' => ($phase == 'runtime') ? l(phpversion(), 'admin/reports/status/php') : phpversion(),
  2571. );
  2572. if (version_compare(phpversion(), DRUPAL_MINIMUM_PHP) < 0) {
  2573. $requirements['php']['description'] = $t('Your PHP installation is too old. Drupal requires at least PHP %version.', array('%version' => DRUPAL_MINIMUM_PHP));
  2574. $requirements['php']['severity'] = REQUIREMENT_ERROR;
  2575. }
  2576. // Report cron status
  2577. if ($phase == 'runtime') {
  2578. $cron_last = variable_get('cron_last');
  2579. if (is_numeric($cron_last)) {
  2580. $requirements['cron']['value'] = $t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
  2581. }
  2582. else {
  2583. $requirements['cron'] = array(
  2584. 'description' => $t('Cron has not run. It appears cron jobs have not been setup on your system. Check the help pages for <a href="@url">configuring cron jobs</a>.', array('@url' => 'http://drupal.org/cron')),
  2585. 'severity' => REQUIREMENT_ERROR,
  2586. 'value' => $t('Never run'),
  2587. );
  2588. }
  2589. $requirements['cron']['description'] .= ' ' . $t('You can <a href="@cron">run cron manually</a>.', array('@cron' => url('admin/reports/status/run-cron')));
  2590. $requirements['cron']['title'] = $t('Cron maintenance tasks');
  2591. }
  2592. return $requirements;
  2593. }
  2594. /**
  2595. * Define the current version of the database schema.
  2596. *
  2597. * A Drupal schema definition is an array structure representing one or
  2598. * more tables and their related keys and indexes. A schema is defined by
  2599. * hook_schema() which must live in your module's .install file.
  2600. *
  2601. * This hook is called at both install and uninstall time, and in the latter
  2602. * case, it cannot rely on the .module file being loaded or hooks being known.
  2603. * If the .module file is needed, it may be loaded with drupal_load().
  2604. *
  2605. * The tables declared by this hook will be automatically created when
  2606. * the module is first enabled, and removed when the module is uninstalled.
  2607. * This happens before hook_install() is invoked, and after hook_uninstall()
  2608. * is invoked, respectively.
  2609. *
  2610. * By declaring the tables used by your module via an implementation of
  2611. * hook_schema(), these tables will be available on all supported database
  2612. * engines. You don't have to deal with the different SQL dialects for table
  2613. * creation and alteration of the supported database engines.
  2614. *
  2615. * See the Schema API Handbook at http://drupal.org/node/146843 for
  2616. * details on schema definition structures.
  2617. *
  2618. * @return
  2619. * A schema definition structure array. For each element of the
  2620. * array, the key is a table name and the value is a table structure
  2621. * definition.
  2622. *
  2623. * @ingroup schemaapi
  2624. */
  2625. function hook_schema() {
  2626. $schema['node'] = array(
  2627. // example (partial) specification for table "node"
  2628. 'description' => 'The base table for nodes.',
  2629. 'fields' => array(
  2630. 'nid' => array(
  2631. 'description' => 'The primary identifier for a node.',
  2632. 'type' => 'serial',
  2633. 'unsigned' => TRUE,
  2634. 'not null' => TRUE),
  2635. 'vid' => array(
  2636. 'description' => 'The current {node_revision}.vid version identifier.',
  2637. 'type' => 'int',
  2638. 'unsigned' => TRUE,
  2639. 'not null' => TRUE,
  2640. 'default' => 0),
  2641. 'type' => array(
  2642. 'description' => 'The {node_type} of this node.',
  2643. 'type' => 'varchar',
  2644. 'length' => 32,
  2645. 'not null' => TRUE,
  2646. 'default' => ''),
  2647. 'title' => array(
  2648. 'description' => 'The title of this node, always treated as non-markup plain text.',
  2649. 'type' => 'varchar',
  2650. 'length' => 255,
  2651. 'not null' => TRUE,
  2652. 'default' => ''),
  2653. ),
  2654. 'indexes' => array(
  2655. 'node_changed' => array('changed'),
  2656. 'node_created' => array('created'),
  2657. ),
  2658. 'unique keys' => array(
  2659. 'nid_vid' => array('nid', 'vid'),
  2660. 'vid' => array('vid')
  2661. ),
  2662. 'foreign keys' => array(
  2663. 'node_revision' => array(
  2664. 'table' => 'node_revision',
  2665. 'columns' => array('vid' => 'vid'),
  2666. ),
  2667. 'node_author' => array(
  2668. 'table' => 'users',
  2669. 'columns' => array('uid' => 'uid')
  2670. ),
  2671. ),
  2672. 'primary key' => array('nid'),
  2673. );
  2674. return $schema;
  2675. }
  2676. /**
  2677. * Perform alterations to existing database schemas.
  2678. *
  2679. * When a module modifies the database structure of another module (by
  2680. * changing, adding or removing fields, keys or indexes), it should
  2681. * implement hook_schema_alter() to update the default $schema to take its
  2682. * changes into account.
  2683. *
  2684. * See hook_schema() for details on the schema definition structure.
  2685. *
  2686. * @param $schema
  2687. * Nested array describing the schemas for all modules.
  2688. */
  2689. function hook_schema_alter(&$schema) {
  2690. // Add field to existing schema.
  2691. $schema['users']['fields']['timezone_id'] = array(
  2692. 'type' => 'int',
  2693. 'not null' => TRUE,
  2694. 'default' => 0,
  2695. 'description' => 'Per-user timezone configuration.',
  2696. );
  2697. }
  2698. /**
  2699. * Perform alterations to a structured query.
  2700. *
  2701. * Structured (aka dynamic) queries that have tags associated may be altered by any module
  2702. * before the query is executed.
  2703. *
  2704. * @param $query
  2705. * A Query object describing the composite parts of a SQL query.
  2706. *
  2707. * @see hook_query_TAG_alter()
  2708. * @see node_query_node_access_alter()
  2709. * @see AlterableInterface
  2710. * @see SelectInterface
  2711. */
  2712. function hook_query_alter(DrupalDatabaseQueryAlterableInterface $query) {
  2713. if ($query->hasTag('micro_limit')) {
  2714. $query->range(0, 2);
  2715. }
  2716. }
  2717. /**
  2718. * Perform alterations to a structured query for a given tag.
  2719. *
  2720. * @param $query
  2721. * An Query object describing the composite parts of a SQL query.
  2722. *
  2723. * @see hook_query_alter()
  2724. * @see node_query_node_access_alter()
  2725. * @see AlterableInterface
  2726. * @see SelectInterface
  2727. */
  2728. function hook_query_TAG_alter(DrupalDatabaseQueryAlterableInterface $query) {
  2729. // Skip the extra expensive alterations if site has no node access control modules.
  2730. if (!node_access_view_all_nodes()) {
  2731. // Prevent duplicates records.
  2732. $query->distinct();
  2733. // The recognized operations are 'view', 'update', 'delete'.
  2734. if (!$op = $query->getMetaData('op')) {
  2735. $op = 'view';
  2736. }
  2737. // Skip the extra joins and conditions for node admins.
  2738. if (!user_access('bypass node access')) {
  2739. // The node_access table has the access grants for any given node.
  2740. $access_alias = $query->join('node_access', 'na', '%alias.nid = n.nid');
  2741. $or = db_or();
  2742. // If any grant exists for the specified user, then user has access to the node for the specified operation.
  2743. foreach (node_access_grants($op, $query->getMetaData('account')) as $realm => $gids) {
  2744. foreach ($gids as $gid) {
  2745. $or->condition(db_and()
  2746. ->condition($access_alias . '.gid', $gid)
  2747. ->condition($access_alias . '.realm', $realm)
  2748. );
  2749. }
  2750. }
  2751. if (count($or->conditions())) {
  2752. $query->condition($or);
  2753. }
  2754. $query->condition($access_alias . 'grant_' . $op, 1, '>=');
  2755. }
  2756. }
  2757. }
  2758. /**
  2759. * Perform setup tasks when the module is installed.
  2760. *
  2761. * If the module implements hook_schema(), the database tables will
  2762. * be created before this hook is fired.
  2763. *
  2764. * Implementations of this hook are by convention declared in the module's
  2765. * .install file. The implementation can rely on the .module file being loaded.
  2766. * The hook will only be called the first time a module is enabled or after it
  2767. * is re-enabled after being uninstalled. The module's schema version will be
  2768. * set to the module's greatest numbered update hook. Because of this, any time
  2769. * a hook_update_N() is added to the module, this function needs to be updated
  2770. * to reflect the current version of the database schema.
  2771. *
  2772. * See the Schema API documentation at
  2773. * @link http://drupal.org/node/146843 http://drupal.org/node/146843 @endlink
  2774. * for details on hook_schema and how database tables are defined.
  2775. *
  2776. * Note that since this function is called from a full bootstrap, all functions
  2777. * (including those in modules enabled by the current page request) are
  2778. * available when this hook is called. Use cases could be displaying a user
  2779. * message, or calling a module function necessary for initial setup, etc.
  2780. *
  2781. * Please be sure that anything added or modified in this function that can
  2782. * be removed during uninstall should be removed with hook_uninstall().
  2783. *
  2784. * @see hook_schema()
  2785. * @see module_enable()
  2786. * @see hook_enable()
  2787. * @see hook_disable()
  2788. * @see hook_uninstall()
  2789. * @see hook_modules_installed()
  2790. */
  2791. function hook_install() {
  2792. // Populate the default {node_access} record.
  2793. db_insert('node_access')
  2794. ->fields(array(
  2795. 'nid' => 0,
  2796. 'gid' => 0,
  2797. 'realm' => 'all',
  2798. 'grant_view' => 1,
  2799. 'grant_update' => 0,
  2800. 'grant_delete' => 0,
  2801. ))
  2802. ->execute();
  2803. }
  2804. /**
  2805. * Perform a single update.
  2806. *
  2807. * For each patch which requires a database change add a new hook_update_N()
  2808. * which will be called by update.php. The database updates are numbered
  2809. * sequentially according to the version of Drupal you are compatible with.
  2810. *
  2811. * Schema updates should adhere to the Schema API:
  2812. * @link http://drupal.org/node/150215 http://drupal.org/node/150215 @endlink
  2813. *
  2814. * Database updates consist of 3 parts:
  2815. * - 1 digit for Drupal core compatibility
  2816. * - 1 digit for your module's major release version (e.g. is this the 5.x-1.* (1) or 5.x-2.* (2) series of your module?)
  2817. * - 2 digits for sequential counting starting with 00
  2818. *
  2819. * The 2nd digit should be 0 for initial porting of your module to a new Drupal
  2820. * core API.
  2821. *
  2822. * Examples:
  2823. * - mymodule_update_5200()
  2824. * - This is the first update to get the database ready to run mymodule 5.x-2.*.
  2825. * - mymodule_update_6000()
  2826. * - This is the required update for mymodule to run with Drupal core API 6.x.
  2827. * - mymodule_update_6100()
  2828. * - This is the first update to get the database ready to run mymodule 6.x-1.*.
  2829. * - mymodule_update_6200()
  2830. * - This is the first update to get the database ready to run mymodule 6.x-2.*.
  2831. * Users can directly update from 5.x-2.* to 6.x-2.* and they get all 60XX
  2832. * and 62XX updates, but not 61XX updates, because those reside in the
  2833. * 6.x-1.x branch only.
  2834. *
  2835. * A good rule of thumb is to remove updates older than two major releases of
  2836. * Drupal. See hook_update_last_removed() to notify Drupal about the removals.
  2837. * For further information about releases and release numbers see:
  2838. * @link http://drupal.org/node/711070 Maintaining a drupal.org project with Git @endlink
  2839. *
  2840. * Never renumber update functions.
  2841. *
  2842. * Implementations of this hook should be placed in a mymodule.install file in
  2843. * the same directory as mymodule.module. Drupal core's updates are implemented
  2844. * using the system module as a name and stored in database/updates.inc.
  2845. *
  2846. * If your update task is potentially time-consuming, you'll need to implement a
  2847. * multipass update to avoid PHP timeouts. Multipass updates use the $sandbox
  2848. * parameter provided by the batch API (normally, $context['sandbox']) to store
  2849. * information between successive calls, and the $sandbox['#finished'] value
  2850. * to provide feedback regarding completion level.
  2851. *
  2852. * See the batch operations page for more information on how to use the batch API:
  2853. * @link http://drupal.org/node/180528 http://drupal.org/node/180528 @endlink
  2854. *
  2855. * @param $sandbox
  2856. * Stores information for multipass updates. See above for more information.
  2857. *
  2858. * @throws DrupalUpdateException, PDOException
  2859. * In case of error, update hooks should throw an instance of DrupalUpdateException
  2860. * with a meaningful message for the user. If a database query fails for whatever
  2861. * reason, it will throw a PDOException.
  2862. *
  2863. * @return
  2864. * Optionally update hooks may return a translated string that will be displayed
  2865. * to the user. If no message is returned, no message will be presented to the
  2866. * user.
  2867. */
  2868. function hook_update_N(&$sandbox) {
  2869. // For non-multipass updates, the signature can simply be;
  2870. // function hook_update_N() {
  2871. // For most updates, the following is sufficient.
  2872. db_add_field('mytable1', 'newcol', array('type' => 'int', 'not null' => TRUE, 'description' => 'My new integer column.'));
  2873. // However, for more complex operations that may take a long time,
  2874. // you may hook into Batch API as in the following example.
  2875. // Update 3 users at a time to have an exclamation point after their names.
  2876. // (They're really happy that we can do batch API in this hook!)
  2877. if (!isset($sandbox['progress'])) {
  2878. $sandbox['progress'] = 0;
  2879. $sandbox['current_uid'] = 0;
  2880. // We'll -1 to disregard the uid 0...
  2881. $sandbox['max'] = db_query('SELECT COUNT(DISTINCT uid) FROM {users}')->fetchField() - 1;
  2882. }
  2883. $users = db_select('users', 'u')
  2884. ->fields('u', array('uid', 'name'))
  2885. ->condition('uid', $sandbox['current_uid'], '>')
  2886. ->range(0, 3)
  2887. ->orderBy('uid', 'ASC')
  2888. ->execute();
  2889. foreach ($users as $user) {
  2890. $user->name .= '!';
  2891. db_update('users')
  2892. ->fields(array('name' => $user->name))
  2893. ->condition('uid', $user->uid)
  2894. ->execute();
  2895. $sandbox['progress']++;
  2896. $sandbox['current_uid'] = $user->uid;
  2897. }
  2898. $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
  2899. // To display a message to the user when the update is completed, return it.
  2900. // If you do not want to display a completion message, simply return nothing.
  2901. return t('The update did what it was supposed to do.');
  2902. // In case of an error, simply throw an exception with an error message.
  2903. throw new DrupalUpdateException('Something went wrong; here is what you should do.');
  2904. }
  2905. /**
  2906. * Return an array of information about module update dependencies.
  2907. *
  2908. * This can be used to indicate update functions from other modules that your
  2909. * module's update functions depend on, or vice versa. It is used by the update
  2910. * system to determine the appropriate order in which updates should be run, as
  2911. * well as to search for missing dependencies.
  2912. *
  2913. * Implementations of this hook should be placed in a mymodule.install file in
  2914. * the same directory as mymodule.module.
  2915. *
  2916. * @return
  2917. * A multidimensional array containing information about the module update
  2918. * dependencies. The first two levels of keys represent the module and update
  2919. * number (respectively) for which information is being returned, and the
  2920. * value is an array of information about that update's dependencies. Within
  2921. * this array, each key represents a module, and each value represents the
  2922. * number of an update function within that module. In the event that your
  2923. * update function depends on more than one update from a particular module,
  2924. * you should always list the highest numbered one here (since updates within
  2925. * a given module always run in numerical order).
  2926. *
  2927. * @see update_resolve_dependencies()
  2928. * @see hook_update_N()
  2929. */
  2930. function hook_update_dependencies() {
  2931. // Indicate that the mymodule_update_8000() function provided by this module
  2932. // must run after the another_module_update_8002() function provided by the
  2933. // 'another_module' module.
  2934. $dependencies['mymodule'][8000] = array(
  2935. 'another_module' => 8002,
  2936. );
  2937. // Indicate that the mymodule_update_8001() function provided by this module
  2938. // must run before the yet_another_module_update_8004() function provided by
  2939. // the 'yet_another_module' module. (Note that declaring dependencies in this
  2940. // direction should be done only in rare situations, since it can lead to the
  2941. // following problem: If a site has already run the yet_another_module
  2942. // module's database updates before it updates its codebase to pick up the
  2943. // newest mymodule code, then the dependency declared here will be ignored.)
  2944. $dependencies['yet_another_module'][8004] = array(
  2945. 'mymodule' => 8001,
  2946. );
  2947. return $dependencies;
  2948. }
  2949. /**
  2950. * Return a number which is no longer available as hook_update_N().
  2951. *
  2952. * If you remove some update functions from your mymodule.install file, you
  2953. * should notify Drupal of those missing functions. This way, Drupal can
  2954. * ensure that no update is accidentally skipped.
  2955. *
  2956. * Implementations of this hook should be placed in a mymodule.install file in
  2957. * the same directory as mymodule.module.
  2958. *
  2959. * @return
  2960. * An integer, corresponding to hook_update_N() which has been removed from
  2961. * mymodule.install.
  2962. *
  2963. * @see hook_update_N()
  2964. */
  2965. function hook_update_last_removed() {
  2966. // We've removed the 5.x-1.x version of mymodule, including database updates.
  2967. // The next update function is mymodule_update_5200().
  2968. return 5103;
  2969. }
  2970. /**
  2971. * Remove any information that the module sets.
  2972. *
  2973. * The information that the module should remove includes:
  2974. * - variables that the module has set using variable_set() or system_settings_form()
  2975. * - modifications to existing tables
  2976. *
  2977. * The module should not remove its entry from the {system} table. Database
  2978. * tables defined by hook_schema() will be removed automatically.
  2979. *
  2980. * The uninstall hook must be implemented in the module's .install file. It
  2981. * will fire when the module gets uninstalled but before the module's database
  2982. * tables are removed, allowing your module to query its own tables during
  2983. * this routine.
  2984. *
  2985. * When hook_uninstall() is called, your module will already be disabled, so
  2986. * its .module file will not be automatically included. If you need to call API
  2987. * functions from your .module file in this hook, use drupal_load() to make
  2988. * them available. (Keep this usage to a minimum, though, especially when
  2989. * calling API functions that invoke hooks, or API functions from modules
  2990. * listed as dependencies, since these may not be available or work as expected
  2991. * when the module is disabled.)
  2992. *
  2993. * @see hook_install()
  2994. * @see hook_schema()
  2995. * @see hook_disable()
  2996. * @see hook_modules_uninstalled()
  2997. */
  2998. function hook_uninstall() {
  2999. variable_del('upload_file_types');
  3000. }
  3001. /**
  3002. * Perform necessary actions after module is enabled.
  3003. *
  3004. * The hook is called every time the module is enabled. It should be
  3005. * implemented in the module's .install file. The implementation can
  3006. * rely on the .module file being loaded.
  3007. *
  3008. * @see module_enable()
  3009. * @see hook_install()
  3010. * @see hook_modules_enabled()
  3011. */
  3012. function hook_enable() {
  3013. mymodule_cache_rebuild();
  3014. }
  3015. /**
  3016. * Perform necessary actions before module is disabled.
  3017. *
  3018. * The hook is called every time the module is disabled. It should be
  3019. * implemented in the module's .install file. The implementation can rely
  3020. * on the .module file being loaded.
  3021. *
  3022. * @see hook_uninstall()
  3023. * @see hook_modules_disabled()
  3024. */
  3025. function hook_disable() {
  3026. mymodule_cache_rebuild();
  3027. }
  3028. /**
  3029. * Perform necessary alterations to the list of files parsed by the registry.
  3030. *
  3031. * Modules can manually modify the list of files before the registry parses
  3032. * them. The $modules array provides the .info file information, which includes
  3033. * the list of files registered to each module. Any files in the list can then
  3034. * be added to the list of files that the registry will parse, or modify
  3035. * attributes of a file.
  3036. *
  3037. * A necessary alteration made by the core SimpleTest module is to force .test
  3038. * files provided by disabled modules into the list of files parsed by the
  3039. * registry.
  3040. *
  3041. * @param $files
  3042. * List of files to be parsed by the registry. The list will contain
  3043. * files found in each enabled module's info file and the core includes
  3044. * directory. The array is keyed by the file path and contains an array of
  3045. * the related module's name and weight as used internally by
  3046. * _registry_update() and related functions.
  3047. *
  3048. * For example:
  3049. * @code
  3050. * $files["modules/system/system.module"] = array(
  3051. * 'module' => 'system',
  3052. * 'weight' => 0,
  3053. * );
  3054. * @endcode
  3055. * @param $modules
  3056. * An array containing all module information stored in the {system} table.
  3057. * Each element of the array also contains the module's .info file
  3058. * information in the property 'info'. An additional 'dir' property has been
  3059. * added to the module information which provides the path to the directory
  3060. * in which the module resides. The example shows how to take advantage of
  3061. * both properties.
  3062. *
  3063. * @see _registry_update()
  3064. * @see simpletest_test_get_all()
  3065. */
  3066. function hook_registry_files_alter(&$files, $modules) {
  3067. foreach ($modules as $module) {
  3068. // Only add test files for disabled modules, as enabled modules should
  3069. // already include any test files they provide.
  3070. if (!$module->status) {
  3071. $dir = $module->dir;
  3072. foreach ($module->info['files'] as $file) {
  3073. if (substr($file, -5) == '.test') {
  3074. $files["$dir/$file"] = array('module' => $module->name, 'weight' => $module->weight);
  3075. }
  3076. }
  3077. }
  3078. }
  3079. }
  3080. /**
  3081. * Return an array of tasks to be performed by an installation profile.
  3082. *
  3083. * Any tasks you define here will be run, in order, after the installer has
  3084. * finished the site configuration step but before it has moved on to the
  3085. * final import of languages and the end of the installation. You can have any
  3086. * number of custom tasks to perform during this phase.
  3087. *
  3088. * Each task you define here corresponds to a callback function which you must
  3089. * separately define and which is called when your task is run. This function
  3090. * will receive the global installation state variable, $install_state, as
  3091. * input, and has the opportunity to access or modify any of its settings. See
  3092. * the install_state_defaults() function in the installer for the list of
  3093. * $install_state settings used by Drupal core.
  3094. *
  3095. * At the end of your task function, you can indicate that you want the
  3096. * installer to pause and display a page to the user by returning any themed
  3097. * output that should be displayed on that page (but see below for tasks that
  3098. * use the form API or batch API; the return values of these task functions are
  3099. * handled differently). You should also use drupal_set_title() within the task
  3100. * callback function to set a custom page title. For some tasks, however, you
  3101. * may want to simply do some processing and pass control to the next task
  3102. * without ending the page request; to indicate this, simply do not send back
  3103. * a return value from your task function at all. This can be used, for
  3104. * example, by installation profiles that need to configure certain site
  3105. * settings in the database without obtaining any input from the user.
  3106. *
  3107. * The task function is treated specially if it defines a form or requires
  3108. * batch processing; in that case, you should return either the form API
  3109. * definition or batch API array, as appropriate. See below for more
  3110. * information on the 'type' key that you must define in the task definition
  3111. * to inform the installer that your task falls into one of those two
  3112. * categories. It is important to use these APIs directly, since the installer
  3113. * may be run non-interactively (for example, via a command line script), all
  3114. * in one page request; in that case, the installer will automatically take
  3115. * care of submitting forms and processing batches correctly for both types of
  3116. * installations. You can inspect the $install_state['interactive'] boolean to
  3117. * see whether or not the current installation is interactive, if you need
  3118. * access to this information.
  3119. *
  3120. * Remember that a user installing Drupal interactively will be able to reload
  3121. * an installation page multiple times, so you should use variable_set() and
  3122. * variable_get() if you are collecting any data that you need to store and
  3123. * inspect later. It is important to remove any temporary variables using
  3124. * variable_del() before your last task has completed and control is handed
  3125. * back to the installer.
  3126. *
  3127. * @return
  3128. * A keyed array of tasks the profile will perform during the final stage of
  3129. * the installation. Each key represents the name of a function (usually a
  3130. * function defined by this profile, although that is not strictly required)
  3131. * that is called when that task is run. The values are associative arrays
  3132. * containing the following key-value pairs (all of which are optional):
  3133. * - 'display_name'
  3134. * The human-readable name of the task. This will be displayed to the
  3135. * user while the installer is running, along with a list of other tasks
  3136. * that are being run. Leave this unset to prevent the task from
  3137. * appearing in the list.
  3138. * - 'display'
  3139. * This is a boolean which can be used to provide finer-grained control
  3140. * over whether or not the task will display. This is mostly useful for
  3141. * tasks that are intended to display only under certain conditions; for
  3142. * these tasks, you can set 'display_name' to the name that you want to
  3143. * display, but then use this boolean to hide the task only when certain
  3144. * conditions apply.
  3145. * - 'type'
  3146. * A string representing the type of task. This parameter has three
  3147. * possible values:
  3148. * - 'normal': This indicates that the task will be treated as a regular
  3149. * callback function, which does its processing and optionally returns
  3150. * HTML output. This is the default behavior which is used when 'type' is
  3151. * not set.
  3152. * - 'batch': This indicates that the task function will return a batch
  3153. * API definition suitable for batch_set(). The installer will then take
  3154. * care of automatically running the task via batch processing.
  3155. * - 'form': This indicates that the task function will return a standard
  3156. * form API definition (and separately define validation and submit
  3157. * handlers, as appropriate). The installer will then take care of
  3158. * automatically directing the user through the form submission process.
  3159. * - 'run'
  3160. * A constant representing the manner in which the task will be run. This
  3161. * parameter has three possible values:
  3162. * - INSTALL_TASK_RUN_IF_NOT_COMPLETED: This indicates that the task will
  3163. * run once during the installation of the profile. This is the default
  3164. * behavior which is used when 'run' is not set.
  3165. * - INSTALL_TASK_SKIP: This indicates that the task will not run during
  3166. * the current installation page request. It can be used to skip running
  3167. * an installation task when certain conditions are met, even though the
  3168. * task may still show on the list of installation tasks presented to the
  3169. * user.
  3170. * - INSTALL_TASK_RUN_IF_REACHED: This indicates that the task will run
  3171. * on each installation page request that reaches it. This is rarely
  3172. * necessary for an installation profile to use; it is primarily used by
  3173. * the Drupal installer for bootstrap-related tasks.
  3174. * - 'function'
  3175. * Normally this does not need to be set, but it can be used to force the
  3176. * installer to call a different function when the task is run (rather
  3177. * than the function whose name is given by the array key). This could be
  3178. * used, for example, to allow the same function to be called by two
  3179. * different tasks.
  3180. *
  3181. * @see install_state_defaults()
  3182. * @see batch_set()
  3183. */
  3184. function hook_install_tasks() {
  3185. // Here, we define a variable to allow tasks to indicate that a particular,
  3186. // processor-intensive batch process needs to be triggered later on in the
  3187. // installation.
  3188. $myprofile_needs_batch_processing = variable_get('myprofile_needs_batch_processing', FALSE);
  3189. $tasks = array(
  3190. // This is an example of a task that defines a form which the user who is
  3191. // installing the site will be asked to fill out. To implement this task,
  3192. // your profile would define a function named myprofile_data_import_form()
  3193. // as a normal form API callback function, with associated validation and
  3194. // submit handlers. In the submit handler, in addition to saving whatever
  3195. // other data you have collected from the user, you might also call
  3196. // variable_set('myprofile_needs_batch_processing', TRUE) if the user has
  3197. // entered data which requires that batch processing will need to occur
  3198. // later on.
  3199. 'myprofile_data_import_form' => array(
  3200. 'display_name' => st('Data import options'),
  3201. 'type' => 'form',
  3202. ),
  3203. // Similarly, to implement this task, your profile would define a function
  3204. // named myprofile_settings_form() with associated validation and submit
  3205. // handlers. This form might be used to collect and save additional
  3206. // information from the user that your profile needs. There are no extra
  3207. // steps required for your profile to act as an "installation wizard"; you
  3208. // can simply define as many tasks of type 'form' as you wish to execute,
  3209. // and the forms will be presented to the user, one after another.
  3210. 'myprofile_settings_form' => array(
  3211. 'display_name' => st('Additional options'),
  3212. 'type' => 'form',
  3213. ),
  3214. // This is an example of a task that performs batch operations. To
  3215. // implement this task, your profile would define a function named
  3216. // myprofile_batch_processing() which returns a batch API array definition
  3217. // that the installer will use to execute your batch operations. Due to the
  3218. // 'myprofile_needs_batch_processing' variable used here, this task will be
  3219. // hidden and skipped unless your profile set it to TRUE in one of the
  3220. // previous tasks.
  3221. 'myprofile_batch_processing' => array(
  3222. 'display_name' => st('Import additional data'),
  3223. 'display' => $myprofile_needs_batch_processing,
  3224. 'type' => 'batch',
  3225. 'run' => $myprofile_needs_batch_processing ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
  3226. ),
  3227. // This is an example of a task that will not be displayed in the list that
  3228. // the user sees. To implement this task, your profile would define a
  3229. // function named myprofile_final_site_setup(), in which additional,
  3230. // automated site setup operations would be performed. Since this is the
  3231. // last task defined by your profile, you should also use this function to
  3232. // call variable_del('myprofile_needs_batch_processing') and clean up the
  3233. // variable that was used above. If you want the user to pass to the final
  3234. // Drupal installation tasks uninterrupted, return no output from this
  3235. // function. Otherwise, return themed output that the user will see (for
  3236. // example, a confirmation page explaining that your profile's tasks are
  3237. // complete, with a link to reload the current page and therefore pass on
  3238. // to the final Drupal installation tasks when the user is ready to do so).
  3239. 'myprofile_final_site_setup' => array(
  3240. ),
  3241. );
  3242. return $tasks;
  3243. }
  3244. /**
  3245. * Change the page the user is sent to by drupal_goto().
  3246. *
  3247. * @param $path
  3248. * A Drupal path or a full URL.
  3249. * @param $options
  3250. * An associative array of additional URL options to pass to url().
  3251. * @param $http_response_code
  3252. * The HTTP status code to use for the redirection. See drupal_goto() for more
  3253. * information.
  3254. */
  3255. function hook_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  3256. // A good addition to misery module.
  3257. $http_response_code = 500;
  3258. }
  3259. /**
  3260. * Alter XHTML HEAD tags before they are rendered by drupal_get_html_head().
  3261. *
  3262. * Elements available to be altered are only those added using
  3263. * drupal_add_html_head_link() or drupal_add_html_head(). CSS and JS files
  3264. * are handled using drupal_add_css() and drupal_add_js(), so the head links
  3265. * for those files will not appear in the $head_elements array.
  3266. *
  3267. * @param $head_elements
  3268. * An array of renderable elements. Generally the values of the #attributes
  3269. * array will be the most likely target for changes.
  3270. */
  3271. function hook_html_head_alter(&$head_elements) {
  3272. foreach ($head_elements as $key => $element) {
  3273. if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
  3274. // I want a custom canonical url.
  3275. $head_elements[$key]['#attributes']['href'] = mymodule_canonical_url();
  3276. }
  3277. }
  3278. }
  3279. /**
  3280. * Alter the full list of installation tasks.
  3281. *
  3282. * You can use this hook to change or replace any part of the Drupal
  3283. * installation process that occurs after the installation profile is selected.
  3284. *
  3285. * @param $tasks
  3286. * An array of all available installation tasks, including those provided by
  3287. * Drupal core. You can modify this array to change or replace individual
  3288. * steps within the installation process.
  3289. * @param $install_state
  3290. * An array of information about the current installation state.
  3291. */
  3292. function hook_install_tasks_alter(&$tasks, $install_state) {
  3293. // Replace the entire site configuration form provided by Drupal core
  3294. // with a custom callback function defined by this installation profile.
  3295. $tasks['install_configure_form']['function'] = 'myprofile_install_configure_form';
  3296. }
  3297. /**
  3298. * Alter MIME type mappings used to determine MIME type from a file extension.
  3299. *
  3300. * This hook is run when file_mimetype_mapping() is called. It is used to
  3301. * allow modules to add to or modify the default mapping from
  3302. * file_default_mimetype_mapping().
  3303. *
  3304. * @param $mapping
  3305. * An array of mimetypes correlated to the extensions that relate to them.
  3306. * The array has 'mimetypes' and 'extensions' elements, each of which is an
  3307. * array.
  3308. *
  3309. * @see file_default_mimetype_mapping()
  3310. */
  3311. function hook_file_mimetype_mapping_alter(&$mapping) {
  3312. // Add new MIME type 'drupal/info'.
  3313. $mapping['mimetypes']['example_info'] = 'drupal/info';
  3314. // Add new extension '.info' and map it to the 'drupal/info' MIME type.
  3315. $mapping['extensions']['info'] = 'example_info';
  3316. // Override existing extension mapping for '.ogg' files.
  3317. $mapping['extensions']['ogg'] = 189;
  3318. }
  3319. /**
  3320. * Declares information about actions.
  3321. *
  3322. * Any module can define actions, and then call actions_do() to make those
  3323. * actions happen in response to events.
  3324. *
  3325. * An action consists of two or three parts:
  3326. * - an action definition (returned by this hook)
  3327. * - a function which performs the action (which by convention is named
  3328. * MODULE_description-of-function_action)
  3329. * - an optional form definition function that defines a configuration form
  3330. * (which has the name of the action function with '_form' appended to it.)
  3331. *
  3332. * The action function takes two to four arguments, which come from the input
  3333. * arguments to actions_do().
  3334. *
  3335. * @return
  3336. * An associative array of action descriptions. The keys of the array
  3337. * are the names of the action functions, and each corresponding value
  3338. * is an associative array with the following key-value pairs:
  3339. * - 'type': The type of object this action acts upon. Core actions have types
  3340. * 'node', 'user', 'comment', and 'system'.
  3341. * - 'label': The human-readable name of the action, which should be passed
  3342. * through the t() function for translation.
  3343. * - 'configurable': If FALSE, then the action doesn't require any extra
  3344. * configuration. If TRUE, then your module must define a form function with
  3345. * the same name as the action function with '_form' appended (e.g., the
  3346. * form for 'node_assign_owner_action' is 'node_assign_owner_action_form'.)
  3347. * This function takes $context as its only parameter, and is paired with
  3348. * the usual _submit function, and possibly a _validate function.
  3349. * - 'triggers': An array of the events (that is, hooks) that can trigger this
  3350. * action. For example: array('node_insert', 'user_update'). You can also
  3351. * declare support for any trigger by returning array('any') for this value.
  3352. * - 'behavior': (optional) A machine-readable array of behaviors of this
  3353. * action, used to signal additionally required actions that may need to be
  3354. * triggered. Modules that are processing actions should take special care
  3355. * for the "presave" hook, in which case a dependent "save" action should
  3356. * NOT be invoked.
  3357. *
  3358. * @ingroup actions
  3359. */
  3360. function hook_action_info() {
  3361. return array(
  3362. 'comment_unpublish_action' => array(
  3363. 'type' => 'comment',
  3364. 'label' => t('Unpublish comment'),
  3365. 'configurable' => FALSE,
  3366. 'behavior' => array('changes_property'),
  3367. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  3368. ),
  3369. 'comment_unpublish_by_keyword_action' => array(
  3370. 'type' => 'comment',
  3371. 'label' => t('Unpublish comment containing keyword(s)'),
  3372. 'configurable' => TRUE,
  3373. 'behavior' => array('changes_property'),
  3374. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  3375. ),
  3376. 'comment_save_action' => array(
  3377. 'type' => 'comment',
  3378. 'label' => t('Save comment'),
  3379. 'configurable' => FALSE,
  3380. 'triggers' => array('comment_insert', 'comment_update'),
  3381. ),
  3382. );
  3383. }
  3384. /**
  3385. * Executes code after an action is deleted.
  3386. *
  3387. * @param $aid
  3388. * The action ID.
  3389. */
  3390. function hook_actions_delete($aid) {
  3391. db_delete('actions_assignments')
  3392. ->condition('aid', $aid)
  3393. ->execute();
  3394. }
  3395. /**
  3396. * Alters the actions declared by another module.
  3397. *
  3398. * Called by actions_list() to allow modules to alter the return values from
  3399. * implementations of hook_action_info().
  3400. */
  3401. function hook_action_info_alter(&$actions) {
  3402. $actions['node_unpublish_action']['label'] = t('Unpublish and remove from public view.');
  3403. }
  3404. /**
  3405. * Declare archivers to the system.
  3406. *
  3407. * An archiver is a class that is able to package and unpackage one or more files
  3408. * into a single possibly compressed file. Common examples of such files are
  3409. * zip files and tar.gz files. All archiver classes must implement
  3410. * ArchiverInterface.
  3411. *
  3412. * Each entry should be keyed on a unique value, and specify three
  3413. * additional keys:
  3414. * - class: The name of the PHP class for this archiver.
  3415. * - extensions: An array of file extensions that this archiver supports.
  3416. * - weight: This optional key specifies the weight of this archiver.
  3417. * When mapping file extensions to archivers, the first archiver by
  3418. * weight found that supports the requested extension will be used.
  3419. *
  3420. * @see hook_archiver_info_alter()
  3421. */
  3422. function hook_archiver_info() {
  3423. return array(
  3424. 'tar' => array(
  3425. 'class' => 'Drupal\Component\Archiver\Tar',
  3426. 'extensions' => array('tar', 'tar.gz', 'tar.bz2'),
  3427. ),
  3428. );
  3429. }
  3430. /**
  3431. * Alter archiver information declared by other modules.
  3432. *
  3433. * See hook_archiver_info() for a description of archivers and the archiver
  3434. * information structure.
  3435. *
  3436. * @param $info
  3437. * Archiver information to alter (return values from hook_archiver_info()).
  3438. */
  3439. function hook_archiver_info_alter(&$info) {
  3440. $info['tar']['extensions'][] = 'tgz';
  3441. }
  3442. /**
  3443. * Define additional date types.
  3444. *
  3445. * Next to the 'long', 'medium' and 'short' date types defined in core, any
  3446. * module can define additional types that can be used when displaying dates,
  3447. * by implementing this hook. A date type is basically just a name for a date
  3448. * format.
  3449. *
  3450. * Date types are used in the administration interface: a user can assign
  3451. * date format types defined in hook_date_formats() to date types defined in
  3452. * this hook. Once a format has been assigned by a user, the machine name of a
  3453. * type can be used in the format_date() function to format a date using the
  3454. * chosen formatting.
  3455. *
  3456. * To define a date type in a module and make sure a format has been assigned to
  3457. * it, without requiring a user to visit the administrative interface, use
  3458. * @code variable_set('date_format_' . $type, $format); @endcode
  3459. * where $type is the machine-readable name defined here, and $format is a PHP
  3460. * date format string.
  3461. *
  3462. * To avoid namespace collisions with date types defined by other modules, it is
  3463. * recommended that each date type starts with the module name. A date type
  3464. * can consist of letters, numbers and underscores.
  3465. *
  3466. * @return
  3467. * An array of date types where the keys are the machine-readable names and
  3468. * the values are the human-readable labels.
  3469. *
  3470. * @see hook_date_formats()
  3471. * @see format_date()
  3472. */
  3473. function hook_date_format_types() {
  3474. // Define the core date format types.
  3475. return array(
  3476. 'long' => t('Long'),
  3477. 'medium' => t('Medium'),
  3478. 'short' => t('Short'),
  3479. );
  3480. }
  3481. /**
  3482. * Modify existing date types.
  3483. *
  3484. * Allows other modules to modify existing date types like 'long'. Called by
  3485. * _system_date_format_types_build(). For instance, A module may use this hook
  3486. * to apply settings across all date types, such as locking all date types so
  3487. * they appear to be provided by the system.
  3488. *
  3489. * @param $types
  3490. * A list of date types. Each date type is keyed by the machine-readable name
  3491. * and the values are associative arrays containing:
  3492. * - is_new: Set to FALSE to override previous settings.
  3493. * - module: The name of the module that created the date type.
  3494. * - type: The machine-readable date type name.
  3495. * - title: The human-readable date type name.
  3496. * - locked: Specifies that the date type is system-provided.
  3497. */
  3498. function hook_date_format_types_alter(&$types) {
  3499. foreach ($types as $name => $type) {
  3500. $types[$name]['locked'] = 1;
  3501. }
  3502. }
  3503. /**
  3504. * Define additional date formats.
  3505. *
  3506. * This hook is used to define the PHP date format strings that can be assigned
  3507. * to date types in the administrative interface. A module can provide date
  3508. * format strings for the core-provided date types ('long', 'medium', and
  3509. * 'short'), or for date types defined in hook_date_format_types() by itself
  3510. * or another module.
  3511. *
  3512. * Since date formats can be locale-specific, you can specify the locales that
  3513. * each date format string applies to. There may be more than one locale for a
  3514. * format. There may also be more than one format for the same locale. For
  3515. * example d/m/Y and Y/m/d work equally well in some locales. You may wish to
  3516. * define some additional date formats that aren't specific to any one locale,
  3517. * for example, "Y m". For these cases, the 'locales' component of the return
  3518. * value should be omitted.
  3519. *
  3520. * Providing a date format here does not normally assign the format to be
  3521. * used with the associated date type -- a user has to choose a format for each
  3522. * date type in the administrative interface. There is one exception: locale
  3523. * initialization chooses a locale-specific format for the three core-provided
  3524. * types (see locale_get_localized_date_format() for details). If your module
  3525. * needs to ensure that a date type it defines has a format associated with it,
  3526. * call @code variable_set('date_format_' . $type, $format); @endcode
  3527. * where $type is the machine-readable name defined in hook_date_format_types(),
  3528. * and $format is a PHP date format string.
  3529. *
  3530. * @return
  3531. * A list of date formats to offer as choices in the administrative
  3532. * interface. Each date format is a keyed array consisting of three elements:
  3533. * - 'type': The date type name that this format can be used with, as
  3534. * declared in an implementation of hook_date_format_types().
  3535. * - 'format': A PHP date format string to use when formatting dates. It
  3536. * can contain any of the formatting options described at
  3537. * http://php.net/manual/function.date.php
  3538. * - 'locales': (optional) An array of 2 and 5 character locale codes,
  3539. * defining which locales this format applies to (for example, 'en',
  3540. * 'en-us', etc.). If your date format is not language-specific, leave this
  3541. * array empty.
  3542. *
  3543. * @see hook_date_format_types()
  3544. */
  3545. function hook_date_formats() {
  3546. return array(
  3547. array(
  3548. 'type' => 'mymodule_extra_long',
  3549. 'format' => 'l jS F Y H:i:s e',
  3550. 'locales' => array('en-ie'),
  3551. ),
  3552. array(
  3553. 'type' => 'mymodule_extra_long',
  3554. 'format' => 'l jS F Y h:i:sa',
  3555. 'locales' => array('en', 'en-us'),
  3556. ),
  3557. array(
  3558. 'type' => 'short',
  3559. 'format' => 'F Y',
  3560. 'locales' => array(),
  3561. ),
  3562. );
  3563. }
  3564. /**
  3565. * Alter date formats declared by another module.
  3566. *
  3567. * Called by _system_date_format_types_build() to allow modules to alter the
  3568. * return values from implementations of hook_date_formats().
  3569. */
  3570. function hook_date_formats_alter(&$formats) {
  3571. foreach ($formats as $id => $format) {
  3572. $formats[$id]['locales'][] = 'en-ca';
  3573. }
  3574. }
  3575. /**
  3576. * Alters the delivery callback used to send the result of the page callback to the browser.
  3577. *
  3578. * Called by drupal_deliver_page() to allow modules to alter how the
  3579. * page is delivered to the browser.
  3580. *
  3581. * This hook is intended for altering the delivery callback based on
  3582. * information unrelated to the path of the page accessed. For example,
  3583. * it can be used to set the delivery callback based on a HTTP request
  3584. * header (as shown in the code sample). To specify a delivery callback
  3585. * based on path information, use hook_menu() or hook_menu_alter().
  3586. *
  3587. * This hook can also be used as an API function that can be used to explicitly
  3588. * set the delivery callback from some other function. For example, for a module
  3589. * named MODULE:
  3590. * @code
  3591. * function MODULE_page_delivery_callback_alter(&$callback, $set = FALSE) {
  3592. * static $stored_callback;
  3593. * if ($set) {
  3594. * $stored_callback = $callback;
  3595. * }
  3596. * elseif (isset($stored_callback)) {
  3597. * $callback = $stored_callback;
  3598. * }
  3599. * }
  3600. * function SOMEWHERE_ELSE() {
  3601. * $desired_delivery_callback = 'foo';
  3602. * MODULE_page_delivery_callback_alter($desired_delivery_callback, TRUE);
  3603. * }
  3604. * @endcode
  3605. *
  3606. * @param $callback
  3607. * The name of a function.
  3608. *
  3609. * @see drupal_deliver_page()
  3610. */
  3611. function hook_page_delivery_callback_alter(&$callback) {
  3612. // jQuery sets a HTTP_X_REQUESTED_WITH header of 'XMLHttpRequest'.
  3613. // If a page would normally be delivered as an html page, and it is called
  3614. // from jQuery, deliver it instead as an Ajax response.
  3615. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && $callback == 'drupal_deliver_html_page') {
  3616. $callback = 'ajax_deliver';
  3617. }
  3618. }
  3619. /**
  3620. * Alters theme operation links.
  3621. *
  3622. * @param $theme_groups
  3623. * An associative array containing groups of themes.
  3624. *
  3625. * @see system_themes_page()
  3626. */
  3627. function hook_system_themes_page_alter(&$theme_groups) {
  3628. foreach ($theme_groups as $state => &$group) {
  3629. foreach ($theme_groups[$state] as &$theme) {
  3630. // Add a foo link to each list of theme operations.
  3631. $theme->operations[] = array(
  3632. 'title' => t('Foo'),
  3633. 'href' => 'admin/appearance/foo',
  3634. 'query' => array('theme' => $theme->name)
  3635. );
  3636. }
  3637. }
  3638. }
  3639. /**
  3640. * Alters inbound URL requests.
  3641. *
  3642. * @param $path
  3643. * The path being constructed, which, if a path alias, has been resolved to a
  3644. * Drupal path by the database, and which also may have been altered by other
  3645. * modules before this one.
  3646. * @param $original_path
  3647. * The original path, before being checked for path aliases or altered by any
  3648. * modules.
  3649. * @param $path_language
  3650. * The language of the path.
  3651. *
  3652. * @see drupal_get_normal_path()
  3653. */
  3654. function hook_url_inbound_alter(&$path, $original_path, $path_language) {
  3655. // Create the path user/me/edit, which allows a user to edit their account.
  3656. if (preg_match('|^user/me/edit(/.*)?|', $path, $matches)) {
  3657. global $user;
  3658. $path = 'user/' . $user->uid . '/edit' . $matches[1];
  3659. }
  3660. }
  3661. /**
  3662. * Alters outbound URLs.
  3663. *
  3664. * @param $path
  3665. * The outbound path to alter, not adjusted for path aliases yet. It won't be
  3666. * adjusted for path aliases until all modules are finished altering it, thus
  3667. * being consistent with hook_url_inbound_alter(), which adjusts for all path
  3668. * aliases before allowing modules to alter it. This may have been altered by
  3669. * other modules before this one.
  3670. * @param $options
  3671. * A set of URL options for the URL so elements such as a fragment or a query
  3672. * string can be added to the URL.
  3673. * @param $original_path
  3674. * The original path, before being altered by any modules.
  3675. *
  3676. * @see url()
  3677. */
  3678. function hook_url_outbound_alter(&$path, &$options, $original_path) {
  3679. // Use an external RSS feed rather than the Drupal one.
  3680. if ($path == 'rss.xml') {
  3681. $path = 'http://example.com/rss.xml';
  3682. $options['external'] = TRUE;
  3683. }
  3684. // Instead of pointing to user/[uid]/edit, point to user/me/edit.
  3685. if (preg_match('|^user/([0-9]*)/edit(/.*)?|', $path, $matches)) {
  3686. global $user;
  3687. if ($user->uid == $matches[1]) {
  3688. $path = 'user/me/edit' . $matches[2];
  3689. }
  3690. }
  3691. }
  3692. /**
  3693. * Provide replacement values for placeholder tokens.
  3694. *
  3695. * This hook is invoked when someone calls token_replace(). That function first
  3696. * scans the text for [type:token] patterns, and splits the needed tokens into
  3697. * groups by type. Then hook_tokens() is invoked on each token-type group,
  3698. * allowing your module to respond by providing replacement text for any of
  3699. * the tokens in the group that your module knows how to process.
  3700. *
  3701. * A module implementing this hook should also implement hook_token_info() in
  3702. * order to list its available tokens on editing screens.
  3703. *
  3704. * @param $type
  3705. * The machine-readable name of the type (group) of token being replaced, such
  3706. * as 'node', 'user', or another type defined by a hook_token_info()
  3707. * implementation.
  3708. * @param $tokens
  3709. * An array of tokens to be replaced. The keys are the machine-readable token
  3710. * names, and the values are the raw [type:token] strings that appeared in the
  3711. * original text.
  3712. * @param $data
  3713. * (optional) An associative array of data objects to be used when generating
  3714. * replacement values, as supplied in the $data parameter to token_replace().
  3715. * @param $options
  3716. * (optional) An associative array of options for token replacement; see
  3717. * token_replace() for possible values.
  3718. *
  3719. * @return
  3720. * An associative array of replacement values, keyed by the raw [type:token]
  3721. * strings from the original text.
  3722. *
  3723. * @see hook_token_info()
  3724. * @see hook_tokens_alter()
  3725. */
  3726. function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
  3727. $url_options = array('absolute' => TRUE);
  3728. if (isset($options['language'])) {
  3729. $url_options['language'] = $options['language'];
  3730. $language_code = $options['language']->langcode;
  3731. }
  3732. else {
  3733. $language_code = NULL;
  3734. }
  3735. $sanitize = !empty($options['sanitize']);
  3736. $replacements = array();
  3737. if ($type == 'node' && !empty($data['node'])) {
  3738. $node = $data['node'];
  3739. foreach ($tokens as $name => $original) {
  3740. switch ($name) {
  3741. // Simple key values on the node.
  3742. case 'nid':
  3743. $replacements[$original] = $node->nid;
  3744. break;
  3745. case 'title':
  3746. $replacements[$original] = $sanitize ? check_plain($node->title) : $node->title;
  3747. break;
  3748. case 'edit-url':
  3749. $replacements[$original] = url('node/' . $node->nid . '/edit', $url_options);
  3750. break;
  3751. // Default values for the chained tokens handled below.
  3752. case 'author':
  3753. $name = ($node->uid == 0) ? variable_get('anonymous', t('Anonymous')) : $node->name;
  3754. $replacements[$original] = $sanitize ? filter_xss($name) : $name;
  3755. break;
  3756. case 'created':
  3757. $replacements[$original] = format_date($node->created, 'medium', '', NULL, $language_code);
  3758. break;
  3759. }
  3760. }
  3761. if ($author_tokens = token_find_with_prefix($tokens, 'author')) {
  3762. $author = user_load($node->uid);
  3763. $replacements += token_generate('user', $author_tokens, array('user' => $author), $options);
  3764. }
  3765. if ($created_tokens = token_find_with_prefix($tokens, 'created')) {
  3766. $replacements += token_generate('date', $created_tokens, array('date' => $node->created), $options);
  3767. }
  3768. }
  3769. return $replacements;
  3770. }
  3771. /**
  3772. * Alter replacement values for placeholder tokens.
  3773. *
  3774. * @param $replacements
  3775. * An associative array of replacements returned by hook_tokens().
  3776. * @param $context
  3777. * The context in which hook_tokens() was called. An associative array with
  3778. * the following keys, which have the same meaning as the corresponding
  3779. * parameters of hook_tokens():
  3780. * - 'type'
  3781. * - 'tokens'
  3782. * - 'data'
  3783. * - 'options'
  3784. *
  3785. * @see hook_tokens()
  3786. */
  3787. function hook_tokens_alter(array &$replacements, array $context) {
  3788. $options = $context['options'];
  3789. if (isset($options['language'])) {
  3790. $url_options['language'] = $options['language'];
  3791. $language_code = $options['language']->langcode;
  3792. }
  3793. else {
  3794. $language_code = NULL;
  3795. }
  3796. $sanitize = !empty($options['sanitize']);
  3797. if ($context['type'] == 'node' && !empty($context['data']['node'])) {
  3798. $node = $context['data']['node'];
  3799. // Alter the [node:title] token, and replace it with the rendered content
  3800. // of a field (field_title).
  3801. if (isset($context['tokens']['title'])) {
  3802. $title = field_view_field('node', $node, 'field_title', 'default', $language_code);
  3803. $replacements[$context['tokens']['title']] = drupal_render($title);
  3804. }
  3805. }
  3806. }
  3807. /**
  3808. * Provide information about available placeholder tokens and token types.
  3809. *
  3810. * Tokens are placeholders that can be put into text by using the syntax
  3811. * [type:token], where type is the machine-readable name of a token type, and
  3812. * token is the machine-readable name of a token within this group. This hook
  3813. * provides a list of types and tokens to be displayed on text editing screens,
  3814. * so that people editing text can see what their token options are.
  3815. *
  3816. * The actual token replacement is done by token_replace(), which invokes
  3817. * hook_tokens(). Your module will need to implement that hook in order to
  3818. * generate token replacements from the tokens defined here.
  3819. *
  3820. * @return
  3821. * An associative array of available tokens and token types. The outer array
  3822. * has two components:
  3823. * - types: An associative array of token types (groups). Each token type is
  3824. * an associative array with the following components:
  3825. * - name: The translated human-readable short name of the token type.
  3826. * - description: A translated longer description of the token type.
  3827. * - needs-data: The type of data that must be provided to token_replace()
  3828. * in the $data argument (i.e., the key name in $data) in order for tokens
  3829. * of this type to be used in the $text being processed. For instance, if
  3830. * the token needs a node object, 'needs-data' should be 'node', and to
  3831. * use this token in token_replace(), the caller needs to supply a node
  3832. * object as $data['node']. Some token data can also be supplied
  3833. * indirectly; for instance, a node object in $data supplies a user object
  3834. * (the author of the node), allowing user tokens to be used when only
  3835. * a node data object is supplied.
  3836. * - tokens: An associative array of tokens. The outer array is keyed by the
  3837. * group name (the same key as in the types array). Within each group of
  3838. * tokens, each token item is keyed by the machine name of the token, and
  3839. * each token item has the following components:
  3840. * - name: The translated human-readable short name of the token.
  3841. * - description: A translated longer description of the token.
  3842. * - type (optional): A 'needs-data' data type supplied by this token, which
  3843. * should match a 'needs-data' value from another token type. For example,
  3844. * the node author token provides a user object, which can then be used
  3845. * for token replacement data in token_replace() without having to supply
  3846. * a separate user object.
  3847. *
  3848. * @see hook_token_info_alter()
  3849. * @see hook_tokens()
  3850. */
  3851. function hook_token_info() {
  3852. $type = array(
  3853. 'name' => t('Nodes'),
  3854. 'description' => t('Tokens related to individual nodes.'),
  3855. 'needs-data' => 'node',
  3856. );
  3857. // Core tokens for nodes.
  3858. $node['nid'] = array(
  3859. 'name' => t("Node ID"),
  3860. 'description' => t("The unique ID of the node."),
  3861. );
  3862. $node['title'] = array(
  3863. 'name' => t("Title"),
  3864. 'description' => t("The title of the node."),
  3865. );
  3866. $node['edit-url'] = array(
  3867. 'name' => t("Edit URL"),
  3868. 'description' => t("The URL of the node's edit page."),
  3869. );
  3870. // Chained tokens for nodes.
  3871. $node['created'] = array(
  3872. 'name' => t("Date created"),
  3873. 'description' => t("The date the node was posted."),
  3874. 'type' => 'date',
  3875. );
  3876. $node['author'] = array(
  3877. 'name' => t("Author"),
  3878. 'description' => t("The author of the node."),
  3879. 'type' => 'user',
  3880. );
  3881. return array(
  3882. 'types' => array('node' => $type),
  3883. 'tokens' => array('node' => $node),
  3884. );
  3885. }
  3886. /**
  3887. * Alter the metadata about available placeholder tokens and token types.
  3888. *
  3889. * @param $data
  3890. * The associative array of token definitions from hook_token_info().
  3891. *
  3892. * @see hook_token_info()
  3893. */
  3894. function hook_token_info_alter(&$data) {
  3895. // Modify description of node tokens for our site.
  3896. $data['tokens']['node']['nid'] = array(
  3897. 'name' => t("Node ID"),
  3898. 'description' => t("The unique ID of the article."),
  3899. );
  3900. $data['tokens']['node']['title'] = array(
  3901. 'name' => t("Title"),
  3902. 'description' => t("The title of the article."),
  3903. );
  3904. // Chained tokens for nodes.
  3905. $data['tokens']['node']['created'] = array(
  3906. 'name' => t("Date created"),
  3907. 'description' => t("The date the article was posted."),
  3908. 'type' => 'date',
  3909. );
  3910. }
  3911. /**
  3912. * Alter batch information before a batch is processed.
  3913. *
  3914. * Called by batch_process() to allow modules to alter a batch before it is
  3915. * processed.
  3916. *
  3917. * @param $batch
  3918. * The associative array of batch information. See batch_set() for details on
  3919. * what this could contain.
  3920. *
  3921. * @see batch_set()
  3922. * @see batch_process()
  3923. *
  3924. * @ingroup batch
  3925. */
  3926. function hook_batch_alter(&$batch) {
  3927. // If the current page request is inside the overlay, add ?render=overlay to
  3928. // the success callback URL, so that it appears correctly within the overlay.
  3929. if (overlay_get_mode() == 'child') {
  3930. if (isset($batch['url_options']['query'])) {
  3931. $batch['url_options']['query']['render'] = 'overlay';
  3932. }
  3933. else {
  3934. $batch['url_options']['query'] = array('render' => 'overlay');
  3935. }
  3936. }
  3937. }
  3938. /**
  3939. * Provide information on Updaters (classes that can update Drupal).
  3940. *
  3941. * Drupal\Core\Updater\Updater is a class that knows how to update various parts
  3942. * of the Drupal file system, for example to update modules that have newer
  3943. * releases, or to install a new theme.
  3944. *
  3945. * @return
  3946. * An associative array of information about the updater(s) being provided.
  3947. * This array is keyed by a unique identifier for each updater, and the
  3948. * values are subarrays that can contain the following keys:
  3949. * - class: The name of the PHP class which implements this updater.
  3950. * - name: Human-readable name of this updater.
  3951. * - weight: Controls what order the Updater classes are consulted to decide
  3952. * which one should handle a given task. When an update task is being run,
  3953. * the system will loop through all the Updater classes defined in this
  3954. * registry in weight order and let each class respond to the task and
  3955. * decide if each Updater wants to handle the task. In general, this
  3956. * doesn't matter, but if you need to override an existing Updater, make
  3957. * sure your Updater has a lighter weight so that it comes first.
  3958. *
  3959. * @see drupal_get_updaters()
  3960. * @see hook_updater_info_alter()
  3961. */
  3962. function hook_updater_info() {
  3963. return array(
  3964. 'module' => array(
  3965. 'class' => 'Drupal\Core\Updater\Module',
  3966. 'name' => t('Update modules'),
  3967. 'weight' => 0,
  3968. ),
  3969. 'theme' => array(
  3970. 'class' => 'Drupal\Core\Updater\Theme',
  3971. 'name' => t('Update themes'),
  3972. 'weight' => 0,
  3973. ),
  3974. );
  3975. }
  3976. /**
  3977. * Alter the Updater information array.
  3978. *
  3979. * An Updater is a class that knows how to update various parts of the Drupal
  3980. * file system, for example to update modules that have newer releases, or to
  3981. * install a new theme.
  3982. *
  3983. * @param array $updaters
  3984. * Associative array of updaters as defined through hook_updater_info().
  3985. * Alter this array directly.
  3986. *
  3987. * @see drupal_get_updaters()
  3988. * @see hook_updater_info()
  3989. */
  3990. function hook_updater_info_alter(&$updaters) {
  3991. // Adjust weight so that the theme Updater gets a chance to handle a given
  3992. // update task before module updaters.
  3993. $updaters['theme']['weight'] = -1;
  3994. }
  3995. /**
  3996. * Alter the default country list.
  3997. *
  3998. * @param $countries
  3999. * The associative array of countries keyed by ISO 3166-1 country code.
  4000. *
  4001. * @see country_get_list()
  4002. * @see standard_country_list()
  4003. */
  4004. function hook_countries_alter(&$countries) {
  4005. // Elbonia is now independent, so add it to the country list.
  4006. $countries['EB'] = 'Elbonia';
  4007. }
  4008. /**
  4009. * Control site status before menu dispatching.
  4010. *
  4011. * The hook is called after checking whether the site is offline but before
  4012. * the current router item is retrieved and executed by
  4013. * menu_execute_active_handler(). If the site is in offline mode,
  4014. * $menu_site_status is set to MENU_SITE_OFFLINE.
  4015. *
  4016. * @param $menu_site_status
  4017. * Supported values are MENU_SITE_OFFLINE, MENU_ACCESS_DENIED,
  4018. * MENU_NOT_FOUND and MENU_SITE_ONLINE. Any other value than
  4019. * MENU_SITE_ONLINE will skip the default menu handling system and be passed
  4020. * for delivery to drupal_deliver_page() with a NULL
  4021. * $default_delivery_callback.
  4022. * @param $path
  4023. * Contains the system path that is going to be loaded. This is read only,
  4024. * use hook_url_inbound_alter() to change the path.
  4025. */
  4026. function hook_menu_site_status_alter(&$menu_site_status, $path) {
  4027. // Allow access to my_module/authentication even if site is in offline mode.
  4028. if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'my_module/authentication') {
  4029. $menu_site_status = MENU_SITE_ONLINE;
  4030. }
  4031. }
  4032. /**
  4033. * Register information about FileTransfer classes provided by a module.
  4034. *
  4035. * The FileTransfer class allows transferring files over a specific type of
  4036. * connection. Core provides classes for FTP and SSH. Contributed modules are
  4037. * free to extend the FileTransfer base class to add other connection types,
  4038. * and if these classes are registered via hook_filetransfer_info(), those
  4039. * connection types will be available to site administrators using the Update
  4040. * manager when they are redirected to the authorize.php script to authorize
  4041. * the file operations.
  4042. *
  4043. * @return array
  4044. * Nested array of information about FileTransfer classes. Each key is a
  4045. * FileTransfer type (not human readable, used for form elements and
  4046. * variable names, etc), and the values are subarrays that define properties
  4047. * of that type. The keys in each subarray are:
  4048. * - 'title': Required. The human-readable name of the connection type.
  4049. * - 'class': Required. The name of the FileTransfer class. The constructor
  4050. * will always be passed the full path to the root of the site that should
  4051. * be used to restrict where file transfer operations can occur (the $jail)
  4052. * and an array of settings values returned by the settings form.
  4053. * - 'file': Required. The include file containing the FileTransfer class.
  4054. * This should be a separate .inc file, not just the .module file, so that
  4055. * the minimum possible code is loaded when authorize.php is running.
  4056. * - 'file path': Optional. The directory (relative to the Drupal root)
  4057. * where the include file lives. If not defined, defaults to the base
  4058. * directory of the module implementing the hook.
  4059. * - 'weight': Optional. Integer weight used for sorting connection types on
  4060. * the authorize.php form.
  4061. *
  4062. * @see Drupal\Core\FileTransfer\FileTransfer
  4063. * @see authorize.php
  4064. * @see hook_filetransfer_info_alter()
  4065. * @see drupal_get_filetransfer_info()
  4066. */
  4067. function hook_filetransfer_info() {
  4068. $info['sftp'] = array(
  4069. 'title' => t('SFTP (Secure FTP)'),
  4070. 'class' => 'Drupal\Core\FileTransfer\SFTP',
  4071. 'weight' => 10,
  4072. );
  4073. return $info;
  4074. }
  4075. /**
  4076. * Alter the FileTransfer class registry.
  4077. *
  4078. * @param array $filetransfer_info
  4079. * Reference to a nested array containing information about the FileTransfer
  4080. * class registry.
  4081. *
  4082. * @see hook_filetransfer_info()
  4083. */
  4084. function hook_filetransfer_info_alter(&$filetransfer_info) {
  4085. if (variable_get('paranoia', FALSE)) {
  4086. // Remove the FTP option entirely.
  4087. unset($filetransfer_info['ftp']);
  4088. // Make sure the SSH option is listed first.
  4089. $filetransfer_info['ssh']['weight'] = -10;
  4090. }
  4091. }
  4092. /**
  4093. * @} End of "addtogroup hooks".
  4094. */
Login or register to post comments