PageRenderTime 81ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/system/system.api.php

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