PageRenderTime 76ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/system/system.api.php

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