Skip navigation
Help

system.api.php

  1. drupal
    1. 7 drupal/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. See also, hook_init.
hook_countries_alterAlter the default country list.
hook_cronPerform periodic actions.
hook_cron_queue_infoDeclare queues holding items that need to be run periodically.
hook_cron_queue_info_alterAlter cron queue information before cron runs.
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_entity_deleteAct on entities when deleted.
hook_entity_infoInform the base system and the Field API about one or more entity types.
hook_entity_info_alterAlter the entity info.
hook_entity_insertAct on entities when inserted.
hook_entity_loadAct on entities when loaded.
hook_entity_prepare_viewAct on entities as they are being prepared for view.
hook_entity_presaveAct on an entity before it is about to be created or updated.
hook_entity_query_alterAlter or execute an EntityFieldQuery.
hook_entity_updateAct on entities when updated.
hook_entity_viewAct on entities being assembled before rendering.
hook_entity_view_alterAlter the results of ENTITY_view().
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 a file being deleted.
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_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_flush_cachesAdd a list of cache tables to be cleared.
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 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. See also, hook_boot.
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_libraryRegisters JavaScript/CSS libraries associated with a module.
hook_library_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_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_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_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_username_alterAlter the username that is displayed for a user.
hook_watchdogLog an event message
hook_xmlrpcRegister XML-RPC callbacks.
hook_xmlrpc_alterAlters the definition of XML-RPC methods before they are called.

File

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