PageRenderTime 156ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/system/system.api.php

https://bitbucket.org/geolivero/qbc
PHP | 4609 lines | 1366 code | 180 blank | 3063 comment | 123 complexity | 8de916a326175b512b7a937415b4f923 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  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. That is 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. Note that wildcards may not
  959. * be used as the first component.
  960. *
  961. * Registered paths may also contain special "auto-loader" wildcard components
  962. * in the form of '%mymodule_abc', where the '%' part means that this path
  963. * component is a wildcard, and the 'mymodule_abc' part defines the prefix for a
  964. * load function, which here would be named mymodule_abc_load(). When a matching
  965. * path is requested, your load function will receive as its first argument the
  966. * path component in the position of the wildcard; load functions may also be
  967. * passed additional arguments (see "load arguments" in the return value
  968. * section below). For example, your module could register path
  969. * 'my-module/%mymodule_abc/edit':
  970. * @code
  971. * $items['my-module/%mymodule_abc/edit'] = array(
  972. * 'page callback' => 'mymodule_abc_edit',
  973. * 'page arguments' => array(1),
  974. * );
  975. * @endcode
  976. * When path 'my-module/123/edit' is requested, your load function
  977. * mymodule_abc_load() will be invoked with the argument '123', and should
  978. * load and return an "abc" object with internal id 123:
  979. * @code
  980. * function mymodule_abc_load($abc_id) {
  981. * return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  982. * }
  983. * @endcode
  984. * This 'abc' object will then be passed into the callback functions defined
  985. * for the menu item, such as the page callback function mymodule_abc_edit()
  986. * to replace the integer 1 in the argument array. Note that a load function
  987. * should return FALSE when it is unable to provide a loadable object. For
  988. * example, the node_load() function for the 'node/%node/edit' menu item will
  989. * return FALSE for the path 'node/999/edit' if a node with a node ID of 999
  990. * does not exist. The menu routing system will return a 404 error in this case.
  991. *
  992. * You can also define a %wildcard_to_arg() function (for the example menu
  993. * entry above this would be 'mymodule_abc_to_arg()'). The _to_arg() function
  994. * is invoked to retrieve a value that is used in the path in place of the
  995. * wildcard. A good example is user.module, which defines
  996. * user_uid_optional_to_arg() (corresponding to the menu entry
  997. * 'user/%user_uid_optional'). This function returns the user ID of the
  998. * current user.
  999. *
  1000. * The _to_arg() function will get called with three arguments:
  1001. * - $arg: A string representing whatever argument may have been supplied by
  1002. * the caller (this is particularly useful if you want the _to_arg()
  1003. * function only supply a (default) value if no other value is specified,
  1004. * as in the case of user_uid_optional_to_arg().
  1005. * - $map: An array of all path fragments (e.g. array('node','123','edit') for
  1006. * 'node/123/edit').
  1007. * - $index: An integer indicating which element of $map corresponds to $arg.
  1008. *
  1009. * _load() and _to_arg() functions may seem similar at first glance, but they
  1010. * have different purposes and are called at different times. _load()
  1011. * functions are called when the menu system is collecting arguments to pass
  1012. * to the callback functions defined for the menu item. _to_arg() functions
  1013. * are called when the menu system is generating links to related paths, such
  1014. * as the tabs for a set of MENU_LOCAL_TASK items.
  1015. *
  1016. * You can also make groups of menu items to be rendered (by default) as tabs
  1017. * on a page. To do that, first create one menu item of type MENU_NORMAL_ITEM,
  1018. * with your chosen path, such as 'foo'. Then duplicate that menu item, using a
  1019. * subdirectory path, such as 'foo/tab1', and changing the type to
  1020. * MENU_DEFAULT_LOCAL_TASK to make it the default tab for the group. Then add
  1021. * the additional tab items, with paths such as "foo/tab2" etc., with type
  1022. * MENU_LOCAL_TASK. Example:
  1023. * @code
  1024. * // Make "Foo settings" appear on the admin Config page
  1025. * $items['admin/config/system/foo'] = array(
  1026. * 'title' => 'Foo settings',
  1027. * 'type' => MENU_NORMAL_ITEM,
  1028. * // Page callback, etc. need to be added here.
  1029. * );
  1030. * // Make "Tab 1" the main tab on the "Foo settings" page
  1031. * $items['admin/config/system/foo/tab1'] = array(
  1032. * 'title' => 'Tab 1',
  1033. * 'type' => MENU_DEFAULT_LOCAL_TASK,
  1034. * // Access callback, page callback, and theme callback will be inherited
  1035. * // from 'admin/config/system/foo', if not specified here to override.
  1036. * );
  1037. * // Make an additional tab called "Tab 2" on "Foo settings"
  1038. * $items['admin/config/system/foo/tab2'] = array(
  1039. * 'title' => 'Tab 2',
  1040. * 'type' => MENU_LOCAL_TASK,
  1041. * // Page callback and theme callback will be inherited from
  1042. * // 'admin/config/system/foo', if not specified here to override.
  1043. * // Need to add access callback or access arguments.
  1044. * );
  1045. * @endcode
  1046. *
  1047. * @return
  1048. * An array of menu items. Each menu item has a key corresponding to the
  1049. * Drupal path being registered. The corresponding array value is an
  1050. * associative array that may contain the following key-value pairs:
  1051. * - "title": Required. The untranslated title of the menu item.
  1052. * - "title callback": Function to generate the title; defaults to t().
  1053. * If you require only the raw string to be output, set this to FALSE.
  1054. * - "title arguments": Arguments to send to t() or your custom callback,
  1055. * with path component substitution as described above.
  1056. * - "description": The untranslated description of the menu item.
  1057. * - "page callback": The function to call to display a web page when the user
  1058. * visits the path. If omitted, the parent menu item's callback will be used
  1059. * instead.
  1060. * - "page arguments": An array of arguments to pass to the page callback
  1061. * function, with path component substitution as described above.
  1062. * - "delivery callback": The function to call to package the result of the
  1063. * page callback function and send it to the browser. Defaults to
  1064. * drupal_deliver_html_page() unless a value is inherited from a parent menu
  1065. * item. Note that this function is called even if the access checks fail,
  1066. * so any custom delivery callback function should take that into account.
  1067. * See drupal_deliver_html_page() for an example.
  1068. * - "access callback": A function returning TRUE if the user has access
  1069. * rights to this menu item, and FALSE if not. It can also be a boolean
  1070. * constant instead of a function, and you can also use numeric values
  1071. * (will be cast to boolean). Defaults to user_access() unless a value is
  1072. * inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items
  1073. * can inherit access callbacks. To use the user_access() default callback,
  1074. * you must specify the permission to check as 'access arguments' (see
  1075. * below).
  1076. * - "access arguments": An array of arguments to pass to the access callback
  1077. * function, with path component substitution as described above. If the
  1078. * access callback is inherited (see above), the access arguments will be
  1079. * inherited with it, unless overridden in the child menu item.
  1080. * - "theme callback": (optional) A function returning the machine-readable
  1081. * name of the theme that will be used to render the page. If not provided,
  1082. * the value will be inherited from a parent menu item. If there is no
  1083. * theme callback, or if the function does not return the name of a current
  1084. * active theme on the site, the theme for this page will be determined by
  1085. * either hook_custom_theme() or the default theme instead. As a general
  1086. * rule, the use of theme callback functions should be limited to pages
  1087. * whose functionality is very closely tied to a particular theme, since
  1088. * they can only be overridden by modules which specifically target those
  1089. * pages in hook_menu_alter(). Modules implementing more generic theme
  1090. * switching functionality (for example, a module which allows the theme to
  1091. * be set dynamically based on the current user's role) should use
  1092. * hook_custom_theme() instead.
  1093. * - "theme arguments": An array of arguments to pass to the theme callback
  1094. * function, with path component substitution as described above.
  1095. * - "file": A file that will be included before the page callback is called;
  1096. * this allows page callback functions to be in separate files. The file
  1097. * should be relative to the implementing module's directory unless
  1098. * otherwise specified by the "file path" option. Does not apply to other
  1099. * callbacks (only page callback).
  1100. * - "file path": The path to the directory containing the file specified in
  1101. * "file". This defaults to the path to the module implementing the hook.
  1102. * - "load arguments": An array of arguments to be passed to each of the
  1103. * wildcard object loaders in the path, after the path argument itself.
  1104. * For example, if a module registers path node/%node/revisions/%/view
  1105. * with load arguments set to array(3), the '%node' in the path indicates
  1106. * that the loader function node_load() will be called with the second
  1107. * path component as the first argument. The 3 in the load arguments
  1108. * indicates that the fourth path component will also be passed to
  1109. * node_load() (numbering of path components starts at zero). So, if path
  1110. * node/12/revisions/29/view is requested, node_load(12, 29) will be called.
  1111. * There are also two "magic" values that can be used in load arguments.
  1112. * "%index" indicates the index of the wildcard path component. "%map"
  1113. * indicates the path components as an array. For example, if a module
  1114. * registers for several paths of the form 'user/%user_category/edit/*', all
  1115. * of them can use the same load function user_category_load(), by setting
  1116. * the load arguments to array('%map', '%index'). For instance, if the user
  1117. * is editing category 'foo' by requesting path 'user/32/edit/foo', the load
  1118. * function user_category_load() will be called with 32 as its first
  1119. * argument, the array ('user', 32, 'edit', 'foo') as the map argument,
  1120. * and 1 as the index argument (because %user_category is the second path
  1121. * component and numbering starts at zero). user_category_load() can then
  1122. * use these values to extract the information that 'foo' is the category
  1123. * being requested.
  1124. * - "weight": An integer that determines the relative position of items in
  1125. * the menu; higher-weighted items sink. Defaults to 0. Menu items with the
  1126. * same weight are ordered alphabetically.
  1127. * - "menu_name": Optional. Set this to a custom menu if you don't want your
  1128. * item to be placed in Navigation.
  1129. * - "context": (optional) Defines the context a tab may appear in. By
  1130. * default, all tabs are only displayed as local tasks when being rendered
  1131. * in a page context. All tabs that should be accessible as contextual links
  1132. * in page region containers outside of the parent menu item's primary page
  1133. * context should be registered using one of the following contexts:
  1134. * - MENU_CONTEXT_PAGE: (default) The tab is displayed as local task for the
  1135. * page context only.
  1136. * - MENU_CONTEXT_INLINE: The tab is displayed as contextual link outside of
  1137. * the primary page context only.
  1138. * Contexts can be combined. For example, to display a tab both on a page
  1139. * and inline, a menu router item may specify:
  1140. * @code
  1141. * 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  1142. * @endcode
  1143. * - "tab_parent": For local task menu items, the path of the task's parent
  1144. * item; defaults to the same path without the last component (e.g., the
  1145. * default parent for 'admin/people/create' is 'admin/people').
  1146. * - "tab_root": For local task menu items, the path of the closest non-tab
  1147. * item; same default as "tab_parent".
  1148. * - "position": Position of the block ('left' or 'right') on the system
  1149. * administration page for this item.
  1150. * - "type": A bitmask of flags describing properties of the menu item.
  1151. * Many shortcut bitmasks are provided as constants in menu.inc:
  1152. * - MENU_NORMAL_ITEM: Normal menu items show up in the menu tree and can be
  1153. * moved/hidden by the administrator.
  1154. * - MENU_CALLBACK: Callbacks simply register a path so that the correct
  1155. * information is generated when the path is accessed.
  1156. * - MENU_SUGGESTED_ITEM: Modules may "suggest" menu items that the
  1157. * administrator may enable.
  1158. * - MENU_LOCAL_ACTION: Local actions are menu items that describe actions
  1159. * on the parent item such as adding a new user or block, and are
  1160. * rendered in the action-links list in your theme.
  1161. * - MENU_LOCAL_TASK: Local tasks are menu items that describe different
  1162. * displays of data, and are generally rendered as tabs.
  1163. * - MENU_DEFAULT_LOCAL_TASK: Every set of local tasks should provide one
  1164. * "default" task, which should display the same page as the parent item.
  1165. * If the "type" element is omitted, MENU_NORMAL_ITEM is assumed.
  1166. * - "options": An array of options to be passed to l() when generating a link
  1167. * from this menu item. Note that the "options" parameter has no effect on
  1168. * MENU_LOCAL_TASK, MENU_DEFAULT_LOCAL_TASK, and MENU_LOCAL_ACTION items.
  1169. *
  1170. * For a detailed usage example, see page_example.module.
  1171. * For comprehensive documentation on the menu system, see
  1172. * http://drupal.org/node/102338.
  1173. */
  1174. function hook_menu() {
  1175. $items['example'] = array(
  1176. 'title' => 'Example Page',
  1177. 'page callback' => 'example_page',
  1178. 'access arguments' => array('access content'),
  1179. 'type' => MENU_SUGGESTED_ITEM,
  1180. );
  1181. $items['example/feed'] = array(
  1182. 'title' => 'Example RSS feed',
  1183. 'page callback' => 'example_feed',
  1184. 'access arguments' => array('access content'),
  1185. 'type' => MENU_CALLBACK,
  1186. );
  1187. return $items;
  1188. }
  1189. /**
  1190. * Alter the data being saved to the {menu_router} table after hook_menu is invoked.
  1191. *
  1192. * This hook is invoked by menu_router_build(). The menu definitions are passed
  1193. * in by reference. Each element of the $items array is one item returned
  1194. * by a module from hook_menu. Additional items may be added, or existing items
  1195. * altered.
  1196. *
  1197. * @param $items
  1198. * Associative array of menu router definitions returned from hook_menu().
  1199. */
  1200. function hook_menu_alter(&$items) {
  1201. // Example - disable the page at node/add
  1202. $items['node/add']['access callback'] = FALSE;
  1203. }
  1204. /**
  1205. * Alter the data being saved to the {menu_links} table by menu_link_save().
  1206. *
  1207. * @param $item
  1208. * Associative array defining a menu link as passed into menu_link_save().
  1209. *
  1210. * @see hook_translated_menu_link_alter()
  1211. */
  1212. function hook_menu_link_alter(&$item) {
  1213. // Make all new admin links hidden (a.k.a disabled).
  1214. if (strpos($item['link_path'], 'admin') === 0 && empty($item['mlid'])) {
  1215. $item['hidden'] = 1;
  1216. }
  1217. // Flag a link to be altered by hook_translated_menu_link_alter().
  1218. if ($item['link_path'] == 'devel/cache/clear') {
  1219. $item['options']['alter'] = TRUE;
  1220. }
  1221. // Flag a link to be altered by hook_translated_menu_link_alter(), but only
  1222. // if it is derived from a menu router item; i.e., do not alter a custom
  1223. // menu link pointing to the same path that has been created by a user.
  1224. if ($item['link_path'] == 'user' && $item['module'] == 'system') {
  1225. $item['options']['alter'] = TRUE;
  1226. }
  1227. }
  1228. /**
  1229. * Alter a menu link after it has been translated and before it is rendered.
  1230. *
  1231. * This hook is invoked from _menu_link_translate() after a menu link has been
  1232. * translated; i.e., after dynamic path argument placeholders (%) have been
  1233. * replaced with actual values, the user access to the link's target page has
  1234. * been checked, and the link has been localized. It is only invoked if
  1235. * $item['options']['alter'] has been set to a non-empty value (e.g., TRUE).
  1236. * This flag should be set using hook_menu_link_alter().
  1237. *
  1238. * Implementations of this hook are able to alter any property of the menu link.
  1239. * For example, this hook may be used to add a page-specific query string to all
  1240. * menu links, or hide a certain link by setting:
  1241. * @code
  1242. * 'hidden' => 1,
  1243. * @endcode
  1244. *
  1245. * @param $item
  1246. * Associative array defining a menu link after _menu_link_translate()
  1247. * @param $map
  1248. * Associative array containing the menu $map (path parts and/or objects).
  1249. *
  1250. * @see hook_menu_link_alter()
  1251. */
  1252. function hook_translated_menu_link_alter(&$item, $map) {
  1253. if ($item['href'] == 'devel/cache/clear') {
  1254. $item['localized_options']['query'] = drupal_get_destination();
  1255. }
  1256. }
  1257. /**
  1258. * Inform modules that a menu link has been created.
  1259. *
  1260. * This hook is used to notify modules that menu items have been
  1261. * created. Contributed modules may use the information to perform
  1262. * actions based on the information entered into the menu system.
  1263. *
  1264. * @param $link
  1265. * Associative array defining a menu link as passed into menu_link_save().
  1266. *
  1267. * @see hook_menu_link_update()
  1268. * @see hook_menu_link_delete()
  1269. */
  1270. function hook_menu_link_insert($link) {
  1271. // In our sample case, we track menu items as editing sections
  1272. // of the site. These are stored in our table as 'disabled' items.
  1273. $record['mlid'] = $link['mlid'];
  1274. $record['menu_name'] = $link['menu_name'];
  1275. $record['status'] = 0;
  1276. drupal_write_record('menu_example', $record);
  1277. }
  1278. /**
  1279. * Inform modules that a menu link has been updated.
  1280. *
  1281. * This hook is used to notify modules that menu items have been
  1282. * updated. Contributed modules may use the information to perform
  1283. * actions based on the information entered into the menu system.
  1284. *
  1285. * @param $link
  1286. * Associative array defining a menu link as passed into menu_link_save().
  1287. *
  1288. * @see hook_menu_link_insert()
  1289. * @see hook_menu_link_delete()
  1290. */
  1291. function hook_menu_link_update($link) {
  1292. // If the parent menu has changed, update our record.
  1293. $menu_name = db_query("SELECT menu_name FROM {menu_example} WHERE mlid = :mlid", array(':mlid' => $link['mlid']))->fetchField();
  1294. if ($menu_name != $link['menu_name']) {
  1295. db_update('menu_example')
  1296. ->fields(array('menu_name' => $link['menu_name']))
  1297. ->condition('mlid', $link['mlid'])
  1298. ->execute();
  1299. }
  1300. }
  1301. /**
  1302. * Inform modules that a menu link has been deleted.
  1303. *
  1304. * This hook is used to notify modules that menu items have been
  1305. * deleted. Contributed modules may use the information to perform
  1306. * actions based on the information entered into the menu system.
  1307. *
  1308. * @param $link
  1309. * Associative array defining a menu link as passed into menu_link_save().
  1310. *
  1311. * @see hook_menu_link_insert()
  1312. * @see hook_menu_link_update()
  1313. */
  1314. function hook_menu_link_delete($link) {
  1315. // Delete the record from our table.
  1316. db_delete('menu_example')
  1317. ->condition('mlid', $link['mlid'])
  1318. ->execute();
  1319. }
  1320. /**
  1321. * Alter tabs and actions displayed on the page before they are rendered.
  1322. *
  1323. * This hook is invoked by menu_local_tasks(). The system-determined tabs and
  1324. * actions are passed in by reference. Additional tabs or actions may be added,
  1325. * or existing items altered.
  1326. *
  1327. * Each tab or action is an associative array containing:
  1328. * - #theme: The theme function to use to render.
  1329. * - #link: An associative array containing:
  1330. * - title: The localized title of the link.
  1331. * - href: The system path to link to.
  1332. * - localized_options: An array of options to pass to url().
  1333. * - #active: Whether the link should be marked as 'active'.
  1334. *
  1335. * @param $data
  1336. * An associative array containing:
  1337. * - actions: An associative array containing:
  1338. * - count: The amount of actions determined by the menu system, which can
  1339. * be ignored.
  1340. * - output: A list of of actions, each one being an associative array
  1341. * as described above.
  1342. * - tabs: An indexed array (list) of tab levels (up to 2 levels), each
  1343. * containing an associative array:
  1344. * - count: The amount of tabs determined by the menu system. This value
  1345. * does not need to be altered if there is more than one tab.
  1346. * - output: A list of of tabs, each one being an associative array as
  1347. * described above.
  1348. * @param $router_item
  1349. * The menu system router item of the page.
  1350. * @param $root_path
  1351. * The path to the root item for this set of tabs.
  1352. */
  1353. function hook_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  1354. // Add an action linking to node/add to all pages.
  1355. $data['actions']['output'][] = array(
  1356. '#theme' => 'menu_local_task',
  1357. '#link' => array(
  1358. 'title' => t('Add new content'),
  1359. 'href' => 'node/add',
  1360. 'localized_options' => array(
  1361. 'attributes' => array(
  1362. 'title' => t('Add new content'),
  1363. ),
  1364. ),
  1365. ),
  1366. );
  1367. // Add a tab linking to node/add to all pages.
  1368. $data['tabs'][0]['output'][] = array(
  1369. '#theme' => 'menu_local_task',
  1370. '#link' => array(
  1371. 'title' => t('Example tab'),
  1372. 'href' => 'node/add',
  1373. 'localized_options' => array(
  1374. 'attributes' => array(
  1375. 'title' => t('Add new content'),
  1376. ),
  1377. ),
  1378. ),
  1379. // Define whether this link is active. This can be omitted for
  1380. // implementations that add links to pages outside of the current page
  1381. // context.
  1382. '#active' => ($router_item['path'] == $root_path),
  1383. );
  1384. }
  1385. /**
  1386. * Alter links in the active trail before it is rendered as the breadcrumb.
  1387. *
  1388. * This hook is invoked by menu_get_active_breadcrumb() and allows alteration
  1389. * of the breadcrumb links for the current page, which may be preferred instead
  1390. * of setting a custom breadcrumb via drupal_set_breadcrumb().
  1391. *
  1392. * Implementations should take into account that menu_get_active_breadcrumb()
  1393. * subsequently performs the following adjustments to the active trail *after*
  1394. * this hook has been invoked:
  1395. * - The last link in $active_trail is removed, if its 'href' is identical to
  1396. * the 'href' of $item. This happens, because the breadcrumb normally does
  1397. * not contain a link to the current page.
  1398. * - The (second to) last link in $active_trail is removed, if the current $item
  1399. * is a MENU_DEFAULT_LOCAL_TASK. This happens in order to do not show a link
  1400. * to the current page, when being on the path for the default local task;
  1401. * e.g. when being on the path node/%/view, the breadcrumb should not contain
  1402. * a link to node/%.
  1403. *
  1404. * Each link in the active trail must contain:
  1405. * - title: The localized title of the link.
  1406. * - href: The system path to link to.
  1407. * - localized_options: An array of options to pass to url().
  1408. *
  1409. * @param $active_trail
  1410. * An array containing breadcrumb links for the current page.
  1411. * @param $item
  1412. * The menu router item of the current page.
  1413. *
  1414. * @see drupal_set_breadcrumb()
  1415. * @see menu_get_active_breadcrumb()
  1416. * @see menu_get_active_trail()
  1417. * @see menu_set_active_trail()
  1418. */
  1419. function hook_menu_breadcrumb_alter(&$active_trail, $item) {
  1420. // Always display a link to the current page by duplicating the last link in
  1421. // the active trail. This means that menu_get_active_breadcrumb() will remove
  1422. // the last link (for the current page), but since it is added once more here,
  1423. // it will appear.
  1424. if (!drupal_is_front_page()) {
  1425. $end = end($active_trail);
  1426. if ($item['href'] == $end['href']) {
  1427. $active_trail[] = $end;
  1428. }
  1429. }
  1430. }
  1431. /**
  1432. * Alter contextual links before they are rendered.
  1433. *
  1434. * This hook is invoked by menu_contextual_links(). The system-determined
  1435. * contextual links are passed in by reference. Additional links may be added
  1436. * or existing links can be altered.
  1437. *
  1438. * Each contextual link must at least contain:
  1439. * - title: The localized title of the link.
  1440. * - href: The system path to link to.
  1441. * - localized_options: An array of options to pass to url().
  1442. *
  1443. * @param $links
  1444. * An associative array containing contextual links for the given $root_path,
  1445. * as described above. The array keys are used to build CSS class names for
  1446. * contextual links and must therefore be unique for each set of contextual
  1447. * links.
  1448. * @param $router_item
  1449. * The menu router item belonging to the $root_path being requested.
  1450. * @param $root_path
  1451. * The (parent) path that has been requested to build contextual links for.
  1452. * This is a normalized path, which means that an originally passed path of
  1453. * 'node/123' became 'node/%'.
  1454. *
  1455. * @see hook_contextual_links_view_alter()
  1456. * @see menu_contextual_links()
  1457. * @see hook_menu()
  1458. * @see contextual_preprocess()
  1459. */
  1460. function hook_menu_contextual_links_alter(&$links, $router_item, $root_path) {
  1461. // Add a link to all contextual links for nodes.
  1462. if ($root_path == 'node/%') {
  1463. $links['foo'] = array(
  1464. 'title' => t('Do fu'),
  1465. 'href' => 'foo/do',
  1466. 'localized_options' => array(
  1467. 'query' => array(
  1468. 'foo' => 'bar',
  1469. ),
  1470. ),
  1471. );
  1472. }
  1473. }
  1474. /**
  1475. * Perform alterations before a page is rendered.
  1476. *
  1477. * Use this hook when you want to remove or alter elements at the page
  1478. * level, or add elements at the page level that depend on an other module's
  1479. * elements (this hook runs after hook_page_build().
  1480. *
  1481. * If you are making changes to entities such as forms, menus, or user
  1482. * profiles, use those objects' native alter hooks instead (hook_form_alter(),
  1483. * for example).
  1484. *
  1485. * The $page array contains top level elements for each block region:
  1486. * @code
  1487. * $page['page_top']
  1488. * $page['header']
  1489. * $page['sidebar_first']
  1490. * $page['content']
  1491. * $page['sidebar_second']
  1492. * $page['page_bottom']
  1493. * @endcode
  1494. *
  1495. * The 'content' element contains the main content of the current page, and its
  1496. * structure will vary depending on what module is responsible for building the
  1497. * page. Some legacy modules may not return structured content at all: their
  1498. * pre-rendered markup will be located in $page['content']['main']['#markup'].
  1499. *
  1500. * Pages built by Drupal's core Node and Blog modules use a standard structure:
  1501. *
  1502. * @code
  1503. * // Node body.
  1504. * $page['content']['system_main']['nodes'][$nid]['body']
  1505. * // Array of links attached to the node (add comments, read more).
  1506. * $page['content']['system_main']['nodes'][$nid]['links']
  1507. * // The node object itself.
  1508. * $page['content']['system_main']['nodes'][$nid]['#node']
  1509. * // The results pager.
  1510. * $page['content']['system_main']['pager']
  1511. * @endcode
  1512. *
  1513. * Blocks may be referenced by their module/delta pair within a region:
  1514. * @code
  1515. * // The login block in the first sidebar region.
  1516. * $page['sidebar_first']['user_login']['#block'];
  1517. * @endcode
  1518. *
  1519. * @param $page
  1520. * Nested array of renderable elements that make up the page.
  1521. *
  1522. * @see hook_page_build()
  1523. * @see drupal_render_page()
  1524. */
  1525. function hook_page_alter(&$page) {
  1526. // Add help text to the user login block.
  1527. $page['sidebar_first']['user_login']['help'] = array(
  1528. '#weight' => -10,
  1529. '#markup' => t('To post comments or add new content, you first have to log in.'),
  1530. );
  1531. }
  1532. /**
  1533. * Perform alterations before a form is rendered.
  1534. *
  1535. * One popular use of this hook is to add form elements to the node form. When
  1536. * altering a node form, the node object can be accessed at $form['#node'].
  1537. *
  1538. * In addition to hook_form_alter(), which is called for all forms, there are
  1539. * two more specific form hooks available. The first,
  1540. * hook_form_BASE_FORM_ID_alter(), allows targeting of a form/forms via a base
  1541. * form (if one exists). The second, hook_form_FORM_ID_alter(), can be used to
  1542. * target a specific form directly.
  1543. *
  1544. * The call order is as follows: all existing form alter functions are called
  1545. * for module A, then all for module B, etc., followed by all for any base
  1546. * theme(s), and finally for the theme itself. The module order is determined
  1547. * by system weight, then by module name.
  1548. *
  1549. * Within each module, form alter hooks are called in the following order:
  1550. * first, hook_form_alter(); second, hook_form_BASE_FORM_ID_alter(); third,
  1551. * hook_form_FORM_ID_alter(). So, for each module, the more general hooks are
  1552. * called first followed by the more specific.
  1553. *
  1554. * @param $form
  1555. * Nested array of form elements that comprise the form.
  1556. * @param $form_state
  1557. * A keyed array containing the current state of the form. The arguments
  1558. * that drupal_get_form() was originally called with are available in the
  1559. * array $form_state['build_info']['args'].
  1560. * @param $form_id
  1561. * String representing the name of the form itself. Typically this is the
  1562. * name of the function that generated the form.
  1563. *
  1564. * @see hook_form_BASE_FORM_ID_alter()
  1565. * @see hook_form_FORM_ID_alter()
  1566. */
  1567. function hook_form_alter(&$form, &$form_state, $form_id) {
  1568. if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
  1569. $form['workflow']['upload_' . $form['type']['#value']] = array(
  1570. '#type' => 'radios',
  1571. '#title' => t('Attachments'),
  1572. '#default_value' => variable_get('upload_' . $form['type']['#value'], 1),
  1573. '#options' => array(t('Disabled'), t('Enabled')),
  1574. );
  1575. }
  1576. }
  1577. /**
  1578. * Provide a form-specific alteration instead of the global hook_form_alter().
  1579. *
  1580. * Modules can implement hook_form_FORM_ID_alter() to modify a specific form,
  1581. * rather than implementing hook_form_alter() and checking the form ID, or
  1582. * using long switch statements to alter multiple forms.
  1583. *
  1584. * Form alter hooks are called in the following order: hook_form_alter(),
  1585. * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  1586. * hook_form_alter() for more details.
  1587. *
  1588. * @param $form
  1589. * Nested array of form elements that comprise the form.
  1590. * @param $form_state
  1591. * A keyed array containing the current state of the form. The arguments
  1592. * that drupal_get_form() was originally called with are available in the
  1593. * array $form_state['build_info']['args'].
  1594. * @param $form_id
  1595. * String representing the name of the form itself. Typically this is the
  1596. * name of the function that generated the form.
  1597. *
  1598. * @see hook_form_alter()
  1599. * @see hook_form_BASE_FORM_ID_alter()
  1600. * @see drupal_prepare_form()
  1601. */
  1602. function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  1603. // Modification for the form with the given form ID goes here. For example, if
  1604. // FORM_ID is "user_register_form" this code would run only on the user
  1605. // registration form.
  1606. // Add a checkbox to registration form about agreeing to terms of use.
  1607. $form['terms_of_use'] = array(
  1608. '#type' => 'checkbox',
  1609. '#title' => t("I agree with the website's terms and conditions."),
  1610. '#required' => TRUE,
  1611. );
  1612. }
  1613. /**
  1614. * Provide a form-specific alteration for shared ('base') forms.
  1615. *
  1616. * By default, when drupal_get_form() is called, Drupal looks for a function
  1617. * with the same name as the form ID, and uses that function to build the form.
  1618. * In contrast, base forms allow multiple form IDs to be mapped to a single base
  1619. * (also called 'factory') form function.
  1620. *
  1621. * Modules can implement hook_form_BASE_FORM_ID_alter() to modify a specific
  1622. * base form, rather than implementing hook_form_alter() and checking for
  1623. * conditions that would identify the shared form constructor.
  1624. *
  1625. * To identify the base form ID for a particular form (or to determine whether
  1626. * one exists) check the $form_state. The base form ID is stored under
  1627. * $form_state['build_info']['base_form_id'].
  1628. *
  1629. * See hook_forms() for more information on how to implement base forms in
  1630. * Drupal.
  1631. *
  1632. * Form alter hooks are called in the following order: hook_form_alter(),
  1633. * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  1634. * hook_form_alter() for more details.
  1635. *
  1636. * @param $form
  1637. * Nested array of form elements that comprise the form.
  1638. * @param $form_state
  1639. * A keyed array containing the current state of the form.
  1640. * @param $form_id
  1641. * String representing the name of the form itself. Typically this is the
  1642. * name of the function that generated the form.
  1643. *
  1644. * @see hook_form_alter()
  1645. * @see hook_form_FORM_ID_alter()
  1646. * @see drupal_prepare_form()
  1647. * @see hook_forms()
  1648. */
  1649. function hook_form_BASE_FORM_ID_alter(&$form, &$form_state, $form_id) {
  1650. // Modification for the form with the given BASE_FORM_ID goes here. For
  1651. // example, if BASE_FORM_ID is "node_form", this code would run on every
  1652. // node form, regardless of node type.
  1653. // Add a checkbox to the node form about agreeing to terms of use.
  1654. $form['terms_of_use'] = array(
  1655. '#type' => 'checkbox',
  1656. '#title' => t("I agree with the website's terms and conditions."),
  1657. '#required' => TRUE,
  1658. );
  1659. }
  1660. /**
  1661. * Map form_ids to form builder functions.
  1662. *
  1663. * By default, when drupal_get_form() is called, the system will look for a
  1664. * function with the same name as the form ID, and use that function to build
  1665. * the form. If no such function is found, Drupal calls this hook. Modules
  1666. * implementing this hook can then provide their own instructions for mapping
  1667. * form IDs to constructor functions. As a result, you can easily map multiple
  1668. * form IDs to a single form constructor (referred to as a 'base' form).
  1669. *
  1670. * Using a base form can help to avoid code duplication, by allowing many
  1671. * similar forms to use the same code base. Another benefit is that it becomes
  1672. * much easier for other modules to apply a general change to the group of
  1673. * forms; hook_form_BASE_FORM_ID_alter() can be used to easily alter multiple
  1674. * forms at once by directly targeting the shared base form.
  1675. *
  1676. * Two example use cases where base forms may be useful are given below.
  1677. *
  1678. * First, you can use this hook to tell the form system to use a different
  1679. * function to build certain forms in your module; this is often used to define
  1680. * a form "factory" function that is used to build several similar forms. In
  1681. * this case, your hook implementation will likely ignore all of the input
  1682. * arguments. See node_forms() for an example of this. Note, node_forms() is the
  1683. * hook_forms() implementation; the base form itself is defined in node_form().
  1684. *
  1685. * Second, you could use this hook to define how to build a form with a
  1686. * dynamically-generated form ID. In this case, you would need to verify that
  1687. * the $form_id input matched your module's format for dynamically-generated
  1688. * form IDs, and if so, act appropriately.
  1689. *
  1690. * @param $form_id
  1691. * The unique string identifying the desired form.
  1692. * @param $args
  1693. * An array containing the original arguments provided to drupal_get_form()
  1694. * or drupal_form_submit(). These are always passed to the form builder and
  1695. * do not have to be specified manually in 'callback arguments'.
  1696. *
  1697. * @return
  1698. * An associative array whose keys define form_ids and whose values are an
  1699. * associative array defining the following keys:
  1700. * - callback: The name of the form builder function to invoke. This will be
  1701. * used for the base form ID, for example, to target a base form using
  1702. * hook_form_BASE_FORM_ID_alter().
  1703. * - callback arguments: (optional) Additional arguments to pass to the
  1704. * function defined in 'callback', which are prepended to $args.
  1705. * - wrapper_callback: (optional) The name of a form builder function to
  1706. * invoke before the form builder defined in 'callback' is invoked. This
  1707. * wrapper callback may prepopulate the $form array with form elements,
  1708. * which will then be already contained in the $form that is passed on to
  1709. * the form builder defined in 'callback'. For example, a wrapper callback
  1710. * could setup wizard-alike form buttons that are the same for a variety of
  1711. * forms that belong to the wizard, which all share the same wrapper
  1712. * callback.
  1713. */
  1714. function hook_forms($form_id, $args) {
  1715. // Simply reroute the (non-existing) $form_id 'mymodule_first_form' to
  1716. // 'mymodule_main_form'.
  1717. $forms['mymodule_first_form'] = array(
  1718. 'callback' => 'mymodule_main_form',
  1719. );
  1720. // Reroute the $form_id and prepend an additional argument that gets passed to
  1721. // the 'mymodule_main_form' form builder function.
  1722. $forms['mymodule_second_form'] = array(
  1723. 'callback' => 'mymodule_main_form',
  1724. 'callback arguments' => array('some parameter'),
  1725. );
  1726. // Reroute the $form_id, but invoke the form builder function
  1727. // 'mymodule_main_form_wrapper' first, so we can prepopulate the $form array
  1728. // that is passed to the actual form builder 'mymodule_main_form'.
  1729. $forms['mymodule_wrapped_form'] = array(
  1730. 'callback' => 'mymodule_main_form',
  1731. 'wrapper_callback' => 'mymodule_main_form_wrapper',
  1732. );
  1733. return $forms;
  1734. }
  1735. /**
  1736. * Perform setup tasks for all page requests.
  1737. *
  1738. * This hook is run at the beginning of the page request. It is typically
  1739. * used to set up global parameters that are needed later in the request.
  1740. *
  1741. * Only use this hook if your code must run even for cached page views. This
  1742. * hook is called before modules or most include files are loaded into memory.
  1743. * It happens while Drupal is still in bootstrap mode.
  1744. *
  1745. * @see hook_init()
  1746. */
  1747. function hook_boot() {
  1748. // We need user_access() in the shutdown function. Make sure it gets loaded.
  1749. drupal_load('module', 'user');
  1750. drupal_register_shutdown_function('devel_shutdown');
  1751. }
  1752. /**
  1753. * Perform setup tasks for non-cached page requests.
  1754. *
  1755. * This hook is run at the beginning of the page request. It is typically
  1756. * used to set up global parameters that are needed later in the request.
  1757. * When this hook is called, all modules are already loaded in memory.
  1758. *
  1759. * This hook is not run on cached pages.
  1760. *
  1761. * To add CSS or JS that should be present on all pages, modules should not
  1762. * implement this hook, but declare these files in their .info file.
  1763. *
  1764. * @see hook_boot()
  1765. */
  1766. function hook_init() {
  1767. // Since this file should only be loaded on the front page, it cannot be
  1768. // declared in the info file.
  1769. if (drupal_is_front_page()) {
  1770. drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  1771. }
  1772. }
  1773. /**
  1774. * Define image toolkits provided by this module.
  1775. *
  1776. * The file which includes each toolkit's functions must be declared as part of
  1777. * the files array in the module .info file so that the registry will find and
  1778. * parse it.
  1779. *
  1780. * The toolkit's functions must be named image_toolkitname_operation().
  1781. * where the operation may be:
  1782. * - 'load': Required. See image_gd_load() for usage.
  1783. * - 'save': Required. See image_gd_save() for usage.
  1784. * - 'settings': Optional. See image_gd_settings() for usage.
  1785. * - 'resize': Optional. See image_gd_resize() for usage.
  1786. * - 'rotate': Optional. See image_gd_rotate() for usage.
  1787. * - 'crop': Optional. See image_gd_crop() for usage.
  1788. * - 'desaturate': Optional. See image_gd_desaturate() for usage.
  1789. *
  1790. * @return
  1791. * An array with the toolkit name as keys and sub-arrays with these keys:
  1792. * - 'title': A string with the toolkit's title.
  1793. * - 'available': A Boolean value to indicate that the toolkit is operating
  1794. * properly, e.g. all required libraries exist.
  1795. *
  1796. * @see system_image_toolkits()
  1797. */
  1798. function hook_image_toolkits() {
  1799. return array(
  1800. 'working' => array(
  1801. 'title' => t('A toolkit that works.'),
  1802. 'available' => TRUE,
  1803. ),
  1804. 'broken' => array(
  1805. 'title' => t('A toolkit that is "broken" and will not be listed.'),
  1806. 'available' => FALSE,
  1807. ),
  1808. );
  1809. }
  1810. /**
  1811. * Alter an email message created with the drupal_mail() function.
  1812. *
  1813. * hook_mail_alter() allows modification of email messages created and sent
  1814. * with drupal_mail(). Usage examples include adding and/or changing message
  1815. * text, message fields, and message headers.
  1816. *
  1817. * Email messages sent using functions other than drupal_mail() will not
  1818. * invoke hook_mail_alter(). For example, a contributed module directly
  1819. * calling the drupal_mail_system()->mail() or PHP mail() function
  1820. * will not invoke this hook. All core modules use drupal_mail() for
  1821. * messaging, it is best practice but not mandatory in contributed modules.
  1822. *
  1823. * @param $message
  1824. * An array containing the message data. Keys in this array include:
  1825. * - 'id':
  1826. * The drupal_mail() id of the message. Look at module source code or
  1827. * drupal_mail() for possible id values.
  1828. * - 'to':
  1829. * The address or addresses the message will be sent to. The
  1830. * formatting of this string must comply with RFC 2822.
  1831. * - 'from':
  1832. * The address the message will be marked as being from, which is
  1833. * either a custom address or the site-wide default email address.
  1834. * - 'subject':
  1835. * Subject of the email to be sent. This must not contain any newline
  1836. * characters, or the email may not be sent properly.
  1837. * - 'body':
  1838. * An array of strings containing the message text. The message body is
  1839. * created by concatenating the individual array strings into a single text
  1840. * string using "\n\n" as a separator.
  1841. * - 'headers':
  1842. * Associative array containing mail headers, such as From, Sender,
  1843. * MIME-Version, Content-Type, etc.
  1844. * - 'params':
  1845. * An array of optional parameters supplied by the caller of drupal_mail()
  1846. * that is used to build the message before hook_mail_alter() is invoked.
  1847. * - 'language':
  1848. * The language object used to build the message before hook_mail_alter()
  1849. * is invoked.
  1850. * - 'send':
  1851. * Set to FALSE to abort sending this email message.
  1852. *
  1853. * @see drupal_mail()
  1854. */
  1855. function hook_mail_alter(&$message) {
  1856. if ($message['id'] == 'modulename_messagekey') {
  1857. if (!example_notifications_optin($message['to'], $message['id'])) {
  1858. // If the recipient has opted to not receive such messages, cancel
  1859. // sending.
  1860. $message['send'] = FALSE;
  1861. return;
  1862. }
  1863. $message['body'][] = "--\nMail sent out from " . variable_get('site_name', t('Drupal'));
  1864. }
  1865. }
  1866. /**
  1867. * Alter the registry of modules implementing a hook.
  1868. *
  1869. * This hook is invoked during module_implements(). A module may implement this
  1870. * hook in order to reorder the implementing modules, which are otherwise
  1871. * ordered by the module's system weight.
  1872. *
  1873. * Note that hooks invoked using drupal_alter() can have multiple variations
  1874. * (such as hook_form_alter() and hook_form_FORM_ID_alter()). drupal_alter()
  1875. * will call all such variants defined by a single module in turn. For the
  1876. * purposes of hook_module_implements_alter(), these variants are treated as
  1877. * a single hook. Thus, to ensure that your implementation of
  1878. * hook_form_FORM_ID_alter() is called at the right time, you will have to
  1879. * have to change the order of hook_form_alter() implementation in
  1880. * hook_module_implements_alter().
  1881. *
  1882. * @param $implementations
  1883. * An array keyed by the module's name. The value of each item corresponds
  1884. * to a $group, which is usually FALSE, unless the implementation is in a
  1885. * file named $module.$group.inc.
  1886. * @param $hook
  1887. * The name of the module hook being implemented.
  1888. */
  1889. function hook_module_implements_alter(&$implementations, $hook) {
  1890. if ($hook == 'rdf_mapping') {
  1891. // Move my_module_rdf_mapping() to the end of the list. module_implements()
  1892. // iterates through $implementations with a foreach loop which PHP iterates
  1893. // in the order that the items were added, so to move an item to the end of
  1894. // the array, we remove it and then add it.
  1895. $group = $implementations['my_module'];
  1896. unset($implementations['my_module']);
  1897. $implementations['my_module'] = $group;
  1898. }
  1899. }
  1900. /**
  1901. * Return additional themes provided by modules.
  1902. *
  1903. * Only use this hook for testing purposes. Use a hidden MYMODULE_test.module
  1904. * to implement this hook. Testing themes should be hidden, too.
  1905. *
  1906. * This hook is invoked from _system_rebuild_theme_data() and allows modules to
  1907. * register additional themes outside of the regular 'themes' directories of a
  1908. * Drupal installation.
  1909. *
  1910. * @return
  1911. * An associative array. Each key is the system name of a theme and each value
  1912. * is the corresponding path to the theme's .info file.
  1913. */
  1914. function hook_system_theme_info() {
  1915. $themes['mymodule_test_theme'] = drupal_get_path('module', 'mymodule') . '/mymodule_test_theme/mymodule_test_theme.info';
  1916. return $themes;
  1917. }
  1918. /**
  1919. * Alter the information parsed from module and theme .info files
  1920. *
  1921. * This hook is invoked in _system_rebuild_module_data() and in
  1922. * _system_rebuild_theme_data(). A module may implement this hook in order to
  1923. * add to or alter the data generated by reading the .info file with
  1924. * drupal_parse_info_file().
  1925. *
  1926. * @param $info
  1927. * The .info file contents, passed by reference so that it can be altered.
  1928. * @param $file
  1929. * Full information about the module or theme, including $file->name, and
  1930. * $file->filename
  1931. * @param $type
  1932. * Either 'module' or 'theme', depending on the type of .info file that was
  1933. * passed.
  1934. */
  1935. function hook_system_info_alter(&$info, $file, $type) {
  1936. // Only fill this in if the .info file does not define a 'datestamp'.
  1937. if (empty($info['datestamp'])) {
  1938. $info['datestamp'] = filemtime($file->filename);
  1939. }
  1940. }
  1941. /**
  1942. * Define user permissions.
  1943. *
  1944. * This hook can supply permissions that the module defines, so that they
  1945. * can be selected on the user permissions page and used to grant or restrict
  1946. * access to actions the module performs.
  1947. *
  1948. * Permissions are checked using user_access().
  1949. *
  1950. * For a detailed usage example, see page_example.module.
  1951. *
  1952. * @return
  1953. * An array whose keys are permission names and whose corresponding values
  1954. * are arrays containing the following key-value pairs:
  1955. * - title: The human-readable name of the permission, to be shown on the
  1956. * permission administration page. This should be wrapped in the t()
  1957. * function so it can be translated.
  1958. * - description: (optional) A description of what the permission does. This
  1959. * should be wrapped in the t() function so it can be translated.
  1960. * - restrict access: (optional) A boolean which can be set to TRUE to
  1961. * indicate that site administrators should restrict access to this
  1962. * permission to trusted users. This should be used for permissions that
  1963. * have inherent security risks across a variety of potential use cases
  1964. * (for example, the "administer filters" and "bypass node access"
  1965. * permissions provided by Drupal core). When set to TRUE, a standard
  1966. * warning message defined in user_admin_permissions() and output via
  1967. * theme_user_permission_description() will be associated with the
  1968. * permission and displayed with it on the permission administration page.
  1969. * Defaults to FALSE.
  1970. * - warning: (optional) A translated warning message to display for this
  1971. * permission on the permission administration page. This warning overrides
  1972. * the automatic warning generated by 'restrict access' being set to TRUE.
  1973. * This should rarely be used, since it is important for all permissions to
  1974. * have a clear, consistent security warning that is the same across the
  1975. * site. Use the 'description' key instead to provide any information that
  1976. * is specific to the permission you are defining.
  1977. *
  1978. * @see theme_user_permission_description()
  1979. */
  1980. function hook_permission() {
  1981. return array(
  1982. 'administer my module' => array(
  1983. 'title' => t('Administer my module'),
  1984. 'description' => t('Perform administration tasks for my module.'),
  1985. ),
  1986. );
  1987. }
  1988. /**
  1989. * Register a module (or theme's) theme implementations.
  1990. *
  1991. * The implementations declared by this hook have two purposes: either they
  1992. * specify how a particular render array is to be rendered as HTML (this is
  1993. * usually the case if the theme function is assigned to the render array's
  1994. * #theme property), or they return the HTML that should be returned by an
  1995. * invocation of theme().
  1996. *
  1997. * The following parameters are all optional.
  1998. *
  1999. * @param array $existing
  2000. * An array of existing implementations that may be used for override
  2001. * purposes. This is primarily useful for themes that may wish to examine
  2002. * existing implementations to extract data (such as arguments) so that
  2003. * it may properly register its own, higher priority implementations.
  2004. * @param $type
  2005. * Whether a theme, module, etc. is being processed. This is primarily useful
  2006. * so that themes tell if they are the actual theme being called or a parent
  2007. * theme. May be one of:
  2008. * - 'module': A module is being checked for theme implementations.
  2009. * - 'base_theme_engine': A theme engine is being checked for a theme that is
  2010. * a parent of the actual theme being used.
  2011. * - 'theme_engine': A theme engine is being checked for the actual theme
  2012. * being used.
  2013. * - 'base_theme': A base theme is being checked for theme implementations.
  2014. * - 'theme': The actual theme in use is being checked.
  2015. * @param $theme
  2016. * The actual name of theme, module, etc. that is being being processed.
  2017. * @param $path
  2018. * The directory path of the theme or module, so that it doesn't need to be
  2019. * looked up.
  2020. *
  2021. * @return array
  2022. * An associative array of theme hook information. The keys on the outer
  2023. * array are the internal names of the hooks, and the values are arrays
  2024. * containing information about the hook. Each information array must contain
  2025. * either a 'variables' element or a 'render element' element, but not both.
  2026. * Use 'render element' if you are theming a single element or element tree
  2027. * composed of elements, such as a form array, a page array, or a single
  2028. * checkbox element. Use 'variables' if your theme implementation is
  2029. * intended to be called directly through theme() and has multiple arguments
  2030. * for the data and style; in this case, the variables not supplied by the
  2031. * calling function will be given default values and passed to the template
  2032. * or theme function. The returned theme information array can contain the
  2033. * following key/value pairs:
  2034. * - variables: (see above) Each array key is the name of the variable, and
  2035. * the value given is used as the default value if the function calling
  2036. * theme() does not supply it. Template implementations receive each array
  2037. * key as a variable in the template file (so they must be legal PHP
  2038. * variable names). Function implementations are passed the variables in a
  2039. * single $variables function argument.
  2040. * - render element: (see above) The name of the renderable element or element
  2041. * tree to pass to the theme function. This name is used as the name of the
  2042. * variable that holds the renderable element or tree in preprocess and
  2043. * process functions.
  2044. * - file: The file the implementation resides in. This file will be included
  2045. * prior to the theme being rendered, to make sure that the function or
  2046. * preprocess function (as needed) is actually loaded; this makes it
  2047. * possible to split theme functions out into separate files quite easily.
  2048. * - path: Override the path of the file to be used. Ordinarily the module or
  2049. * theme path will be used, but if the file will not be in the default
  2050. * path, include it here. This path should be relative to the Drupal root
  2051. * directory.
  2052. * - template: If specified, this theme implementation is a template, and
  2053. * this is the template file without an extension. Do not put .tpl.php on
  2054. * this file; that extension will be added automatically by the default
  2055. * rendering engine (which is PHPTemplate). If 'path', above, is specified,
  2056. * the template should also be in this path.
  2057. * - function: If specified, this will be the function name to invoke for
  2058. * this implementation. If neither 'template' nor 'function' is specified,
  2059. * a default function name will be assumed. For example, if a module
  2060. * registers the 'node' theme hook, 'theme_node' will be assigned to its
  2061. * function. If the chameleon theme registers the node hook, it will be
  2062. * assigned 'chameleon_node' as its function.
  2063. * - pattern: A regular expression pattern to be used to allow this theme
  2064. * implementation to have a dynamic name. The convention is to use __ to
  2065. * differentiate the dynamic portion of the theme. For example, to allow
  2066. * forums to be themed individually, the pattern might be: 'forum__'. Then,
  2067. * when the forum is themed, call:
  2068. * @code
  2069. * theme(array('forum__' . $tid, 'forum'), $forum)
  2070. * @endcode
  2071. * - preprocess functions: A list of functions used to preprocess this data.
  2072. * Ordinarily this won't be used; it's automatically filled in. By default,
  2073. * for a module this will be filled in as template_preprocess_HOOK. For
  2074. * a theme this will be filled in as phptemplate_preprocess and
  2075. * phptemplate_preprocess_HOOK as well as themename_preprocess and
  2076. * themename_preprocess_HOOK.
  2077. * - override preprocess functions: Set to TRUE when a theme does NOT want
  2078. * the standard preprocess functions to run. This can be used to give a
  2079. * theme FULL control over how variables are set. For example, if a theme
  2080. * wants total control over how certain variables in the page.tpl.php are
  2081. * set, this can be set to true. Please keep in mind that when this is used
  2082. * by a theme, that theme becomes responsible for making sure necessary
  2083. * variables are set.
  2084. * - type: (automatically derived) Where the theme hook is defined:
  2085. * 'module', 'theme_engine', or 'theme'.
  2086. * - theme path: (automatically derived) The directory path of the theme or
  2087. * module, so that it doesn't need to be looked up.
  2088. */
  2089. function hook_theme($existing, $type, $theme, $path) {
  2090. return array(
  2091. 'forum_display' => array(
  2092. 'variables' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
  2093. ),
  2094. 'forum_list' => array(
  2095. 'variables' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
  2096. ),
  2097. 'forum_topic_list' => array(
  2098. 'variables' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
  2099. ),
  2100. 'forum_icon' => array(
  2101. 'variables' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0),
  2102. ),
  2103. 'status_report' => array(
  2104. 'render element' => 'requirements',
  2105. 'file' => 'system.admin.inc',
  2106. ),
  2107. 'system_date_time_settings' => array(
  2108. 'render element' => 'form',
  2109. 'file' => 'system.admin.inc',
  2110. ),
  2111. );
  2112. }
  2113. /**
  2114. * Alter the theme registry information returned from hook_theme().
  2115. *
  2116. * The theme registry stores information about all available theme hooks,
  2117. * including which callback functions those hooks will call when triggered,
  2118. * what template files are exposed by these hooks, and so on.
  2119. *
  2120. * Note that this hook is only executed as the theme cache is re-built.
  2121. * Changes here will not be visible until the next cache clear.
  2122. *
  2123. * The $theme_registry array is keyed by theme hook name, and contains the
  2124. * information returned from hook_theme(), as well as additional properties
  2125. * added by _theme_process_registry().
  2126. *
  2127. * For example:
  2128. * @code
  2129. * $theme_registry['user_profile'] = array(
  2130. * 'variables' => array(
  2131. * 'account' => NULL,
  2132. * ),
  2133. * 'template' => 'modules/user/user-profile',
  2134. * 'file' => 'modules/user/user.pages.inc',
  2135. * 'type' => 'module',
  2136. * 'theme path' => 'modules/user',
  2137. * 'preprocess functions' => array(
  2138. * 0 => 'template_preprocess',
  2139. * 1 => 'template_preprocess_user_profile',
  2140. * ),
  2141. * );
  2142. * @endcode
  2143. *
  2144. * @param $theme_registry
  2145. * The entire cache of theme registry information, post-processing.
  2146. *
  2147. * @see hook_theme()
  2148. * @see _theme_process_registry()
  2149. */
  2150. function hook_theme_registry_alter(&$theme_registry) {
  2151. // Kill the next/previous forum topic navigation links.
  2152. foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
  2153. if ($value == 'template_preprocess_forum_topic_navigation') {
  2154. unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
  2155. }
  2156. }
  2157. }
  2158. /**
  2159. * Return the machine-readable name of the theme to use for the current page.
  2160. *
  2161. * This hook can be used to dynamically set the theme for the current page
  2162. * request. It should be used by modules which need to override the theme
  2163. * based on dynamic conditions (for example, a module which allows the theme to
  2164. * be set based on the current user's role). The return value of this hook will
  2165. * be used on all pages except those which have a valid per-page or per-section
  2166. * theme set via a theme callback function in hook_menu(); the themes on those
  2167. * pages can only be overridden using hook_menu_alter().
  2168. *
  2169. * Note that returning different themes for the same path may not work with page
  2170. * caching. This is most likely to be a problem if an anonymous user on a given
  2171. * path could have different themes returned under different conditions.
  2172. *
  2173. * Since only one theme can be used at a time, the last (i.e., highest
  2174. * weighted) module which returns a valid theme name from this hook will
  2175. * prevail.
  2176. *
  2177. * @return
  2178. * The machine-readable name of the theme that should be used for the current
  2179. * page request. The value returned from this function will only have an
  2180. * effect if it corresponds to a currently-active theme on the site.
  2181. */
  2182. function hook_custom_theme() {
  2183. // Allow the user to request a particular theme via a query parameter.
  2184. if (isset($_GET['theme'])) {
  2185. return $_GET['theme'];
  2186. }
  2187. }
  2188. /**
  2189. * Register XML-RPC callbacks.
  2190. *
  2191. * This hook lets a module register callback functions to be called when
  2192. * particular XML-RPC methods are invoked by a client.
  2193. *
  2194. * @return
  2195. * An array which maps XML-RPC methods to Drupal functions. Each array
  2196. * element is either a pair of method => function or an array with four
  2197. * entries:
  2198. * - The XML-RPC method name (for example, module.function).
  2199. * - The Drupal callback function (for example, module_function).
  2200. * - The method signature is an array of XML-RPC types. The first element
  2201. * of this array is the type of return value and then you should write a
  2202. * list of the types of the parameters. XML-RPC types are the following
  2203. * (See the types at http://www.xmlrpc.com/spec):
  2204. * - "boolean": 0 (false) or 1 (true).
  2205. * - "double": a floating point number (for example, -12.214).
  2206. * - "int": a integer number (for example, -12).
  2207. * - "array": an array without keys (for example, array(1, 2, 3)).
  2208. * - "struct": an associative array or an object (for example,
  2209. * array('one' => 1, 'two' => 2)).
  2210. * - "date": when you return a date, then you may either return a
  2211. * timestamp (time(), mktime() etc.) or an ISO8601 timestamp. When
  2212. * date is specified as an input parameter, then you get an object,
  2213. * which is described in the function xmlrpc_date
  2214. * - "base64": a string containing binary data, automatically
  2215. * encoded/decoded automatically.
  2216. * - "string": anything else, typically a string.
  2217. * - A descriptive help string, enclosed in a t() function for translation
  2218. * purposes.
  2219. * Both forms are shown in the example.
  2220. */
  2221. function hook_xmlrpc() {
  2222. return array(
  2223. 'drupal.login' => 'drupal_login',
  2224. array(
  2225. 'drupal.site.ping',
  2226. 'drupal_directory_ping',
  2227. array('boolean', 'string', 'string', 'string', 'string', 'string'),
  2228. t('Handling ping request'))
  2229. );
  2230. }
  2231. /**
  2232. * Alters the definition of XML-RPC methods before they are called.
  2233. *
  2234. * This hook allows modules to modify the callback definition of declared
  2235. * XML-RPC methods, right before they are invoked by a client. Methods may be
  2236. * added, or existing methods may be altered.
  2237. *
  2238. * Note that hook_xmlrpc() supports two distinct and incompatible formats to
  2239. * define a callback, so care must be taken when altering other methods.
  2240. *
  2241. * @param $methods
  2242. * An asssociative array of method callback definitions, as returned from
  2243. * hook_xmlrpc() implementations.
  2244. *
  2245. * @see hook_xmlrpc()
  2246. * @see xmlrpc_server()
  2247. */
  2248. function hook_xmlrpc_alter(&$methods) {
  2249. // Directly change a simple method.
  2250. $methods['drupal.login'] = 'mymodule_login';
  2251. // Alter complex definitions.
  2252. foreach ($methods as $key => &$method) {
  2253. // Skip simple method definitions.
  2254. if (!is_int($key)) {
  2255. continue;
  2256. }
  2257. // Perform the wanted manipulation.
  2258. if ($method[0] == 'drupal.site.ping') {
  2259. $method[1] = 'mymodule_directory_ping';
  2260. }
  2261. }
  2262. }
  2263. /**
  2264. * Log an event message.
  2265. *
  2266. * This hook allows modules to route log events to custom destinations, such as
  2267. * SMS, Email, pager, syslog, ...etc.
  2268. *
  2269. * @param $log_entry
  2270. * An associative array containing the following keys:
  2271. * - type: The type of message for this entry.
  2272. * - user: The user object for the user who was logged in when the event
  2273. * happened.
  2274. * - request_uri: The request URI for the page the event happened in.
  2275. * - referer: The page that referred the user to the page where the event
  2276. * occurred.
  2277. * - ip: The IP address where the request for the page came from.
  2278. * - timestamp: The UNIX timestamp of the date/time the event occurred.
  2279. * - severity: The severity of the message; one of the following values as
  2280. * defined in @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
  2281. * - WATCHDOG_EMERGENCY: Emergency, system is unusable.
  2282. * - WATCHDOG_ALERT: Alert, action must be taken immediately.
  2283. * - WATCHDOG_CRITICAL: Critical conditions.
  2284. * - WATCHDOG_ERROR: Error conditions.
  2285. * - WATCHDOG_WARNING: Warning conditions.
  2286. * - WATCHDOG_NOTICE: Normal but significant conditions.
  2287. * - WATCHDOG_INFO: Informational messages.
  2288. * - WATCHDOG_DEBUG: Debug-level messages.
  2289. * - link: An optional link provided by the module that called the watchdog()
  2290. * function.
  2291. * - message: The text of the message to be logged. Variables in the message
  2292. * are indicated by using placeholder strings alongside the variables
  2293. * argument to declare the value of the placeholders. See t() for
  2294. * documentation on how the message and variable parameters interact.
  2295. * - variables: An array of variables to be inserted into the message on
  2296. * display. Will be NULL or missing if a message is already translated or if
  2297. * the message is not possible to translate.
  2298. */
  2299. function hook_watchdog(array $log_entry) {
  2300. global $base_url, $language;
  2301. $severity_list = array(
  2302. WATCHDOG_EMERGENCY => t('Emergency'),
  2303. WATCHDOG_ALERT => t('Alert'),
  2304. WATCHDOG_CRITICAL => t('Critical'),
  2305. WATCHDOG_ERROR => t('Error'),
  2306. WATCHDOG_WARNING => t('Warning'),
  2307. WATCHDOG_NOTICE => t('Notice'),
  2308. WATCHDOG_INFO => t('Info'),
  2309. WATCHDOG_DEBUG => t('Debug'),
  2310. );
  2311. $to = 'someone@example.com';
  2312. $params = array();
  2313. $params['subject'] = t('[@site_name] @severity_desc: Alert from your web site', array(
  2314. '@site_name' => variable_get('site_name', 'Drupal'),
  2315. '@severity_desc' => $severity_list[$log_entry['severity']],
  2316. ));
  2317. $params['message'] = "\nSite: @base_url";
  2318. $params['message'] .= "\nSeverity: (@severity) @severity_desc";
  2319. $params['message'] .= "\nTimestamp: @timestamp";
  2320. $params['message'] .= "\nType: @type";
  2321. $params['message'] .= "\nIP Address: @ip";
  2322. $params['message'] .= "\nRequest URI: @request_uri";
  2323. $params['message'] .= "\nReferrer URI: @referer_uri";
  2324. $params['message'] .= "\nUser: (@uid) @name";
  2325. $params['message'] .= "\nLink: @link";
  2326. $params['message'] .= "\nMessage: \n\n@message";
  2327. $params['message'] = t($params['message'], array(
  2328. '@base_url' => $base_url,
  2329. '@severity' => $log_entry['severity'],
  2330. '@severity_desc' => $severity_list[$log_entry['severity']],
  2331. '@timestamp' => format_date($log_entry['timestamp']),
  2332. '@type' => $log_entry['type'],
  2333. '@ip' => $log_entry['ip'],
  2334. '@request_uri' => $log_entry['request_uri'],
  2335. '@referer_uri' => $log_entry['referer'],
  2336. '@uid' => $log_entry['user']->uid,
  2337. '@name' => $log_entry['user']->name,
  2338. '@link' => strip_tags($log_entry['link']),
  2339. '@message' => strip_tags($log_entry['message']),
  2340. ));
  2341. drupal_mail('emaillog', 'entry', $to, $language, $params);
  2342. }
  2343. /**
  2344. * Prepare a message based on parameters; called from drupal_mail().
  2345. *
  2346. * Note that hook_mail(), unlike hook_mail_alter(), is only called on the
  2347. * $module argument to drupal_mail(), not all modules.
  2348. *
  2349. * @param $key
  2350. * An identifier of the mail.
  2351. * @param $message
  2352. * An array to be filled in. Elements in this array include:
  2353. * - id: An ID to identify the mail sent. Look at module source code
  2354. * or drupal_mail() for possible id values.
  2355. * - to: The address or addresses the message will be sent to. The
  2356. * formatting of this string must comply with RFC 2822.
  2357. * - subject: Subject of the e-mail to be sent. This must not contain any
  2358. * newline characters, or the mail may not be sent properly. drupal_mail()
  2359. * sets this to an empty string when the hook is invoked.
  2360. * - body: An array of lines containing the message to be sent. Drupal will
  2361. * format the correct line endings for you. drupal_mail() sets this to an
  2362. * empty array when the hook is invoked.
  2363. * - from: The address the message will be marked as being from, which is
  2364. * set by drupal_mail() to either a custom address or the site-wide
  2365. * default email address when the hook is invoked.
  2366. * - headers: Associative array containing mail headers, such as From,
  2367. * Sender, MIME-Version, Content-Type, etc. drupal_mail() pre-fills
  2368. * several headers in this array.
  2369. * @param $params
  2370. * An array of parameters supplied by the caller of drupal_mail().
  2371. */
  2372. function hook_mail($key, &$message, $params) {
  2373. $account = $params['account'];
  2374. $context = $params['context'];
  2375. $variables = array(
  2376. '%site_name' => variable_get('site_name', 'Drupal'),
  2377. '%username' => format_username($account),
  2378. );
  2379. if ($context['hook'] == 'taxonomy') {
  2380. $entity = $params['entity'];
  2381. $vocabulary = taxonomy_vocabulary_load($entity->vid);
  2382. $variables += array(
  2383. '%term_name' => $entity->name,
  2384. '%term_description' => $entity->description,
  2385. '%term_id' => $entity->tid,
  2386. '%vocabulary_name' => $vocabulary->name,
  2387. '%vocabulary_description' => $vocabulary->description,
  2388. '%vocabulary_id' => $vocabulary->vid,
  2389. );
  2390. }
  2391. // Node-based variable translation is only available if we have a node.
  2392. if (isset($params['node'])) {
  2393. $node = $params['node'];
  2394. $variables += array(
  2395. '%uid' => $node->uid,
  2396. '%node_url' => url('node/' . $node->nid, array('absolute' => TRUE)),
  2397. '%node_type' => node_type_get_name($node),
  2398. '%title' => $node->title,
  2399. '%teaser' => $node->teaser,
  2400. '%body' => $node->body,
  2401. );
  2402. }
  2403. $subject = strtr($context['subject'], $variables);
  2404. $body = strtr($context['message'], $variables);
  2405. $message['subject'] .= str_replace(array("\r", "\n"), '', $subject);
  2406. $message['body'][] = drupal_html_to_text($body);
  2407. }
  2408. /**
  2409. * Add a list of cache tables to be cleared.
  2410. *
  2411. * This hook allows your module to add cache table names to the list of cache
  2412. * tables that will be cleared by the Clear button on the Performance page or
  2413. * whenever drupal_flush_all_caches is invoked.
  2414. *
  2415. * @return
  2416. * An array of cache table names.
  2417. *
  2418. * @see drupal_flush_all_caches()
  2419. */
  2420. function hook_flush_caches() {
  2421. return array('cache_example');
  2422. }
  2423. /**
  2424. * Perform necessary actions after modules are installed.
  2425. *
  2426. * This function differs from hook_install() in that it gives all other modules
  2427. * a chance to perform actions when a module is installed, whereas
  2428. * hook_install() is only called on the module actually being installed. See
  2429. * module_enable() for a detailed description of the order in which install and
  2430. * enable hooks are invoked.
  2431. *
  2432. * @param $modules
  2433. * An array of the modules that were installed.
  2434. *
  2435. * @see module_enable()
  2436. * @see hook_modules_enabled()
  2437. * @see hook_install()
  2438. */
  2439. function hook_modules_installed($modules) {
  2440. if (in_array('lousy_module', $modules)) {
  2441. variable_set('lousy_module_conflicting_variable', FALSE);
  2442. }
  2443. }
  2444. /**
  2445. * Perform necessary actions after modules are enabled.
  2446. *
  2447. * This function differs from hook_enable() in that it gives all other modules a
  2448. * chance to perform actions when modules are enabled, whereas hook_enable() is
  2449. * only called on the module actually being enabled. See module_enable() for a
  2450. * detailed description of the order in which install and enable hooks are
  2451. * invoked.
  2452. *
  2453. * @param $modules
  2454. * An array of the modules that were enabled.
  2455. *
  2456. * @see hook_enable()
  2457. * @see hook_modules_installed()
  2458. * @see module_enable()
  2459. */
  2460. function hook_modules_enabled($modules) {
  2461. if (in_array('lousy_module', $modules)) {
  2462. drupal_set_message(t('mymodule is not compatible with lousy_module'), 'error');
  2463. mymodule_disable_functionality();
  2464. }
  2465. }
  2466. /**
  2467. * Perform necessary actions after modules are disabled.
  2468. *
  2469. * This function differs from hook_disable() in that it gives all other modules
  2470. * a chance to perform actions when modules are disabled, whereas hook_disable()
  2471. * is only called on the module actually being disabled.
  2472. *
  2473. * @param $modules
  2474. * An array of the modules that were disabled.
  2475. *
  2476. * @see hook_disable()
  2477. * @see hook_modules_uninstalled()
  2478. */
  2479. function hook_modules_disabled($modules) {
  2480. if (in_array('lousy_module', $modules)) {
  2481. mymodule_enable_functionality();
  2482. }
  2483. }
  2484. /**
  2485. * Perform necessary actions after modules are uninstalled.
  2486. *
  2487. * This function differs from hook_uninstall() in that it gives all other
  2488. * modules a chance to perform actions when a module is uninstalled, whereas
  2489. * hook_uninstall() is only called on the module actually being uninstalled.
  2490. *
  2491. * It is recommended that you implement this hook if your module stores
  2492. * data that may have been set by other modules.
  2493. *
  2494. * @param $modules
  2495. * An array of the modules that were uninstalled.
  2496. *
  2497. * @see hook_uninstall()
  2498. * @see hook_modules_disabled()
  2499. */
  2500. function hook_modules_uninstalled($modules) {
  2501. foreach ($modules as $module) {
  2502. db_delete('mymodule_table')
  2503. ->condition('module', $module)
  2504. ->execute();
  2505. }
  2506. mymodule_cache_rebuild();
  2507. }
  2508. /**
  2509. * Registers PHP stream wrapper implementations associated with a module.
  2510. *
  2511. * Provide a facility for managing and querying user-defined stream wrappers
  2512. * in PHP. PHP's internal stream_get_wrappers() doesn't return the class
  2513. * registered to handle a stream, which we need to be able to find the handler
  2514. * for class instantiation.
  2515. *
  2516. * If a module registers a scheme that is already registered with PHP, it will
  2517. * be unregistered and replaced with the specified class.
  2518. *
  2519. * @return
  2520. * A nested array, keyed first by scheme name ("public" for "public://"),
  2521. * then keyed by the following values:
  2522. * - 'name' A short string to name the wrapper.
  2523. * - 'class' A string specifying the PHP class that implements the
  2524. * DrupalStreamWrapperInterface interface.
  2525. * - 'description' A string with a short description of what the wrapper does.
  2526. * - 'type' (Optional) A bitmask of flags indicating what type of streams this
  2527. * wrapper will access - local or remote, readable and/or writeable, etc.
  2528. * Many shortcut constants are defined in stream_wrappers.inc. Defaults to
  2529. * STREAM_WRAPPERS_NORMAL which includes all of these bit flags:
  2530. * - STREAM_WRAPPERS_READ
  2531. * - STREAM_WRAPPERS_WRITE
  2532. * - STREAM_WRAPPERS_VISIBLE
  2533. *
  2534. * @see file_get_stream_wrappers()
  2535. * @see hook_stream_wrappers_alter()
  2536. * @see system_stream_wrappers()
  2537. */
  2538. function hook_stream_wrappers() {
  2539. return array(
  2540. 'public' => array(
  2541. 'name' => t('Public files'),
  2542. 'class' => 'DrupalPublicStreamWrapper',
  2543. 'description' => t('Public local files served by the webserver.'),
  2544. 'type' => STREAM_WRAPPERS_LOCAL_NORMAL,
  2545. ),
  2546. 'private' => array(
  2547. 'name' => t('Private files'),
  2548. 'class' => 'DrupalPrivateStreamWrapper',
  2549. 'description' => t('Private local files served by Drupal.'),
  2550. 'type' => STREAM_WRAPPERS_LOCAL_NORMAL,
  2551. ),
  2552. 'temp' => array(
  2553. 'name' => t('Temporary files'),
  2554. 'class' => 'DrupalTempStreamWrapper',
  2555. 'description' => t('Temporary local files for upload and previews.'),
  2556. 'type' => STREAM_WRAPPERS_LOCAL_HIDDEN,
  2557. ),
  2558. 'cdn' => array(
  2559. 'name' => t('Content delivery network files'),
  2560. 'class' => 'MyModuleCDNStreamWrapper',
  2561. 'description' => t('Files served by a content delivery network.'),
  2562. // 'type' can be omitted to use the default of STREAM_WRAPPERS_NORMAL
  2563. ),
  2564. 'youtube' => array(
  2565. 'name' => t('YouTube video'),
  2566. 'class' => 'MyModuleYouTubeStreamWrapper',
  2567. 'description' => t('Video streamed from YouTube.'),
  2568. // A module implementing YouTube integration may decide to support using
  2569. // the YouTube API for uploading video, but here, we assume that this
  2570. // particular module only supports playing YouTube video.
  2571. 'type' => STREAM_WRAPPERS_READ_VISIBLE,
  2572. ),
  2573. );
  2574. }
  2575. /**
  2576. * Alters the list of PHP stream wrapper implementations.
  2577. *
  2578. * @see file_get_stream_wrappers()
  2579. * @see hook_stream_wrappers()
  2580. */
  2581. function hook_stream_wrappers_alter(&$wrappers) {
  2582. // Change the name of private files to reflect the performance.
  2583. $wrappers['private']['name'] = t('Slow files');
  2584. }
  2585. /**
  2586. * Load additional information into file objects.
  2587. *
  2588. * file_load_multiple() calls this hook to allow modules to load
  2589. * additional information into each file.
  2590. *
  2591. * @param $files
  2592. * An array of file objects, indexed by fid.
  2593. *
  2594. * @see file_load_multiple()
  2595. * @see file_load()
  2596. */
  2597. function hook_file_load($files) {
  2598. // Add the upload specific data into the file object.
  2599. $result = db_query('SELECT * FROM {upload} u WHERE u.fid IN (:fids)', array(':fids' => array_keys($files)))->fetchAll(PDO::FETCH_ASSOC);
  2600. foreach ($result as $record) {
  2601. foreach ($record as $key => $value) {
  2602. $files[$record['fid']]->$key = $value;
  2603. }
  2604. }
  2605. }
  2606. /**
  2607. * Check that files meet a given criteria.
  2608. *
  2609. * This hook lets modules perform additional validation on files. They're able
  2610. * to report a failure by returning one or more error messages.
  2611. *
  2612. * @param $file
  2613. * The file object being validated.
  2614. * @return
  2615. * An array of error messages. If there are no problems with the file return
  2616. * an empty array.
  2617. *
  2618. * @see file_validate()
  2619. */
  2620. function hook_file_validate($file) {
  2621. $errors = array();
  2622. if (empty($file->filename)) {
  2623. $errors[] = t("The file's name is empty. Please give a name to the file.");
  2624. }
  2625. if (strlen($file->filename) > 255) {
  2626. $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  2627. }
  2628. return $errors;
  2629. }
  2630. /**
  2631. * Act on a file being inserted or updated.
  2632. *
  2633. * This hook is called when a file has been added to the database. The hook
  2634. * doesn't distinguish between files created as a result of a copy or those
  2635. * created by an upload.
  2636. *
  2637. * @param $file
  2638. * The file that has just been created.
  2639. *
  2640. * @see file_save()
  2641. */
  2642. function hook_file_presave($file) {
  2643. // Change the file timestamp to an hour prior.
  2644. $file->timestamp -= 3600;
  2645. }
  2646. /**
  2647. * Respond to a file being added.
  2648. *
  2649. * This hook is called after a file has been added to the database. The hook
  2650. * doesn't distinguish between files created as a result of a copy or those
  2651. * created by an upload.
  2652. *
  2653. * @param $file
  2654. * The file that has been added.
  2655. *
  2656. * @see file_save()
  2657. */
  2658. function hook_file_insert($file) {
  2659. // Add a message to the log, if the file is a jpg
  2660. $validate = file_validate_extensions($file, 'jpg');
  2661. if (empty($validate)) {
  2662. watchdog('file', 'A jpg has been added.');
  2663. }
  2664. }
  2665. /**
  2666. * Respond to a file being updated.
  2667. *
  2668. * This hook is called when file_save() is called on an existing file.
  2669. *
  2670. * @param $file
  2671. * The file that has just been updated.
  2672. *
  2673. * @see file_save()
  2674. */
  2675. function hook_file_update($file) {
  2676. }
  2677. /**
  2678. * Respond to a file that has been copied.
  2679. *
  2680. * @param $file
  2681. * The newly copied file object.
  2682. * @param $source
  2683. * The original file before the copy.
  2684. *
  2685. * @see file_copy()
  2686. */
  2687. function hook_file_copy($file, $source) {
  2688. }
  2689. /**
  2690. * Respond to a file that has been moved.
  2691. *
  2692. * @param $file
  2693. * The updated file object after the move.
  2694. * @param $source
  2695. * The original file object before the move.
  2696. *
  2697. * @see file_move()
  2698. */
  2699. function hook_file_move($file, $source) {
  2700. }
  2701. /**
  2702. * Respond to a file being deleted.
  2703. *
  2704. * @param $file
  2705. * The file that has just been deleted.
  2706. *
  2707. * @see file_delete()
  2708. */
  2709. function hook_file_delete($file) {
  2710. // Delete all information associated with the file.
  2711. db_delete('upload')->condition('fid', $file->fid)->execute();
  2712. }
  2713. /**
  2714. * Control access to private file downloads and specify HTTP headers.
  2715. *
  2716. * This hook allows modules enforce permissions on file downloads when the
  2717. * private file download method is selected. Modules can also provide headers
  2718. * to specify information like the file's name or MIME type.
  2719. *
  2720. * @param $uri
  2721. * The URI of the file.
  2722. * @return
  2723. * If the user does not have permission to access the file, return -1. If the
  2724. * user has permission, return an array with the appropriate headers. If the
  2725. * file is not controlled by the current module, the return value should be
  2726. * NULL.
  2727. *
  2728. * @see file_download()
  2729. */
  2730. function hook_file_download($uri) {
  2731. // Check if the file is controlled by the current module.
  2732. if (!file_prepare_directory($uri)) {
  2733. $uri = FALSE;
  2734. }
  2735. if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
  2736. if (!user_access('access user profiles')) {
  2737. // Access to the file is denied.
  2738. return -1;
  2739. }
  2740. else {
  2741. $info = image_get_info($uri);
  2742. return array('Content-Type' => $info['mime_type']);
  2743. }
  2744. }
  2745. }
  2746. /**
  2747. * Alter the URL to a file.
  2748. *
  2749. * This hook is called from file_create_url(), and is called fairly
  2750. * frequently (10+ times per page), depending on how many files there are in a
  2751. * given page.
  2752. * If CSS and JS aggregation are disabled, this can become very frequently
  2753. * (50+ times per page) so performance is critical.
  2754. *
  2755. * This function should alter the URI, if it wants to rewrite the file URL.
  2756. *
  2757. * @param $uri
  2758. * The URI to a file for which we need an external URL, or the path to a
  2759. * shipped file.
  2760. */
  2761. function hook_file_url_alter(&$uri) {
  2762. global $user;
  2763. // User 1 will always see the local file in this example.
  2764. if ($user->uid == 1) {
  2765. return;
  2766. }
  2767. $cdn1 = 'http://cdn1.example.com';
  2768. $cdn2 = 'http://cdn2.example.com';
  2769. $cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png');
  2770. // Most CDNs don't support private file transfers without a lot of hassle,
  2771. // so don't support this in the common case.
  2772. $schemes = array('public');
  2773. $scheme = file_uri_scheme($uri);
  2774. // Only serve shipped files and public created files from the CDN.
  2775. if (!$scheme || in_array($scheme, $schemes)) {
  2776. // Shipped files.
  2777. if (!$scheme) {
  2778. $path = $uri;
  2779. }
  2780. // Public created files.
  2781. else {
  2782. $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
  2783. $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
  2784. }
  2785. // Clean up Windows paths.
  2786. $path = str_replace('\\', '/', $path);
  2787. // Serve files with one of the CDN extensions from CDN 1, all others from
  2788. // CDN 2.
  2789. $pathinfo = pathinfo($path);
  2790. if (isset($pathinfo['extension']) && in_array($pathinfo['extension'], $cdn_extensions)) {
  2791. $uri = $cdn1 . '/' . $path;
  2792. }
  2793. else {
  2794. $uri = $cdn2 . '/' . $path;
  2795. }
  2796. }
  2797. }
  2798. /**
  2799. * Check installation requirements and do status reporting.
  2800. *
  2801. * This hook has three closely related uses, determined by the $phase argument:
  2802. * - Checking installation requirements ($phase == 'install').
  2803. * - Checking update requirements ($phase == 'update').
  2804. * - Status reporting ($phase == 'runtime').
  2805. *
  2806. * Note that this hook, like all others dealing with installation and updates,
  2807. * must reside in a module_name.install file, or it will not properly abort
  2808. * the installation of the module if a critical requirement is missing.
  2809. *
  2810. * During the 'install' phase, modules can for example assert that
  2811. * library or server versions are available or sufficient.
  2812. * Note that the installation of a module can happen during installation of
  2813. * Drupal itself (by install.php) with an installation profile or later by hand.
  2814. * As a consequence, install-time requirements must be checked without access
  2815. * to the full Drupal API, because it is not available during install.php.
  2816. * For localization you should for example use $t = get_t() to
  2817. * retrieve the appropriate localization function name (t() or st()).
  2818. * If a requirement has a severity of REQUIREMENT_ERROR, install.php will abort
  2819. * or at least the module will not install.
  2820. * Other severity levels have no effect on the installation.
  2821. * Module dependencies do not belong to these installation requirements,
  2822. * but should be defined in the module's .info file.
  2823. *
  2824. * The 'runtime' phase is not limited to pure installation requirements
  2825. * but can also be used for more general status information like maintenance
  2826. * tasks and security issues.
  2827. * The returned 'requirements' will be listed on the status report in the
  2828. * administration section, with indication of the severity level.
  2829. * Moreover, any requirement with a severity of REQUIREMENT_ERROR severity will
  2830. * result in a notice on the the administration overview page.
  2831. *
  2832. * @param $phase
  2833. * The phase in which requirements are checked:
  2834. * - install: The module is being installed.
  2835. * - update: The module is enabled and update.php is run.
  2836. * - runtime: The runtime requirements are being checked and shown on the
  2837. * status report page.
  2838. *
  2839. * @return
  2840. * A keyed array of requirements. Each requirement is itself an array with
  2841. * the following items:
  2842. * - title: The name of the requirement.
  2843. * - value: The current value (e.g., version, time, level, etc). During
  2844. * install phase, this should only be used for version numbers, do not set
  2845. * it if not applicable.
  2846. * - description: The description of the requirement/status.
  2847. * - severity: The requirement's result/severity level, one of:
  2848. * - REQUIREMENT_INFO: For info only.
  2849. * - REQUIREMENT_OK: The requirement is satisfied.
  2850. * - REQUIREMENT_WARNING: The requirement failed with a warning.
  2851. * - REQUIREMENT_ERROR: The requirement failed with an error.
  2852. */
  2853. function hook_requirements($phase) {
  2854. $requirements = array();
  2855. // Ensure translations don't break at install time
  2856. $t = get_t();
  2857. // Report Drupal version
  2858. if ($phase == 'runtime') {
  2859. $requirements['drupal'] = array(
  2860. 'title' => $t('Drupal'),
  2861. 'value' => VERSION,
  2862. 'severity' => REQUIREMENT_INFO
  2863. );
  2864. }
  2865. // Test PHP version
  2866. $requirements['php'] = array(
  2867. 'title' => $t('PHP'),
  2868. 'value' => ($phase == 'runtime') ? l(phpversion(), 'admin/reports/status/php') : phpversion(),
  2869. );
  2870. if (version_compare(phpversion(), DRUPAL_MINIMUM_PHP) < 0) {
  2871. $requirements['php']['description'] = $t('Your PHP installation is too old. Drupal requires at least PHP %version.', array('%version' => DRUPAL_MINIMUM_PHP));
  2872. $requirements['php']['severity'] = REQUIREMENT_ERROR;
  2873. }
  2874. // Report cron status
  2875. if ($phase == 'runtime') {
  2876. $cron_last = variable_get('cron_last');
  2877. if (is_numeric($cron_last)) {
  2878. $requirements['cron']['value'] = $t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
  2879. }
  2880. else {
  2881. $requirements['cron'] = array(
  2882. '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')),
  2883. 'severity' => REQUIREMENT_ERROR,
  2884. 'value' => $t('Never run'),
  2885. );
  2886. }
  2887. $requirements['cron']['description'] .= ' ' . $t('You can <a href="@cron">run cron manually</a>.', array('@cron' => url('admin/reports/status/run-cron')));
  2888. $requirements['cron']['title'] = $t('Cron maintenance tasks');
  2889. }
  2890. return $requirements;
  2891. }
  2892. /**
  2893. * Define the current version of the database schema.
  2894. *
  2895. * A Drupal schema definition is an array structure representing one or
  2896. * more tables and their related keys and indexes. A schema is defined by
  2897. * hook_schema() which must live in your module's .install file.
  2898. *
  2899. * This hook is called at both install and uninstall time, and in the latter
  2900. * case, it cannot rely on the .module file being loaded or hooks being known.
  2901. * If the .module file is needed, it may be loaded with drupal_load().
  2902. *
  2903. * The tables declared by this hook will be automatically created when
  2904. * the module is first enabled, and removed when the module is uninstalled.
  2905. * This happens before hook_install() is invoked, and after hook_uninstall()
  2906. * is invoked, respectively.
  2907. *
  2908. * By declaring the tables used by your module via an implementation of
  2909. * hook_schema(), these tables will be available on all supported database
  2910. * engines. You don't have to deal with the different SQL dialects for table
  2911. * creation and alteration of the supported database engines.
  2912. *
  2913. * See the Schema API Handbook at http://drupal.org/node/146843 for
  2914. * details on schema definition structures.
  2915. *
  2916. * @return
  2917. * A schema definition structure array. For each element of the
  2918. * array, the key is a table name and the value is a table structure
  2919. * definition.
  2920. *
  2921. * @ingroup schemaapi
  2922. */
  2923. function hook_schema() {
  2924. $schema['node'] = array(
  2925. // example (partial) specification for table "node"
  2926. 'description' => 'The base table for nodes.',
  2927. 'fields' => array(
  2928. 'nid' => array(
  2929. 'description' => 'The primary identifier for a node.',
  2930. 'type' => 'serial',
  2931. 'unsigned' => TRUE,
  2932. 'not null' => TRUE),
  2933. 'vid' => array(
  2934. 'description' => 'The current {node_revision}.vid version identifier.',
  2935. 'type' => 'int',
  2936. 'unsigned' => TRUE,
  2937. 'not null' => TRUE,
  2938. 'default' => 0),
  2939. 'type' => array(
  2940. 'description' => 'The {node_type} of this node.',
  2941. 'type' => 'varchar',
  2942. 'length' => 32,
  2943. 'not null' => TRUE,
  2944. 'default' => ''),
  2945. 'title' => array(
  2946. 'description' => 'The title of this node, always treated as non-markup plain text.',
  2947. 'type' => 'varchar',
  2948. 'length' => 255,
  2949. 'not null' => TRUE,
  2950. 'default' => ''),
  2951. ),
  2952. 'indexes' => array(
  2953. 'node_changed' => array('changed'),
  2954. 'node_created' => array('created'),
  2955. ),
  2956. 'unique keys' => array(
  2957. 'nid_vid' => array('nid', 'vid'),
  2958. 'vid' => array('vid')
  2959. ),
  2960. 'foreign keys' => array(
  2961. 'node_revision' => array(
  2962. 'table' => 'node_revision',
  2963. 'columns' => array('vid' => 'vid'),
  2964. ),
  2965. 'node_author' => array(
  2966. 'table' => 'users',
  2967. 'columns' => array('uid' => 'uid')
  2968. ),
  2969. ),
  2970. 'primary key' => array('nid'),
  2971. );
  2972. return $schema;
  2973. }
  2974. /**
  2975. * Perform alterations to existing database schemas.
  2976. *
  2977. * When a module modifies the database structure of another module (by
  2978. * changing, adding or removing fields, keys or indexes), it should
  2979. * implement hook_schema_alter() to update the default $schema to take its
  2980. * changes into account.
  2981. *
  2982. * See hook_schema() for details on the schema definition structure.
  2983. *
  2984. * @param $schema
  2985. * Nested array describing the schemas for all modules.
  2986. */
  2987. function hook_schema_alter(&$schema) {
  2988. // Add field to existing schema.
  2989. $schema['users']['fields']['timezone_id'] = array(
  2990. 'type' => 'int',
  2991. 'not null' => TRUE,
  2992. 'default' => 0,
  2993. 'description' => 'Per-user timezone configuration.',
  2994. );
  2995. }
  2996. /**
  2997. * Perform alterations to a structured query.
  2998. *
  2999. * Structured (aka dynamic) queries that have tags associated may be altered by any module
  3000. * before the query is executed.
  3001. *
  3002. * @param $query
  3003. * A Query object describing the composite parts of a SQL query.
  3004. *
  3005. * @see hook_query_TAG_alter()
  3006. * @see node_query_node_access_alter()
  3007. * @see QueryAlterableInterface
  3008. * @see SelectQueryInterface
  3009. */
  3010. function hook_query_alter(QueryAlterableInterface $query) {
  3011. if ($query->hasTag('micro_limit')) {
  3012. $query->range(0, 2);
  3013. }
  3014. }
  3015. /**
  3016. * Perform alterations to a structured query for a given tag.
  3017. *
  3018. * @param $query
  3019. * An Query object describing the composite parts of a SQL query.
  3020. *
  3021. * @see hook_query_alter()
  3022. * @see node_query_node_access_alter()
  3023. * @see QueryAlterableInterface
  3024. * @see SelectQueryInterface
  3025. */
  3026. function hook_query_TAG_alter(QueryAlterableInterface $query) {
  3027. // Skip the extra expensive alterations if site has no node access control modules.
  3028. if (!node_access_view_all_nodes()) {
  3029. // Prevent duplicates records.
  3030. $query->distinct();
  3031. // The recognized operations are 'view', 'update', 'delete'.
  3032. if (!$op = $query->getMetaData('op')) {
  3033. $op = 'view';
  3034. }
  3035. // Skip the extra joins and conditions for node admins.
  3036. if (!user_access('bypass node access')) {
  3037. // The node_access table has the access grants for any given node.
  3038. $access_alias = $query->join('node_access', 'na', '%alias.nid = n.nid');
  3039. $or = db_or();
  3040. // If any grant exists for the specified user, then user has access to the node for the specified operation.
  3041. foreach (node_access_grants($op, $query->getMetaData('account')) as $realm => $gids) {
  3042. foreach ($gids as $gid) {
  3043. $or->condition(db_and()
  3044. ->condition($access_alias . '.gid', $gid)
  3045. ->condition($access_alias . '.realm', $realm)
  3046. );
  3047. }
  3048. }
  3049. if (count($or->conditions())) {
  3050. $query->condition($or);
  3051. }
  3052. $query->condition($access_alias . 'grant_' . $op, 1, '>=');
  3053. }
  3054. }
  3055. }
  3056. /**
  3057. * Perform setup tasks when the module is installed.
  3058. *
  3059. * If the module implements hook_schema(), the database tables will
  3060. * be created before this hook is fired.
  3061. *
  3062. * Implementations of this hook are by convention declared in the module's
  3063. * .install file. The implementation can rely on the .module file being loaded.
  3064. * The hook will only be called the first time a module is enabled or after it
  3065. * is re-enabled after being uninstalled. The module's schema version will be
  3066. * set to the module's greatest numbered update hook. Because of this, any time
  3067. * a hook_update_N() is added to the module, this function needs to be updated
  3068. * to reflect the current version of the database schema.
  3069. *
  3070. * See the Schema API documentation at
  3071. * @link http://drupal.org/node/146843 http://drupal.org/node/146843 @endlink
  3072. * for details on hook_schema and how database tables are defined.
  3073. *
  3074. * Note that since this function is called from a full bootstrap, all functions
  3075. * (including those in modules enabled by the current page request) are
  3076. * available when this hook is called. Use cases could be displaying a user
  3077. * message, or calling a module function necessary for initial setup, etc.
  3078. *
  3079. * Please be sure that anything added or modified in this function that can
  3080. * be removed during uninstall should be removed with hook_uninstall().
  3081. *
  3082. * @see hook_schema()
  3083. * @see module_enable()
  3084. * @see hook_enable()
  3085. * @see hook_disable()
  3086. * @see hook_uninstall()
  3087. * @see hook_modules_installed()
  3088. */
  3089. function hook_install() {
  3090. // Populate the default {node_access} record.
  3091. db_insert('node_access')
  3092. ->fields(array(
  3093. 'nid' => 0,
  3094. 'gid' => 0,
  3095. 'realm' => 'all',
  3096. 'grant_view' => 1,
  3097. 'grant_update' => 0,
  3098. 'grant_delete' => 0,
  3099. ))
  3100. ->execute();
  3101. }
  3102. /**
  3103. * Perform a single update.
  3104. *
  3105. * For each patch which requires a database change add a new hook_update_N()
  3106. * which will be called by update.php. The database updates are numbered
  3107. * sequentially according to the version of Drupal you are compatible with.
  3108. *
  3109. * Schema updates should adhere to the Schema API:
  3110. * @link http://drupal.org/node/150215 http://drupal.org/node/150215 @endlink
  3111. *
  3112. * Database updates consist of 3 parts:
  3113. * - 1 digit for Drupal core compatibility
  3114. * - 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?)
  3115. * - 2 digits for sequential counting starting with 00
  3116. *
  3117. * The 2nd digit should be 0 for initial porting of your module to a new Drupal
  3118. * core API.
  3119. *
  3120. * Examples:
  3121. * - mymodule_update_5200()
  3122. * - This is the first update to get the database ready to run mymodule 5.x-2.*.
  3123. * - mymodule_update_6000()
  3124. * - This is the required update for mymodule to run with Drupal core API 6.x.
  3125. * - mymodule_update_6100()
  3126. * - This is the first update to get the database ready to run mymodule 6.x-1.*.
  3127. * - mymodule_update_6200()
  3128. * - This is the first update to get the database ready to run mymodule 6.x-2.*.
  3129. * Users can directly update from 5.x-2.* to 6.x-2.* and they get all 60XX
  3130. * and 62XX updates, but not 61XX updates, because those reside in the
  3131. * 6.x-1.x branch only.
  3132. *
  3133. * A good rule of thumb is to remove updates older than two major releases of
  3134. * Drupal. See hook_update_last_removed() to notify Drupal about the removals.
  3135. * For further information about releases and release numbers see:
  3136. * @link http://drupal.org/node/711070 Maintaining a drupal.org project with Git @endlink
  3137. *
  3138. * Never renumber update functions.
  3139. *
  3140. * Implementations of this hook should be placed in a mymodule.install file in
  3141. * the same directory as mymodule.module. Drupal core's updates are implemented
  3142. * using the system module as a name and stored in database/updates.inc.
  3143. *
  3144. * If your update task is potentially time-consuming, you'll need to implement a
  3145. * multipass update to avoid PHP timeouts. Multipass updates use the $sandbox
  3146. * parameter provided by the batch API (normally, $context['sandbox']) to store
  3147. * information between successive calls, and the $sandbox['#finished'] value
  3148. * to provide feedback regarding completion level.
  3149. *
  3150. * See the batch operations page for more information on how to use the batch API:
  3151. * @link http://drupal.org/node/180528 http://drupal.org/node/180528 @endlink
  3152. *
  3153. * @param $sandbox
  3154. * Stores information for multipass updates. See above for more information.
  3155. *
  3156. * @throws DrupalUpdateException, PDOException
  3157. * In case of error, update hooks should throw an instance of DrupalUpdateException
  3158. * with a meaningful message for the user. If a database query fails for whatever
  3159. * reason, it will throw a PDOException.
  3160. *
  3161. * @return
  3162. * Optionally update hooks may return a translated string that will be displayed
  3163. * to the user. If no message is returned, no message will be presented to the
  3164. * user.
  3165. */
  3166. function hook_update_N(&$sandbox) {
  3167. // For non-multipass updates, the signature can simply be;
  3168. // function hook_update_N() {
  3169. // For most updates, the following is sufficient.
  3170. db_add_field('mytable1', 'newcol', array('type' => 'int', 'not null' => TRUE, 'description' => 'My new integer column.'));
  3171. // However, for more complex operations that may take a long time,
  3172. // you may hook into Batch API as in the following example.
  3173. // Update 3 users at a time to have an exclamation point after their names.
  3174. // (They're really happy that we can do batch API in this hook!)
  3175. if (!isset($sandbox['progress'])) {
  3176. $sandbox['progress'] = 0;
  3177. $sandbox['current_uid'] = 0;
  3178. // We'll -1 to disregard the uid 0...
  3179. $sandbox['max'] = db_query('SELECT COUNT(DISTINCT uid) FROM {users}')->fetchField() - 1;
  3180. }
  3181. $users = db_select('users', 'u')
  3182. ->fields('u', array('uid', 'name'))
  3183. ->condition('uid', $sandbox['current_uid'], '>')
  3184. ->range(0, 3)
  3185. ->orderBy('uid', 'ASC')
  3186. ->execute();
  3187. foreach ($users as $user) {
  3188. $user->name .= '!';
  3189. db_update('users')
  3190. ->fields(array('name' => $user->name))
  3191. ->condition('uid', $user->uid)
  3192. ->execute();
  3193. $sandbox['progress']++;
  3194. $sandbox['current_uid'] = $user->uid;
  3195. }
  3196. $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
  3197. // To display a message to the user when the update is completed, return it.
  3198. // If you do not want to display a completion message, simply return nothing.
  3199. return t('The update did what it was supposed to do.');
  3200. // In case of an error, simply throw an exception with an error message.
  3201. throw new DrupalUpdateException('Something went wrong; here is what you should do.');
  3202. }
  3203. /**
  3204. * Return an array of information about module update dependencies.
  3205. *
  3206. * This can be used to indicate update functions from other modules that your
  3207. * module's update functions depend on, or vice versa. It is used by the update
  3208. * system to determine the appropriate order in which updates should be run, as
  3209. * well as to search for missing dependencies.
  3210. *
  3211. * Implementations of this hook should be placed in a mymodule.install file in
  3212. * the same directory as mymodule.module.
  3213. *
  3214. * @return
  3215. * A multidimensional array containing information about the module update
  3216. * dependencies. The first two levels of keys represent the module and update
  3217. * number (respectively) for which information is being returned, and the
  3218. * value is an array of information about that update's dependencies. Within
  3219. * this array, each key represents a module, and each value represents the
  3220. * number of an update function within that module. In the event that your
  3221. * update function depends on more than one update from a particular module,
  3222. * you should always list the highest numbered one here (since updates within
  3223. * a given module always run in numerical order).
  3224. *
  3225. * @see update_resolve_dependencies()
  3226. * @see hook_update_N()
  3227. */
  3228. function hook_update_dependencies() {
  3229. // Indicate that the mymodule_update_7000() function provided by this module
  3230. // must run after the another_module_update_7002() function provided by the
  3231. // 'another_module' module.
  3232. $dependencies['mymodule'][7000] = array(
  3233. 'another_module' => 7002,
  3234. );
  3235. // Indicate that the mymodule_update_7001() function provided by this module
  3236. // must run before the yet_another_module_update_7004() function provided by
  3237. // the 'yet_another_module' module. (Note that declaring dependencies in this
  3238. // direction should be done only in rare situations, since it can lead to the
  3239. // following problem: If a site has already run the yet_another_module
  3240. // module's database updates before it updates its codebase to pick up the
  3241. // newest mymodule code, then the dependency declared here will be ignored.)
  3242. $dependencies['yet_another_module'][7004] = array(
  3243. 'mymodule' => 7001,
  3244. );
  3245. return $dependencies;
  3246. }
  3247. /**
  3248. * Return a number which is no longer available as hook_update_N().
  3249. *
  3250. * If you remove some update functions from your mymodule.install file, you
  3251. * should notify Drupal of those missing functions. This way, Drupal can
  3252. * ensure that no update is accidentally skipped.
  3253. *
  3254. * Implementations of this hook should be placed in a mymodule.install file in
  3255. * the same directory as mymodule.module.
  3256. *
  3257. * @return
  3258. * An integer, corresponding to hook_update_N() which has been removed from
  3259. * mymodule.install.
  3260. *
  3261. * @see hook_update_N()
  3262. */
  3263. function hook_update_last_removed() {
  3264. // We've removed the 5.x-1.x version of mymodule, including database updates.
  3265. // The next update function is mymodule_update_5200().
  3266. return 5103;
  3267. }
  3268. /**
  3269. * Remove any information that the module sets.
  3270. *
  3271. * The information that the module should remove includes:
  3272. * - variables that the module has set using variable_set() or system_settings_form()
  3273. * - modifications to existing tables
  3274. *
  3275. * The module should not remove its entry from the {system} table. Database
  3276. * tables defined by hook_schema() will be removed automatically.
  3277. *
  3278. * The uninstall hook must be implemented in the module's .install file. It
  3279. * will fire when the module gets uninstalled but before the module's database
  3280. * tables are removed, allowing your module to query its own tables during
  3281. * this routine.
  3282. *
  3283. * When hook_uninstall() is called, your module will already be disabled, so
  3284. * its .module file will not be automatically included. If you need to call API
  3285. * functions from your .module file in this hook, use drupal_load() to make
  3286. * them available. (Keep this usage to a minimum, though, especially when
  3287. * calling API functions that invoke hooks, or API functions from modules
  3288. * listed as dependencies, since these may not be available or work as expected
  3289. * when the module is disabled.)
  3290. *
  3291. * @see hook_install()
  3292. * @see hook_schema()
  3293. * @see hook_disable()
  3294. * @see hook_modules_uninstalled()
  3295. */
  3296. function hook_uninstall() {
  3297. variable_del('upload_file_types');
  3298. }
  3299. /**
  3300. * Perform necessary actions after module is enabled.
  3301. *
  3302. * The hook is called every time the module is enabled. It should be
  3303. * implemented in the module's .install file. The implementation can
  3304. * rely on the .module file being loaded.
  3305. *
  3306. * @see module_enable()
  3307. * @see hook_install()
  3308. * @see hook_modules_enabled()
  3309. */
  3310. function hook_enable() {
  3311. mymodule_cache_rebuild();
  3312. }
  3313. /**
  3314. * Perform necessary actions before module is disabled.
  3315. *
  3316. * The hook is called every time the module is disabled. It should be
  3317. * implemented in the module's .install file. The implementation can rely
  3318. * on the .module file being loaded.
  3319. *
  3320. * @see hook_uninstall()
  3321. * @see hook_modules_disabled()
  3322. */
  3323. function hook_disable() {
  3324. mymodule_cache_rebuild();
  3325. }
  3326. /**
  3327. * Perform necessary alterations to the list of files parsed by the registry.
  3328. *
  3329. * Modules can manually modify the list of files before the registry parses
  3330. * them. The $modules array provides the .info file information, which includes
  3331. * the list of files registered to each module. Any files in the list can then
  3332. * be added to the list of files that the registry will parse, or modify
  3333. * attributes of a file.
  3334. *
  3335. * A necessary alteration made by the core SimpleTest module is to force .test
  3336. * files provided by disabled modules into the list of files parsed by the
  3337. * registry.
  3338. *
  3339. * @param $files
  3340. * List of files to be parsed by the registry. The list will contain
  3341. * files found in each enabled module's info file and the core includes
  3342. * directory. The array is keyed by the file path and contains an array of
  3343. * the related module's name and weight as used internally by
  3344. * _registry_update() and related functions.
  3345. *
  3346. * For example:
  3347. * @code
  3348. * $files["modules/system/system.module"] = array(
  3349. * 'module' => 'system',
  3350. * 'weight' => 0,
  3351. * );
  3352. * @endcode
  3353. * @param $modules
  3354. * An array containing all module information stored in the {system} table.
  3355. * Each element of the array also contains the module's .info file
  3356. * information in the property 'info'. An additional 'dir' property has been
  3357. * added to the module information which provides the path to the directory
  3358. * in which the module resides. The example shows how to take advantage of
  3359. * both properties.
  3360. *
  3361. * @see _registry_update()
  3362. * @see simpletest_test_get_all()
  3363. */
  3364. function hook_registry_files_alter(&$files, $modules) {
  3365. foreach ($modules as $module) {
  3366. // Only add test files for disabled modules, as enabled modules should
  3367. // already include any test files they provide.
  3368. if (!$module->status) {
  3369. $dir = $module->dir;
  3370. foreach ($module->info['files'] as $file) {
  3371. if (substr($file, -5) == '.test') {
  3372. $files["$dir/$file"] = array('module' => $module->name, 'weight' => $module->weight);
  3373. }
  3374. }
  3375. }
  3376. }
  3377. }
  3378. /**
  3379. * Return an array of tasks to be performed by an installation profile.
  3380. *
  3381. * Any tasks you define here will be run, in order, after the installer has
  3382. * finished the site configuration step but before it has moved on to the
  3383. * final import of languages and the end of the installation. You can have any
  3384. * number of custom tasks to perform during this phase.
  3385. *
  3386. * Each task you define here corresponds to a callback function which you must
  3387. * separately define and which is called when your task is run. This function
  3388. * will receive the global installation state variable, $install_state, as
  3389. * input, and has the opportunity to access or modify any of its settings. See
  3390. * the install_state_defaults() function in the installer for the list of
  3391. * $install_state settings used by Drupal core.
  3392. *
  3393. * At the end of your task function, you can indicate that you want the
  3394. * installer to pause and display a page to the user by returning any themed
  3395. * output that should be displayed on that page (but see below for tasks that
  3396. * use the form API or batch API; the return values of these task functions are
  3397. * handled differently). You should also use drupal_set_title() within the task
  3398. * callback function to set a custom page title. For some tasks, however, you
  3399. * may want to simply do some processing and pass control to the next task
  3400. * without ending the page request; to indicate this, simply do not send back
  3401. * a return value from your task function at all. This can be used, for
  3402. * example, by installation profiles that need to configure certain site
  3403. * settings in the database without obtaining any input from the user.
  3404. *
  3405. * The task function is treated specially if it defines a form or requires
  3406. * batch processing; in that case, you should return either the form API
  3407. * definition or batch API array, as appropriate. See below for more
  3408. * information on the 'type' key that you must define in the task definition
  3409. * to inform the installer that your task falls into one of those two
  3410. * categories. It is important to use these APIs directly, since the installer
  3411. * may be run non-interactively (for example, via a command line script), all
  3412. * in one page request; in that case, the installer will automatically take
  3413. * care of submitting forms and processing batches correctly for both types of
  3414. * installations. You can inspect the $install_state['interactive'] boolean to
  3415. * see whether or not the current installation is interactive, if you need
  3416. * access to this information.
  3417. *
  3418. * Remember that a user installing Drupal interactively will be able to reload
  3419. * an installation page multiple times, so you should use variable_set() and
  3420. * variable_get() if you are collecting any data that you need to store and
  3421. * inspect later. It is important to remove any temporary variables using
  3422. * variable_del() before your last task has completed and control is handed
  3423. * back to the installer.
  3424. *
  3425. * @return
  3426. * A keyed array of tasks the profile will perform during the final stage of
  3427. * the installation. Each key represents the name of a function (usually a
  3428. * function defined by this profile, although that is not strictly required)
  3429. * that is called when that task is run. The values are associative arrays
  3430. * containing the following key-value pairs (all of which are optional):
  3431. * - 'display_name'
  3432. * The human-readable name of the task. This will be displayed to the
  3433. * user while the installer is running, along with a list of other tasks
  3434. * that are being run. Leave this unset to prevent the task from
  3435. * appearing in the list.
  3436. * - 'display'
  3437. * This is a boolean which can be used to provide finer-grained control
  3438. * over whether or not the task will display. This is mostly useful for
  3439. * tasks that are intended to display only under certain conditions; for
  3440. * these tasks, you can set 'display_name' to the name that you want to
  3441. * display, but then use this boolean to hide the task only when certain
  3442. * conditions apply.
  3443. * - 'type'
  3444. * A string representing the type of task. This parameter has three
  3445. * possible values:
  3446. * - 'normal': This indicates that the task will be treated as a regular
  3447. * callback function, which does its processing and optionally returns
  3448. * HTML output. This is the default behavior which is used when 'type' is
  3449. * not set.
  3450. * - 'batch': This indicates that the task function will return a batch
  3451. * API definition suitable for batch_set(). The installer will then take
  3452. * care of automatically running the task via batch processing.
  3453. * - 'form': This indicates that the task function will return a standard
  3454. * form API definition (and separately define validation and submit
  3455. * handlers, as appropriate). The installer will then take care of
  3456. * automatically directing the user through the form submission process.
  3457. * - 'run'
  3458. * A constant representing the manner in which the task will be run. This
  3459. * parameter has three possible values:
  3460. * - INSTALL_TASK_RUN_IF_NOT_COMPLETED: This indicates that the task will
  3461. * run once during the installation of the profile. This is the default
  3462. * behavior which is used when 'run' is not set.
  3463. * - INSTALL_TASK_SKIP: This indicates that the task will not run during
  3464. * the current installation page request. It can be used to skip running
  3465. * an installation task when certain conditions are met, even though the
  3466. * task may still show on the list of installation tasks presented to the
  3467. * user.
  3468. * - INSTALL_TASK_RUN_IF_REACHED: This indicates that the task will run
  3469. * on each installation page request that reaches it. This is rarely
  3470. * necessary for an installation profile to use; it is primarily used by
  3471. * the Drupal installer for bootstrap-related tasks.
  3472. * - 'function'
  3473. * Normally this does not need to be set, but it can be used to force the
  3474. * installer to call a different function when the task is run (rather
  3475. * than the function whose name is given by the array key). This could be
  3476. * used, for example, to allow the same function to be called by two
  3477. * different tasks.
  3478. *
  3479. * @see install_state_defaults()
  3480. * @see batch_set()
  3481. */
  3482. function hook_install_tasks() {
  3483. // Here, we define a variable to allow tasks to indicate that a particular,
  3484. // processor-intensive batch process needs to be triggered later on in the
  3485. // installation.
  3486. $myprofile_needs_batch_processing = variable_get('myprofile_needs_batch_processing', FALSE);
  3487. $tasks = array(
  3488. // This is an example of a task that defines a form which the user who is
  3489. // installing the site will be asked to fill out. To implement this task,
  3490. // your profile would define a function named myprofile_data_import_form()
  3491. // as a normal form API callback function, with associated validation and
  3492. // submit handlers. In the submit handler, in addition to saving whatever
  3493. // other data you have collected from the user, you might also call
  3494. // variable_set('myprofile_needs_batch_processing', TRUE) if the user has
  3495. // entered data which requires that batch processing will need to occur
  3496. // later on.
  3497. 'myprofile_data_import_form' => array(
  3498. 'display_name' => st('Data import options'),
  3499. 'type' => 'form',
  3500. ),
  3501. // Similarly, to implement this task, your profile would define a function
  3502. // named myprofile_settings_form() with associated validation and submit
  3503. // handlers. This form might be used to collect and save additional
  3504. // information from the user that your profile needs. There are no extra
  3505. // steps required for your profile to act as an "installation wizard"; you
  3506. // can simply define as many tasks of type 'form' as you wish to execute,
  3507. // and the forms will be presented to the user, one after another.
  3508. 'myprofile_settings_form' => array(
  3509. 'display_name' => st('Additional options'),
  3510. 'type' => 'form',
  3511. ),
  3512. // This is an example of a task that performs batch operations. To
  3513. // implement this task, your profile would define a function named
  3514. // myprofile_batch_processing() which returns a batch API array definition
  3515. // that the installer will use to execute your batch operations. Due to the
  3516. // 'myprofile_needs_batch_processing' variable used here, this task will be
  3517. // hidden and skipped unless your profile set it to TRUE in one of the
  3518. // previous tasks.
  3519. 'myprofile_batch_processing' => array(
  3520. 'display_name' => st('Import additional data'),
  3521. 'display' => $myprofile_needs_batch_processing,
  3522. 'type' => 'batch',
  3523. 'run' => $myprofile_needs_batch_processing ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
  3524. ),
  3525. // This is an example of a task that will not be displayed in the list that
  3526. // the user sees. To implement this task, your profile would define a
  3527. // function named myprofile_final_site_setup(), in which additional,
  3528. // automated site setup operations would be performed. Since this is the
  3529. // last task defined by your profile, you should also use this function to
  3530. // call variable_del('myprofile_needs_batch_processing') and clean up the
  3531. // variable that was used above. If you want the user to pass to the final
  3532. // Drupal installation tasks uninterrupted, return no output from this
  3533. // function. Otherwise, return themed output that the user will see (for
  3534. // example, a confirmation page explaining that your profile's tasks are
  3535. // complete, with a link to reload the current page and therefore pass on
  3536. // to the final Drupal installation tasks when the user is ready to do so).
  3537. 'myprofile_final_site_setup' => array(
  3538. ),
  3539. );
  3540. return $tasks;
  3541. }
  3542. /**
  3543. * Change the page the user is sent to by drupal_goto().
  3544. *
  3545. * @param $path
  3546. * A Drupal path or a full URL.
  3547. * @param $options
  3548. * An associative array of additional URL options to pass to url().
  3549. * @param $http_response_code
  3550. * The HTTP status code to use for the redirection. See drupal_goto() for more
  3551. * information.
  3552. */
  3553. function hook_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  3554. // A good addition to misery module.
  3555. $http_response_code = 500;
  3556. }
  3557. /**
  3558. * Alter XHTML HEAD tags before they are rendered by drupal_get_html_head().
  3559. *
  3560. * Elements available to be altered are only those added using
  3561. * drupal_add_html_head_link() or drupal_add_html_head(). CSS and JS files
  3562. * are handled using drupal_add_css() and drupal_add_js(), so the head links
  3563. * for those files will not appear in the $head_elements array.
  3564. *
  3565. * @param $head_elements
  3566. * An array of renderable elements. Generally the values of the #attributes
  3567. * array will be the most likely target for changes.
  3568. */
  3569. function hook_html_head_alter(&$head_elements) {
  3570. foreach ($head_elements as $key => $element) {
  3571. if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
  3572. // I want a custom canonical url.
  3573. $head_elements[$key]['#attributes']['href'] = mymodule_canonical_url();
  3574. }
  3575. }
  3576. }
  3577. /**
  3578. * Alter the full list of installation tasks.
  3579. *
  3580. * @param $tasks
  3581. * An array of all available installation tasks, including those provided by
  3582. * Drupal core. You can modify this array to change or replace any part of
  3583. * the Drupal installation process that occurs after the installation profile
  3584. * is selected.
  3585. * @param $install_state
  3586. * An array of information about the current installation state.
  3587. */
  3588. function hook_install_tasks_alter(&$tasks, $install_state) {
  3589. // Replace the "Choose language" installation task provided by Drupal core
  3590. // with a custom callback function defined by this installation profile.
  3591. $tasks['install_select_locale']['function'] = 'myprofile_locale_selection';
  3592. }
  3593. /**
  3594. * Alter MIME type mappings used to determine MIME type from a file extension.
  3595. *
  3596. * This hook is run when file_mimetype_mapping() is called. It is used to
  3597. * allow modules to add to or modify the default mapping from
  3598. * file_default_mimetype_mapping().
  3599. *
  3600. * @param $mapping
  3601. * An array of mimetypes correlated to the extensions that relate to them.
  3602. * The array has 'mimetypes' and 'extensions' elements, each of which is an
  3603. * array.
  3604. *
  3605. * @see file_default_mimetype_mapping()
  3606. */
  3607. function hook_file_mimetype_mapping_alter(&$mapping) {
  3608. // Add new MIME type 'drupal/info'.
  3609. $mapping['mimetypes']['example_info'] = 'drupal/info';
  3610. // Add new extension '.info' and map it to the 'drupal/info' MIME type.
  3611. $mapping['extensions']['info'] = 'example_info';
  3612. // Override existing extension mapping for '.ogg' files.
  3613. $mapping['extensions']['ogg'] = 189;
  3614. }
  3615. /**
  3616. * Declares information about actions.
  3617. *
  3618. * Any module can define actions, and then call actions_do() to make those
  3619. * actions happen in response to events. The trigger module provides a user
  3620. * interface for associating actions with module-defined triggers, and it makes
  3621. * sure the core triggers fire off actions when their events happen.
  3622. *
  3623. * An action consists of two or three parts:
  3624. * - an action definition (returned by this hook)
  3625. * - a function which performs the action (which by convention is named
  3626. * MODULE_description-of-function_action)
  3627. * - an optional form definition function that defines a configuration form
  3628. * (which has the name of the action function with '_form' appended to it.)
  3629. *
  3630. * The action function takes two to four arguments, which come from the input
  3631. * arguments to actions_do().
  3632. *
  3633. * @return
  3634. * An associative array of action descriptions. The keys of the array
  3635. * are the names of the action functions, and each corresponding value
  3636. * is an associative array with the following key-value pairs:
  3637. * - 'type': The type of object this action acts upon. Core actions have types
  3638. * 'node', 'user', 'comment', and 'system'.
  3639. * - 'label': The human-readable name of the action, which should be passed
  3640. * through the t() function for translation.
  3641. * - 'configurable': If FALSE, then the action doesn't require any extra
  3642. * configuration. If TRUE, then your module must define a form function with
  3643. * the same name as the action function with '_form' appended (e.g., the
  3644. * form for 'node_assign_owner_action' is 'node_assign_owner_action_form'.)
  3645. * This function takes $context as its only parameter, and is paired with
  3646. * the usual _submit function, and possibly a _validate function.
  3647. * - 'triggers': An array of the events (that is, hooks) that can trigger this
  3648. * action. For example: array('node_insert', 'user_update'). You can also
  3649. * declare support for any trigger by returning array('any') for this value.
  3650. * - 'behavior': (optional) A machine-readable array of behaviors of this
  3651. * action, used to signal additionally required actions that may need to be
  3652. * triggered. Currently recognized behaviors by Trigger module:
  3653. * - 'changes_property': If an action with this behavior is assigned to a
  3654. * trigger other than a "presave" hook, any save actions also assigned to
  3655. * this trigger are moved later in the list. If no save action is present,
  3656. * one will be added.
  3657. * Modules that are processing actions (like Trigger module) should take
  3658. * special care for the "presave" hook, in which case a dependent "save"
  3659. * action should NOT be invoked.
  3660. *
  3661. * @ingroup actions
  3662. */
  3663. function hook_action_info() {
  3664. return array(
  3665. 'comment_unpublish_action' => array(
  3666. 'type' => 'comment',
  3667. 'label' => t('Unpublish comment'),
  3668. 'configurable' => FALSE,
  3669. 'behavior' => array('changes_property'),
  3670. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  3671. ),
  3672. 'comment_unpublish_by_keyword_action' => array(
  3673. 'type' => 'comment',
  3674. 'label' => t('Unpublish comment containing keyword(s)'),
  3675. 'configurable' => TRUE,
  3676. 'behavior' => array('changes_property'),
  3677. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  3678. ),
  3679. 'comment_save_action' => array(
  3680. 'type' => 'comment',
  3681. 'label' => t('Save comment'),
  3682. 'configurable' => FALSE,
  3683. 'triggers' => array('comment_insert', 'comment_update'),
  3684. ),
  3685. );
  3686. }
  3687. /**
  3688. * Executes code after an action is deleted.
  3689. *
  3690. * @param $aid
  3691. * The action ID.
  3692. */
  3693. function hook_actions_delete($aid) {
  3694. db_delete('actions_assignments')
  3695. ->condition('aid', $aid)
  3696. ->execute();
  3697. }
  3698. /**
  3699. * Alters the actions declared by another module.
  3700. *
  3701. * Called by actions_list() to allow modules to alter the return values from
  3702. * implementations of hook_action_info().
  3703. *
  3704. * @see trigger_example_action_info_alter()
  3705. */
  3706. function hook_action_info_alter(&$actions) {
  3707. $actions['node_unpublish_action']['label'] = t('Unpublish and remove from public view.');
  3708. }
  3709. /**
  3710. * Declare archivers to the system.
  3711. *
  3712. * An archiver is a class that is able to package and unpackage one or more files
  3713. * into a single possibly compressed file. Common examples of such files are
  3714. * zip files and tar.gz files. All archiver classes must implement
  3715. * ArchiverInterface.
  3716. *
  3717. * Each entry should be keyed on a unique value, and specify three
  3718. * additional keys:
  3719. * - class: The name of the PHP class for this archiver.
  3720. * - extensions: An array of file extensions that this archiver supports.
  3721. * - weight: This optional key specifies the weight of this archiver.
  3722. * When mapping file extensions to archivers, the first archiver by
  3723. * weight found that supports the requested extension will be used.
  3724. *
  3725. * @see hook_archiver_info_alter()
  3726. */
  3727. function hook_archiver_info() {
  3728. return array(
  3729. 'tar' => array(
  3730. 'class' => 'ArchiverTar',
  3731. 'extensions' => array('tar', 'tar.gz', 'tar.bz2'),
  3732. ),
  3733. );
  3734. }
  3735. /**
  3736. * Alter archiver information declared by other modules.
  3737. *
  3738. * See hook_archiver_info() for a description of archivers and the archiver
  3739. * information structure.
  3740. *
  3741. * @param $info
  3742. * Archiver information to alter (return values from hook_archiver_info()).
  3743. */
  3744. function hook_archiver_info_alter(&$info) {
  3745. $info['tar']['extensions'][] = 'tgz';
  3746. }
  3747. /**
  3748. * Define additional date types.
  3749. *
  3750. * Next to the 'long', 'medium' and 'short' date types defined in core, any
  3751. * module can define additional types that can be used when displaying dates,
  3752. * by implementing this hook. A date type is basically just a name for a date
  3753. * format.
  3754. *
  3755. * Date types are used in the administration interface: a user can assign
  3756. * date format types defined in hook_date_formats() to date types defined in
  3757. * this hook. Once a format has been assigned by a user, the machine name of a
  3758. * type can be used in the format_date() function to format a date using the
  3759. * chosen formatting.
  3760. *
  3761. * To define a date type in a module and make sure a format has been assigned to
  3762. * it, without requiring a user to visit the administrative interface, use
  3763. * @code variable_set('date_format_' . $type, $format); @endcode
  3764. * where $type is the machine-readable name defined here, and $format is a PHP
  3765. * date format string.
  3766. *
  3767. * To avoid namespace collisions with date types defined by other modules, it is
  3768. * recommended that each date type starts with the module name. A date type
  3769. * can consist of letters, numbers and underscores.
  3770. *
  3771. * @return
  3772. * An array of date types where the keys are the machine-readable names and
  3773. * the values are the human-readable labels.
  3774. *
  3775. * @see hook_date_formats()
  3776. * @see format_date()
  3777. */
  3778. function hook_date_format_types() {
  3779. // Define the core date format types.
  3780. return array(
  3781. 'long' => t('Long'),
  3782. 'medium' => t('Medium'),
  3783. 'short' => t('Short'),
  3784. );
  3785. }
  3786. /**
  3787. * Modify existing date types.
  3788. *
  3789. * Allows other modules to modify existing date types like 'long'. Called by
  3790. * _system_date_format_types_build(). For instance, A module may use this hook
  3791. * to apply settings across all date types, such as locking all date types so
  3792. * they appear to be provided by the system.
  3793. *
  3794. * @param $types
  3795. * A list of date types. Each date type is keyed by the machine-readable name
  3796. * and the values are associative arrays containing:
  3797. * - is_new: Set to FALSE to override previous settings.
  3798. * - module: The name of the module that created the date type.
  3799. * - type: The machine-readable date type name.
  3800. * - title: The human-readable date type name.
  3801. * - locked: Specifies that the date type is system-provided.
  3802. */
  3803. function hook_date_format_types_alter(&$types) {
  3804. foreach ($types as $name => $type) {
  3805. $types[$name]['locked'] = 1;
  3806. }
  3807. }
  3808. /**
  3809. * Define additional date formats.
  3810. *
  3811. * This hook is used to define the PHP date format strings that can be assigned
  3812. * to date types in the administrative interface. A module can provide date
  3813. * format strings for the core-provided date types ('long', 'medium', and
  3814. * 'short'), or for date types defined in hook_date_format_types() by itself
  3815. * or another module.
  3816. *
  3817. * Since date formats can be locale-specific, you can specify the locales that
  3818. * each date format string applies to. There may be more than one locale for a
  3819. * format. There may also be more than one format for the same locale. For
  3820. * example d/m/Y and Y/m/d work equally well in some locales. You may wish to
  3821. * define some additional date formats that aren't specific to any one locale,
  3822. * for example, "Y m". For these cases, the 'locales' component of the return
  3823. * value should be omitted.
  3824. *
  3825. * Providing a date format here does not normally assign the format to be
  3826. * used with the associated date type -- a user has to choose a format for each
  3827. * date type in the administrative interface. There is one exception: locale
  3828. * initialization chooses a locale-specific format for the three core-provided
  3829. * types (see locale_get_localized_date_format() for details). If your module
  3830. * needs to ensure that a date type it defines has a format associated with it,
  3831. * call @code variable_set('date_format_' . $type, $format); @endcode
  3832. * where $type is the machine-readable name defined in hook_date_format_types(),
  3833. * and $format is a PHP date format string.
  3834. *
  3835. * @return
  3836. * A list of date formats to offer as choices in the administrative
  3837. * interface. Each date format is a keyed array consisting of three elements:
  3838. * - 'type': The date type name that this format can be used with, as
  3839. * declared in an implementation of hook_date_format_types().
  3840. * - 'format': A PHP date format string to use when formatting dates. It
  3841. * can contain any of the formatting options described at
  3842. * http://php.net/manual/en/function.date.php
  3843. * - 'locales': (optional) An array of 2 and 5 character locale codes,
  3844. * defining which locales this format applies to (for example, 'en',
  3845. * 'en-us', etc.). If your date format is not language-specific, leave this
  3846. * array empty.
  3847. *
  3848. * @see hook_date_format_types()
  3849. */
  3850. function hook_date_formats() {
  3851. return array(
  3852. array(
  3853. 'type' => 'mymodule_extra_long',
  3854. 'format' => 'l jS F Y H:i:s e',
  3855. 'locales' => array('en-ie'),
  3856. ),
  3857. array(
  3858. 'type' => 'mymodule_extra_long',
  3859. 'format' => 'l jS F Y h:i:sa',
  3860. 'locales' => array('en', 'en-us'),
  3861. ),
  3862. array(
  3863. 'type' => 'short',
  3864. 'format' => 'F Y',
  3865. 'locales' => array(),
  3866. ),
  3867. );
  3868. }
  3869. /**
  3870. * Alter date formats declared by another module.
  3871. *
  3872. * Called by _system_date_format_types_build() to allow modules to alter the
  3873. * return values from implementations of hook_date_formats().
  3874. */
  3875. function hook_date_formats_alter(&$formats) {
  3876. foreach ($formats as $id => $format) {
  3877. $formats[$id]['locales'][] = 'en-ca';
  3878. }
  3879. }
  3880. /**
  3881. * Alters the delivery callback used to send the result of the page callback to the browser.
  3882. *
  3883. * Called by drupal_deliver_page() to allow modules to alter how the
  3884. * page is delivered to the browser.
  3885. *
  3886. * This hook is intended for altering the delivery callback based on
  3887. * information unrelated to the path of the page accessed. For example,
  3888. * it can be used to set the delivery callback based on a HTTP request
  3889. * header (as shown in the code sample). To specify a delivery callback
  3890. * based on path information, use hook_menu() or hook_menu_alter().
  3891. *
  3892. * This hook can also be used as an API function that can be used to explicitly
  3893. * set the delivery callback from some other function. For example, for a module
  3894. * named MODULE:
  3895. * @code
  3896. * function MODULE_page_delivery_callback_alter(&$callback, $set = FALSE) {
  3897. * static $stored_callback;
  3898. * if ($set) {
  3899. * $stored_callback = $callback;
  3900. * }
  3901. * elseif (isset($stored_callback)) {
  3902. * $callback = $stored_callback;
  3903. * }
  3904. * }
  3905. * function SOMEWHERE_ELSE() {
  3906. * $desired_delivery_callback = 'foo';
  3907. * MODULE_page_delivery_callback_alter($desired_delivery_callback, TRUE);
  3908. * }
  3909. * @endcode
  3910. *
  3911. * @param $callback
  3912. * The name of a function.
  3913. *
  3914. * @see drupal_deliver_page()
  3915. */
  3916. function hook_page_delivery_callback_alter(&$callback) {
  3917. // jQuery sets a HTTP_X_REQUESTED_WITH header of 'XMLHttpRequest'.
  3918. // If a page would normally be delivered as an html page, and it is called
  3919. // from jQuery, deliver it instead as an Ajax response.
  3920. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && $callback == 'drupal_deliver_html_page') {
  3921. $callback = 'ajax_deliver';
  3922. }
  3923. }
  3924. /**
  3925. * Alters theme operation links.
  3926. *
  3927. * @param $theme_groups
  3928. * An associative array containing groups of themes.
  3929. *
  3930. * @see system_themes_page()
  3931. */
  3932. function hook_system_themes_page_alter(&$theme_groups) {
  3933. foreach ($theme_groups as $state => &$group) {
  3934. foreach ($theme_groups[$state] as &$theme) {
  3935. // Add a foo link to each list of theme operations.
  3936. $theme->operations[] = array(
  3937. 'title' => t('Foo'),
  3938. 'href' => 'admin/appearance/foo',
  3939. 'query' => array('theme' => $theme->name)
  3940. );
  3941. }
  3942. }
  3943. }
  3944. /**
  3945. * Alters inbound URL requests.
  3946. *
  3947. * @param $path
  3948. * The path being constructed, which, if a path alias, has been resolved to a
  3949. * Drupal path by the database, and which also may have been altered by other
  3950. * modules before this one.
  3951. * @param $original_path
  3952. * The original path, before being checked for path aliases or altered by any
  3953. * modules.
  3954. * @param $path_language
  3955. * The language of the path.
  3956. *
  3957. * @see drupal_get_normal_path()
  3958. */
  3959. function hook_url_inbound_alter(&$path, $original_path, $path_language) {
  3960. // Create the path user/me/edit, which allows a user to edit their account.
  3961. if (preg_match('|^user/me/edit(/.*)?|', $path, $matches)) {
  3962. global $user;
  3963. $path = 'user/' . $user->uid . '/edit' . $matches[1];
  3964. }
  3965. }
  3966. /**
  3967. * Alters outbound URLs.
  3968. *
  3969. * @param $path
  3970. * The outbound path to alter, not adjusted for path aliases yet. It won't be
  3971. * adjusted for path aliases until all modules are finished altering it, thus
  3972. * being consistent with hook_url_inbound_alter(), which adjusts for all path
  3973. * aliases before allowing modules to alter it. This may have been altered by
  3974. * other modules before this one.
  3975. * @param $options
  3976. * A set of URL options for the URL so elements such as a fragment or a query
  3977. * string can be added to the URL.
  3978. * @param $original_path
  3979. * The original path, before being altered by any modules.
  3980. *
  3981. * @see url()
  3982. */
  3983. function hook_url_outbound_alter(&$path, &$options, $original_path) {
  3984. // Use an external RSS feed rather than the Drupal one.
  3985. if ($path == 'rss.xml') {
  3986. $path = 'http://example.com/rss.xml';
  3987. $options['external'] = TRUE;
  3988. }
  3989. // Instead of pointing to user/[uid]/edit, point to user/me/edit.
  3990. if (preg_match('|^user/([0-9]*)/edit(/.*)?|', $path, $matches)) {
  3991. global $user;
  3992. if ($user->uid == $matches[1]) {
  3993. $path = 'user/me/edit' . $matches[2];
  3994. }
  3995. }
  3996. }
  3997. /**
  3998. * Alter the username that is displayed for a user.
  3999. *
  4000. * Called by format_username() to allow modules to alter the username that's
  4001. * displayed. Can be used to ensure user privacy in situations where
  4002. * $account->name is too revealing.
  4003. *
  4004. * @param $name
  4005. * The string that format_username() will return.
  4006. *
  4007. * @param $account
  4008. * The account object passed to format_username().
  4009. *
  4010. * @see format_username()
  4011. */
  4012. function hook_username_alter(&$name, $account) {
  4013. // Display the user's uid instead of name.
  4014. if (isset($account->uid)) {
  4015. $name = t('User !uid', array('!uid' => $account->uid));
  4016. }
  4017. }
  4018. /**
  4019. * Provide replacement values for placeholder tokens.
  4020. *
  4021. * This hook is invoked when someone calls token_replace(). That function first
  4022. * scans the text for [type:token] patterns, and splits the needed tokens into
  4023. * groups by type. Then hook_tokens() is invoked on each token-type group,
  4024. * allowing your module to respond by providing replacement text for any of
  4025. * the tokens in the group that your module knows how to process.
  4026. *
  4027. * A module implementing this hook should also implement hook_token_info() in
  4028. * order to list its available tokens on editing screens.
  4029. *
  4030. * @param $type
  4031. * The machine-readable name of the type (group) of token being replaced, such
  4032. * as 'node', 'user', or another type defined by a hook_token_info()
  4033. * implementation.
  4034. * @param $tokens
  4035. * An array of tokens to be replaced. The keys are the machine-readable token
  4036. * names, and the values are the raw [type:token] strings that appeared in the
  4037. * original text.
  4038. * @param $data
  4039. * (optional) An associative array of data objects to be used when generating
  4040. * replacement values, as supplied in the $data parameter to token_replace().
  4041. * @param $options
  4042. * (optional) An associative array of options for token replacement; see
  4043. * token_replace() for possible values.
  4044. *
  4045. * @return
  4046. * An associative array of replacement values, keyed by the raw [type:token]
  4047. * strings from the original text.
  4048. *
  4049. * @see hook_token_info()
  4050. * @see hook_tokens_alter()
  4051. */
  4052. function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
  4053. $url_options = array('absolute' => TRUE);
  4054. if (isset($options['language'])) {
  4055. $url_options['language'] = $options['language'];
  4056. $language_code = $options['language']->language;
  4057. }
  4058. else {
  4059. $language_code = NULL;
  4060. }
  4061. $sanitize = !empty($options['sanitize']);
  4062. $replacements = array();
  4063. if ($type == 'node' && !empty($data['node'])) {
  4064. $node = $data['node'];
  4065. foreach ($tokens as $name => $original) {
  4066. switch ($name) {
  4067. // Simple key values on the node.
  4068. case 'nid':
  4069. $replacements[$original] = $node->nid;
  4070. break;
  4071. case 'title':
  4072. $replacements[$original] = $sanitize ? check_plain($node->title) : $node->title;
  4073. break;
  4074. case 'edit-url':
  4075. $replacements[$original] = url('node/' . $node->nid . '/edit', $url_options);
  4076. break;
  4077. // Default values for the chained tokens handled below.
  4078. case 'author':
  4079. $name = ($node->uid == 0) ? variable_get('anonymous', t('Anonymous')) : $node->name;
  4080. $replacements[$original] = $sanitize ? filter_xss($name) : $name;
  4081. break;
  4082. case 'created':
  4083. $replacements[$original] = format_date($node->created, 'medium', '', NULL, $language_code);
  4084. break;
  4085. }
  4086. }
  4087. if ($author_tokens = token_find_with_prefix($tokens, 'author')) {
  4088. $author = user_load($node->uid);
  4089. $replacements += token_generate('user', $author_tokens, array('user' => $author), $options);
  4090. }
  4091. if ($created_tokens = token_find_with_prefix($tokens, 'created')) {
  4092. $replacements += token_generate('date', $created_tokens, array('date' => $node->created), $options);
  4093. }
  4094. }
  4095. return $replacements;
  4096. }
  4097. /**
  4098. * Alter replacement values for placeholder tokens.
  4099. *
  4100. * @param $replacements
  4101. * An associative array of replacements returned by hook_tokens().
  4102. * @param $context
  4103. * The context in which hook_tokens() was called. An associative array with
  4104. * the following keys, which have the same meaning as the corresponding
  4105. * parameters of hook_tokens():
  4106. * - 'type'
  4107. * - 'tokens'
  4108. * - 'data'
  4109. * - 'options'
  4110. *
  4111. * @see hook_tokens()
  4112. */
  4113. function hook_tokens_alter(array &$replacements, array $context) {
  4114. $options = $context['options'];
  4115. if (isset($options['language'])) {
  4116. $url_options['language'] = $options['language'];
  4117. $language_code = $options['language']->language;
  4118. }
  4119. else {
  4120. $language_code = NULL;
  4121. }
  4122. $sanitize = !empty($options['sanitize']);
  4123. if ($context['type'] == 'node' && !empty($context['data']['node'])) {
  4124. $node = $context['data']['node'];
  4125. // Alter the [node:title] token, and replace it with the rendered content
  4126. // of a field (field_title).
  4127. if (isset($context['tokens']['title'])) {
  4128. $title = field_view_field('node', $node, 'field_title', 'default', $language_code);
  4129. $replacements[$context['tokens']['title']] = drupal_render($title);
  4130. }
  4131. }
  4132. }
  4133. /**
  4134. * Provide information about available placeholder tokens and token types.
  4135. *
  4136. * Tokens are placeholders that can be put into text by using the syntax
  4137. * [type:token], where type is the machine-readable name of a token type, and
  4138. * token is the machine-readable name of a token within this group. This hook
  4139. * provides a list of types and tokens to be displayed on text editing screens,
  4140. * so that people editing text can see what their token options are.
  4141. *
  4142. * The actual token replacement is done by token_replace(), which invokes
  4143. * hook_tokens(). Your module will need to implement that hook in order to
  4144. * generate token replacements from the tokens defined here.
  4145. *
  4146. * @return
  4147. * An associative array of available tokens and token types. The outer array
  4148. * has two components:
  4149. * - types: An associative array of token types (groups). Each token type is
  4150. * an associative array with the following components:
  4151. * - name: The translated human-readable short name of the token type.
  4152. * - description: A translated longer description of the token type.
  4153. * - needs-data: The type of data that must be provided to token_replace()
  4154. * in the $data argument (i.e., the key name in $data) in order for tokens
  4155. * of this type to be used in the $text being processed. For instance, if
  4156. * the token needs a node object, 'needs-data' should be 'node', and to
  4157. * use this token in token_replace(), the caller needs to supply a node
  4158. * object as $data['node']. Some token data can also be supplied
  4159. * indirectly; for instance, a node object in $data supplies a user object
  4160. * (the author of the node), allowing user tokens to be used when only
  4161. * a node data object is supplied.
  4162. * - tokens: An associative array of tokens. The outer array is keyed by the
  4163. * group name (the same key as in the types array). Within each group of
  4164. * tokens, each token item is keyed by the machine name of the token, and
  4165. * each token item has the following components:
  4166. * - name: The translated human-readable short name of the token.
  4167. * - description: A translated longer description of the token.
  4168. * - type (optional): A 'needs-data' data type supplied by this token, which
  4169. * should match a 'needs-data' value from another token type. For example,
  4170. * the node author token provides a user object, which can then be used
  4171. * for token replacement data in token_replace() without having to supply
  4172. * a separate user object.
  4173. *
  4174. * @see hook_token_info_alter()
  4175. * @see hook_tokens()
  4176. */
  4177. function hook_token_info() {
  4178. $type = array(
  4179. 'name' => t('Nodes'),
  4180. 'description' => t('Tokens related to individual nodes.'),
  4181. 'needs-data' => 'node',
  4182. );
  4183. // Core tokens for nodes.
  4184. $node['nid'] = array(
  4185. 'name' => t("Node ID"),
  4186. 'description' => t("The unique ID of the node."),
  4187. );
  4188. $node['title'] = array(
  4189. 'name' => t("Title"),
  4190. 'description' => t("The title of the node."),
  4191. );
  4192. $node['edit-url'] = array(
  4193. 'name' => t("Edit URL"),
  4194. 'description' => t("The URL of the node's edit page."),
  4195. );
  4196. // Chained tokens for nodes.
  4197. $node['created'] = array(
  4198. 'name' => t("Date created"),
  4199. 'description' => t("The date the node was posted."),
  4200. 'type' => 'date',
  4201. );
  4202. $node['author'] = array(
  4203. 'name' => t("Author"),
  4204. 'description' => t("The author of the node."),
  4205. 'type' => 'user',
  4206. );
  4207. return array(
  4208. 'types' => array('node' => $type),
  4209. 'tokens' => array('node' => $node),
  4210. );
  4211. }
  4212. /**
  4213. * Alter the metadata about available placeholder tokens and token types.
  4214. *
  4215. * @param $data
  4216. * The associative array of token definitions from hook_token_info().
  4217. *
  4218. * @see hook_token_info()
  4219. */
  4220. function hook_token_info_alter(&$data) {
  4221. // Modify description of node tokens for our site.
  4222. $data['tokens']['node']['nid'] = array(
  4223. 'name' => t("Node ID"),
  4224. 'description' => t("The unique ID of the article."),
  4225. );
  4226. $data['tokens']['node']['title'] = array(
  4227. 'name' => t("Title"),
  4228. 'description' => t("The title of the article."),
  4229. );
  4230. // Chained tokens for nodes.
  4231. $data['tokens']['node']['created'] = array(
  4232. 'name' => t("Date created"),
  4233. 'description' => t("The date the article was posted."),
  4234. 'type' => 'date',
  4235. );
  4236. }
  4237. /**
  4238. * Alter batch information before a batch is processed.
  4239. *
  4240. * Called by batch_process() to allow modules to alter a batch before it is
  4241. * processed.
  4242. *
  4243. * @param $batch
  4244. * The associative array of batch information. See batch_set() for details on
  4245. * what this could contain.
  4246. *
  4247. * @see batch_set()
  4248. * @see batch_process()
  4249. *
  4250. * @ingroup batch
  4251. */
  4252. function hook_batch_alter(&$batch) {
  4253. // If the current page request is inside the overlay, add ?render=overlay to
  4254. // the success callback URL, so that it appears correctly within the overlay.
  4255. if (overlay_get_mode() == 'child') {
  4256. if (isset($batch['url_options']['query'])) {
  4257. $batch['url_options']['query']['render'] = 'overlay';
  4258. }
  4259. else {
  4260. $batch['url_options']['query'] = array('render' => 'overlay');
  4261. }
  4262. }
  4263. }
  4264. /**
  4265. * Provide information on Updaters (classes that can update Drupal).
  4266. *
  4267. * An Updater is a class that knows how to update various parts of the Drupal
  4268. * file system, for example to update modules that have newer releases, or to
  4269. * install a new theme.
  4270. *
  4271. * @return
  4272. * An associative array of information about the updater(s) being provided.
  4273. * This array is keyed by a unique identifier for each updater, and the
  4274. * values are subarrays that can contain the following keys:
  4275. * - class: The name of the PHP class which implements this updater.
  4276. * - name: Human-readable name of this updater.
  4277. * - weight: Controls what order the Updater classes are consulted to decide
  4278. * which one should handle a given task. When an update task is being run,
  4279. * the system will loop through all the Updater classes defined in this
  4280. * registry in weight order and let each class respond to the task and
  4281. * decide if each Updater wants to handle the task. In general, this
  4282. * doesn't matter, but if you need to override an existing Updater, make
  4283. * sure your Updater has a lighter weight so that it comes first.
  4284. *
  4285. * @see drupal_get_updaters()
  4286. * @see hook_updater_info_alter()
  4287. */
  4288. function hook_updater_info() {
  4289. return array(
  4290. 'module' => array(
  4291. 'class' => 'ModuleUpdater',
  4292. 'name' => t('Update modules'),
  4293. 'weight' => 0,
  4294. ),
  4295. 'theme' => array(
  4296. 'class' => 'ThemeUpdater',
  4297. 'name' => t('Update themes'),
  4298. 'weight' => 0,
  4299. ),
  4300. );
  4301. }
  4302. /**
  4303. * Alter the Updater information array.
  4304. *
  4305. * An Updater is a class that knows how to update various parts of the Drupal
  4306. * file system, for example to update modules that have newer releases, or to
  4307. * install a new theme.
  4308. *
  4309. * @param array $updaters
  4310. * Associative array of updaters as defined through hook_updater_info().
  4311. * Alter this array directly.
  4312. *
  4313. * @see drupal_get_updaters()
  4314. * @see hook_updater_info()
  4315. */
  4316. function hook_updater_info_alter(&$updaters) {
  4317. // Adjust weight so that the theme Updater gets a chance to handle a given
  4318. // update task before module updaters.
  4319. $updaters['theme']['weight'] = -1;
  4320. }
  4321. /**
  4322. * Alter the default country list.
  4323. *
  4324. * @param $countries
  4325. * The associative array of countries keyed by ISO 3166-1 country code.
  4326. *
  4327. * @see country_get_list()
  4328. * @see _country_get_predefined_list()
  4329. */
  4330. function hook_countries_alter(&$countries) {
  4331. // Elbonia is now independent, so add it to the country list.
  4332. $countries['EB'] = 'Elbonia';
  4333. }
  4334. /**
  4335. * Control site status before menu dispatching.
  4336. *
  4337. * The hook is called after checking whether the site is offline but before
  4338. * the current router item is retrieved and executed by
  4339. * menu_execute_active_handler(). If the site is in offline mode,
  4340. * $menu_site_status is set to MENU_SITE_OFFLINE.
  4341. *
  4342. * @param $menu_site_status
  4343. * Supported values are MENU_SITE_OFFLINE, MENU_ACCESS_DENIED,
  4344. * MENU_NOT_FOUND and MENU_SITE_ONLINE. Any other value than
  4345. * MENU_SITE_ONLINE will skip the default menu handling system and be passed
  4346. * for delivery to drupal_deliver_page() with a NULL
  4347. * $default_delivery_callback.
  4348. * @param $path
  4349. * Contains the system path that is going to be loaded. This is read only,
  4350. * use hook_url_inbound_alter() to change the path.
  4351. */
  4352. function hook_menu_site_status_alter(&$menu_site_status, $path) {
  4353. // Allow access to my_module/authentication even if site is in offline mode.
  4354. if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'my_module/authentication') {
  4355. $menu_site_status = MENU_SITE_ONLINE;
  4356. }
  4357. }
  4358. /**
  4359. * Register information about FileTransfer classes provided by a module.
  4360. *
  4361. * The FileTransfer class allows transferring files over a specific type of
  4362. * connection. Core provides classes for FTP and SSH. Contributed modules are
  4363. * free to extend the FileTransfer base class to add other connection types,
  4364. * and if these classes are registered via hook_filetransfer_info(), those
  4365. * connection types will be available to site administrators using the Update
  4366. * manager when they are redirected to the authorize.php script to authorize
  4367. * the file operations.
  4368. *
  4369. * @return array
  4370. * Nested array of information about FileTransfer classes. Each key is a
  4371. * FileTransfer type (not human readable, used for form elements and
  4372. * variable names, etc), and the values are subarrays that define properties
  4373. * of that type. The keys in each subarray are:
  4374. * - 'title': Required. The human-readable name of the connection type.
  4375. * - 'class': Required. The name of the FileTransfer class. The constructor
  4376. * will always be passed the full path to the root of the site that should
  4377. * be used to restrict where file transfer operations can occur (the $jail)
  4378. * and an array of settings values returned by the settings form.
  4379. * - 'file': Required. The include file containing the FileTransfer class.
  4380. * This should be a separate .inc file, not just the .module file, so that
  4381. * the minimum possible code is loaded when authorize.php is running.
  4382. * - 'file path': Optional. The directory (relative to the Drupal root)
  4383. * where the include file lives. If not defined, defaults to the base
  4384. * directory of the module implementing the hook.
  4385. * - 'weight': Optional. Integer weight used for sorting connection types on
  4386. * the authorize.php form.
  4387. *
  4388. * @see FileTransfer
  4389. * @see authorize.php
  4390. * @see hook_filetransfer_info_alter()
  4391. * @see drupal_get_filetransfer_info()
  4392. */
  4393. function hook_filetransfer_info() {
  4394. $info['sftp'] = array(
  4395. 'title' => t('SFTP (Secure FTP)'),
  4396. 'file' => 'sftp.filetransfer.inc',
  4397. 'class' => 'FileTransferSFTP',
  4398. 'weight' => 10,
  4399. );
  4400. return $info;
  4401. }
  4402. /**
  4403. * Alter the FileTransfer class registry.
  4404. *
  4405. * @param array $filetransfer_info
  4406. * Reference to a nested array containing information about the FileTransfer
  4407. * class registry.
  4408. *
  4409. * @see hook_filetransfer_info()
  4410. */
  4411. function hook_filetransfer_info_alter(&$filetransfer_info) {
  4412. if (variable_get('paranoia', FALSE)) {
  4413. // Remove the FTP option entirely.
  4414. unset($filetransfer_info['ftp']);
  4415. // Make sure the SSH option is listed first.
  4416. $filetransfer_info['ssh']['weight'] = -10;
  4417. }
  4418. }
  4419. /**
  4420. * @} End of "addtogroup hooks".
  4421. */