core.php

  1. drupal
    1. 4.6 developer/hooks/core.php
    2. 4.7 developer/hooks/core.php
    3. 5 developer/hooks/core.php
    4. 6 developer/hooks/core.php

These are the hooks that are invoked by the Drupal core.

Core hooks are typically called in all modules at once using module_invoke_all().

Functions & methods

NameDescription
custom_url_rewrite_inboundcustom_url_rewrite_inbound is not a hook, it's a function you can add to settings.php to alter incoming requests so they map to a Drupal path. This function is called before modules are loaded and the menu system is initialized and it changes…
custom_url_rewrite_outboundcustom_url_rewrite_outbound is not a hook, it's a function you can add to settings.php to alter all links generated by Drupal. This function is called from url(). This function is called very frequently (100+ times per page) so performance…
hook_actions_deleteExecute code after an action is deleted.
hook_action_infoDeclare information about one or more Drupal actions.
hook_action_info_alterAlter the actions declared by another module.
hook_blockDeclare a block or set of blocks.
hook_bootPerform setup tasks. See also, hook_init.
hook_commentRespond to comment actions.
hook_cronPerform periodic actions.
hook_db_rewrite_sqlRewrite database queries, usually for access control.
hook_elementsAllows modules to declare their own Forms API element types and specify their default values.
hook_exitPerform cleanup tasks.
hook_file_downloadControl access to private file downloads and specify HTTP headers.
hook_filterDefine content filters.
hook_filter_tipsProvide tips for using filters.
hook_flush_cachesAdd a list of cache tables to be cleared.
hook_footerInsert closing HTML.
hook_formsMap form_ids to builder functions.
hook_form_alterPerform alterations before a form is rendered.
hook_form_FORM_ID_alterProvide a form-specific alteration instead of the global hook_form_alter().
hook_helpProvide online user help.
hook_hook_infoExpose a list of triggers (events) that users can assign actions to.
hook_initPerform setup tasks. See also, hook_boot.
hook_linkDefine internal Drupal links.
hook_link_alterPerform alterations before links on a node or comment are rendered.
hook_localeAllows modules to define their own text groups that can be translated.
hook_mailPrepare a message based on parameters; called from drupal_mail().
hook_mail_alterAlter any aspect of email sent by Drupal. You can use this hook to add a common site footer to all outgoing email, add extra header fields, and/or modify the email in any way. HTML-izing the outgoing email is one possibility. See also drupal_mail().
hook_menuDefine menu items and page callbacks.
hook_menu_alterAlter the data being saved to the {menu_router} table after hook_menu is invoked.
hook_menu_link_alterAlter the data being saved to the {menu_links} table by menu_link_save().
hook_nodeapiAct on nodes defined by other modules.
hook_node_access_recordsSet permissions for a node to be written to the database.
hook_node_grantsInform the node access system what permissions the user has.
hook_node_operationsAdd mass node operations.
hook_openidAllow modules to modify the OpenID request parameters.
hook_permDefine user permissions.
hook_pingPing another server.
hook_preprocessPreprocess theme variables for template files.
hook_preprocess_HOOKPreprocess theme variables for a specific theme hook.
hook_profile_alterAlter profile items before they are rendered.
hook_schema_alterPerforms alterations to existing database schemas.
hook_searchDefine a custom search routine.
hook_search_pageOverride the rendering of search results.
hook_search_preprocessPreprocess text for the search index.
hook_system_info_alterAlter the information parsed from module and theme .info files
hook_taxonomyAct on taxonomy changes.
hook_term_pathAllows modules to provide an alternative path for the terms it manages.
hook_themeRegister a module (or theme's) theme implementations.
hook_theme_registry_alterAlter the theme registry information returned from hook_theme().
hook_translated_menu_link_alterAlter a menu link after it's translated, but before it's rendered.
hook_translation_link_alterPerform alterations on translation links.
hook_update_indexUpdate Drupal's full-text index for this module.
hook_update_projects_alterAlter the list of projects before fetching data and comparing versions.
hook_update_status_alterAlter the information about available updates for projects.
hook_userAct on user account actions.
hook_user_operationsAdd mass user operations.
hook_watchdogLog an event message
hook_xmlrpcRegister XML-RPC callbacks.
page_cache_fastpathOutputs a cached page.

File

developer/hooks/core.php
View source
  1. <?php
  2. /**
  3. * @file
  4. * These are the hooks that are invoked by the Drupal core.
  5. *
  6. * Core hooks are typically called in all modules at once using
  7. * module_invoke_all().
  8. */
  9. /**
  10. * @addtogroup hooks
  11. * @{
  12. */
  13. /**
  14. * Declare information about one or more Drupal actions.
  15. *
  16. * Any module can define any number of Drupal actions. The trigger module is an
  17. * example of a module that uses actions. An action consists of two or three
  18. * parts: (1) an action definition (returned by this hook), (2) a function which
  19. * does the action (which by convention is named module + '_' + description of
  20. * what the function does + '_action'), and an optional form definition
  21. * function that defines a configuration form (which has the name of the action
  22. * with '_form' appended to it.)
  23. *
  24. * @return
  25. * - An array of action descriptions. Each action description is an associative
  26. * array, where the key of the item is the action's function, and the
  27. * following key-value pairs:
  28. * - 'type': (required) the type is determined by what object the action
  29. * acts on. Possible choices are node, user, comment, and system. Or
  30. * whatever your own custom type is. So, for the nodequeue module, the
  31. * type might be set to 'nodequeue' if the action would be performed on a
  32. * nodequeue.
  33. * - 'description': (required) The human-readable name of the action.
  34. * - 'configurable': (required) If FALSE, then the action doesn't require
  35. * any extra configuration. If TRUE, then you should define a form
  36. * function with the same name as the key, but with '_form' appended to
  37. * it (i.e., the form for 'node_assign_owner_action' is
  38. * 'node_assign_owner_action_form'.)
  39. * This function will take the $context as the only parameter, and is
  40. * paired with the usual _submit function, and possibly a _validate
  41. * function.
  42. * - 'hooks': (required) An array of all of the operations this action is
  43. * appropriate for, keyed by hook name. The trigger module uses this to
  44. * filter out inappropriate actions when presenting the interface for
  45. * assigning actions to events. If you are writing actions in your own
  46. * modules and you simply want to declare support for all possible hooks,
  47. * you can set 'hooks' => array('any' => TRUE). Common hooks are 'user',
  48. * 'nodeapi', 'comment', or 'taxonomy'. Any hook that has been described
  49. * to Drupal in hook_hook_info() will work is a possiblity.
  50. * - 'behavior': (optional) Human-readable array of behavior descriptions.
  51. * The only one we have now is 'changes node property'. You will almost
  52. * certainly never have to return this in your own implementations of this
  53. * hook.
  54. *
  55. * The function that is called when the action is triggered is passed two
  56. * parameters - an object of the same type as the 'type' value of the
  57. * hook_action_info array, and a context variable that contains the context
  58. * under which the action is currently running, sent as an array. For example,
  59. * the actions module sets the 'hook' and 'op' keys of the context array (so,
  60. * 'hook' may be 'nodeapi' and 'op' may be 'insert').
  61. *
  62. * @ingroup actions
  63. */
  64. function hook_action_info() {
  65. return array(
  66. 'comment_unpublish_action' => array(
  67. 'description' => t('Unpublish comment'),
  68. 'type' => 'comment',
  69. 'configurable' => FALSE,
  70. 'hooks' => array(
  71. 'comment' => array('insert', 'update'),
  72. )
  73. ),
  74. 'comment_unpublish_by_keyword_action' => array(
  75. 'description' => t('Unpublish comment containing keyword(s)'),
  76. 'type' => 'comment',
  77. 'configurable' => TRUE,
  78. 'hooks' => array(
  79. 'comment' => array('insert', 'update'),
  80. )
  81. )
  82. );
  83. }
  84. /**
  85. * Execute code after an action is deleted.
  86. *
  87. * @param $aid
  88. * The action ID.
  89. */
  90. function hook_actions_delete($aid) {
  91. db_query("DELETE FROM {actions_assignments} WHERE aid = '%s'", $aid);
  92. }
  93. /**
  94. * Alter the actions declared by another module.
  95. *
  96. * Called by actions_list() to allow modules to alter the return
  97. * values from implementations of hook_action_info().
  98. *
  99. * @see trigger_example_action_info_alter().
  100. */
  101. function hook_action_info_alter(&$actions) {
  102. $actions['node_unpublish_action']['description'] = t('Unpublish and remove from public view.');
  103. }
  104. /**
  105. * Declare a block or set of blocks.
  106. *
  107. * Any module can declare a block (or blocks) to be displayed by implementing
  108. * hook_block(), which also allows you to specify any custom configuration
  109. * settings, and how to display the block.
  110. *
  111. * In hook_block(), each block your module provides is given a unique
  112. * identifier referred to as "delta" (the array key in the return value for the
  113. * 'list' operation). Delta values only need to be unique within your module,
  114. * and they are used in the following ways:
  115. * - Passed into the other hook_block() operations as an argument to
  116. * identify the block being configured or viewed.
  117. * - Used to construct the default HTML ID of "block-MODULE-DELTA" applied to
  118. * each block when it is rendered (which can then be used for CSS styling or
  119. * JavaScript programming).
  120. * - Used to define a theming template suggestion of block__MODULE__DELTA, for
  121. * advanced theming possibilities.
  122. * The values of delta can be strings or numbers, but because of the uses above
  123. * it is preferable to use descriptive strings whenever possible, and only use a
  124. * numeric identifier if you have to (for instance if your module allows users
  125. * to create several similar blocks that you identify within your module code
  126. * with numeric IDs).
  127. *
  128. * @param $op
  129. * What kind of information to retrieve about the block or blocks.
  130. * Possible values:
  131. * - 'list': A list of all blocks defined by the module.
  132. * - 'configure': Configuration form for the block.
  133. * - 'save': Save the configuration options.
  134. * - 'view': Process the block when enabled in a region in order to view its
  135. * contents.
  136. * @param $delta
  137. * Which block to return (not applicable if $op is 'list'). See above for more
  138. * information about delta values.
  139. * @param $edit
  140. * If $op is 'save', the submitted form data from the configuration form.
  141. * @return
  142. * - If $op is 'list': An array of block descriptions. Each block description
  143. * is an associative array, with the following key-value pairs:
  144. * - 'info': (required) The human-readable name of the block. This is used
  145. * to identify the block on administration screens, and is not displayed
  146. * to non-administrative users.
  147. * - 'cache': A bitmask of flags describing how the block should behave with
  148. * respect to block caching. The following shortcut bitmasks are provided
  149. * as constants in block.module:
  150. * - BLOCK_CACHE_PER_ROLE (default): The block can change depending on the
  151. * roles the user viewing the page belongs to.
  152. * - BLOCK_CACHE_PER_USER: The block can change depending on the user
  153. * viewing the page. This setting can be resource-consuming for sites
  154. * with large number of users, and should only be used when
  155. * BLOCK_CACHE_PER_ROLE is not sufficient.
  156. * - BLOCK_CACHE_PER_PAGE: The block can change depending on the page
  157. * being viewed.
  158. * - BLOCK_CACHE_GLOBAL: The block is the same for every user on every
  159. * page where it is visible.
  160. * - BLOCK_NO_CACHE: The block should not get cached.
  161. * - 'weight': (optional) Initial value for the ordering weight of this
  162. * block. Most modules do not provide an initial value, and any value
  163. * provided can be modified by a user on the block configuration screen.
  164. * - 'status': (optional) Initial value for block enabled status. (1 =
  165. * enabled, 0 = disabled). Most modules do not provide an initial value,
  166. * and any value provided can be modified by a user on the block
  167. * configuration screen.
  168. * - 'region': (optional) Initial value for theme region within which this
  169. * block is set. Most modules do not provide an initial value, and
  170. * any value provided can be modified by a user on the block configuration
  171. * screen. Note: If you set a region that isn't available in the currently
  172. * enabled theme, the block will be disabled.
  173. * - 'visibility': (optional) Initial value for the visibility flag, which
  174. * tells how to interpret the 'pages' value. Possible values are:
  175. * - 0: Show on all pages except listed pages. 'pages' lists the paths
  176. * where the block should not be shown.
  177. * - 1: Show only on listed pages. 'pages' lists the paths where the block
  178. * should be shown.
  179. * - 2: Use custom PHP code to determine visibility. 'pages' gives the PHP
  180. * code to use.
  181. * Most modules do not provide an initial value for 'visibility' or
  182. * 'pages', and any value provided can be modified by a user on the block
  183. * configuration screen.
  184. * - 'pages': (optional) See 'visibility' above. A string that contains one
  185. * or more page paths separated by '\n', '\r', or '\r\n' when 'visibility'
  186. * is set to 0 or 1, or custom PHP code when 'visibility' is set to 2.
  187. * Paths may use '*' as a wildcard (matching any number of characters);
  188. * '<front>' designates the site's front page. For 'visibility' setting of
  189. * 2, the PHP code's return value should be TRUE if the block is to be
  190. * made visible or FALSE if the block should not be visible.
  191. * - If $op is 'configure': optionally return the configuration form.
  192. * - If $op is 'save': return nothing; save the configuration values.
  193. * - If $op is 'view': return an array which must define a 'subject' element
  194. * (the localized block title) and a 'content' element (the block body)
  195. * defining the block indexed by $delta. If the "content" element
  196. * is empty, no block will be displayed even if "subject" is present.
  197. *
  198. * For a detailed usage example, see block_example.module.
  199. */
  200. function hook_block($op = 'list', $delta = 0, $edit = array()) {
  201. if ($op == 'list') {
  202. $blocks[0] = array('info' => t('Mymodule block #1 shows ...'),
  203. 'weight' => 0, 'status' => 1, 'region' => 'left');
  204. // BLOCK_CACHE_PER_ROLE will be assumed for block 0.
  205. $blocks[1] = array('info' => t('Mymodule block #2 describes ...'),
  206. 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE);
  207. return $blocks;
  208. }
  209. else if ($op == 'configure' && $delta == 0) {
  210. $form['items'] = array(
  211. '#type' => 'select',
  212. '#title' => t('Number of items'),
  213. '#default_value' => variable_get('mymodule_block_items', 0),
  214. '#options' => array('1', '2', '3'),
  215. );
  216. return $form;
  217. }
  218. else if ($op == 'save' && $delta == 0) {
  219. variable_set('mymodule_block_items', $edit['items']);
  220. }
  221. else if ($op == 'view') {
  222. switch($delta) {
  223. case 0:
  224. // Your module will need to define this function to render the block.
  225. $block = array('subject' => t('Title of block #1'),
  226. 'content' => mymodule_display_block_1());
  227. break;
  228. case 1:
  229. // Your module will need to define this function to render the block.
  230. $block = array('subject' => t('Title of block #2'),
  231. 'content' => mymodule_display_block_2());
  232. break;
  233. }
  234. return $block;
  235. }
  236. }
  237. /**
  238. * Respond to comment actions.
  239. *
  240. * This hook allows modules to extend the comments system by responding when
  241. * certain actions take place.
  242. *
  243. * @param $a1
  244. * Argument; meaning is dependent on the action being performed.
  245. * - For "validate", "update", and "insert": an array of form values
  246. * submitted by the user.
  247. * - For all other operations, the comment the action is being performed on.
  248. * @param $op
  249. * The action being performed. Possible values:
  250. * - "insert": The comment is being inserted.
  251. * - "update": The comment is being updated.
  252. * - "view": The comment is being viewed. This hook can be used to add
  253. * additional data to the comment before theming.
  254. * - "validate": The user has just finished editing the comment and is
  255. * trying to preview or submit it. This hook can be used to check
  256. * the comment. Errors should be set with form_set_error().
  257. * - "publish": The comment is being published by the moderator.
  258. * - "unpublish": The comment is being unpublished by the moderator.
  259. * - "delete": The comment is being deleted by the moderator.
  260. */
  261. function hook_comment(&$a1, $op) {
  262. if ($op == 'insert' || $op == 'update') {
  263. $nid = $a1['nid'];
  264. }
  265. cache_clear_all_like(drupal_url(array('id' => $nid)));
  266. }
  267. /**
  268. * Perform periodic actions.
  269. *
  270. * Modules that require to schedule some commands to be executed at regular
  271. * intervals can implement hook_cron(). The engine will then call the hook
  272. * at the appropriate intervals defined by the administrator. This interface
  273. * is particularly handy to implement timers or to automate certain tasks.
  274. * Database maintenance, recalculation of settings or parameters, and
  275. * automatic mailings are good candidates for cron tasks.
  276. *
  277. * @return
  278. * None.
  279. *
  280. * This hook will only be called if cron.php is run (e.g. by crontab).
  281. */
  282. function hook_cron() {
  283. $result = db_query('SELECT * FROM {site} WHERE checked = 0 OR checked
  284. + refresh < %d', time());
  285. while ($site = db_fetch_array($result)) {
  286. cloud_update($site);
  287. }
  288. }
  289. /**
  290. * Expose a list of triggers (events) that users can assign actions to.
  291. *
  292. * @see hook_action_info(), which allows your module to define actions.
  293. *
  294. * Note: Implementing this hook doesn't actually make any action functions run.
  295. * It just lets the trigger module set up an admin page that will let a site
  296. * administrator assign actions to hooks. To make this work, module needs to:
  297. * - Detect that the event has happened
  298. * - Figure out which actions have been associated with the event. Currently,
  299. * the best way to do that is to call _trigger_get_hook_aids(), whose inputs
  300. * are the name of the hook and the name of the operation, as defined in your
  301. * hook_hook_info() return value)
  302. * - Call the associated action functions using the actions_do() function.
  303. *
  304. * @return
  305. * A nested array:
  306. * - The outermost array key must be the name of your module.
  307. * - The next key represents the name of the hook that triggers the
  308. * events, but for custom and contributed modules, it actually must
  309. * be the name of your module.
  310. * - The next key is the name of the operation within the hook. The
  311. * array values at this level are arrays; currently, the only
  312. * recognized key in that array is 'runs when', whose array value gives
  313. * a translated description of the hook.
  314. */
  315. function hook_hook_info() {
  316. return array(
  317. 'comment' => array(
  318. 'comment' => array(
  319. 'insert' => array(
  320. 'runs when' => t('After saving a new comment'),
  321. ),
  322. 'update' => array(
  323. 'runs when' => t('After saving an updated comment'),
  324. ),
  325. 'delete' => array(
  326. 'runs when' => t('After deleting a comment')
  327. ),
  328. 'view' => array(
  329. 'runs when' => t('When a comment is being viewed by an authenticated user')
  330. ),
  331. ),
  332. ),
  333. );
  334. }
  335. /**
  336. * Alter the data being saved to the {menu_router} table after hook_menu is invoked.
  337. *
  338. * This hook is invoked by menu_router_build(). The menu definitions are passed
  339. * in by reference. Each element of the $items array is one item returned
  340. * by a module from hook_menu. Additional items may be added, or existing items
  341. * altered.
  342. *
  343. * @param $items
  344. * Associative array of menu router definitions returned from hook_menu().
  345. * @return
  346. * None.
  347. */
  348. function hook_menu_alter(&$items) {
  349. // Example - disable the page at node/add
  350. $items['node/add']['access callback'] = FALSE;
  351. }
  352. /**
  353. * Alter the data being saved to the {menu_links} table by menu_link_save().
  354. *
  355. * @param $item
  356. * Associative array defining a menu link as passed into menu_link_save().
  357. * @param $menu
  358. * Associative array containg the menu router returned from menu_router_build().
  359. * @return
  360. * None.
  361. */
  362. function hook_menu_link_alter(&$item, $menu) {
  363. // Example 1 - make all new admin links hidden (a.k.a disabled).
  364. if (strpos($item['link_path'], 'admin') === 0 && empty($item['mlid'])) {
  365. $item['hidden'] = 1;
  366. }
  367. // Example 2 - flag a link to be altered by hook_translated_menu_link_alter()
  368. if ($item['link_path'] == 'devel/cache/clear') {
  369. $item['options']['alter'] = TRUE;
  370. }
  371. }
  372. /**
  373. * Alter a menu link after it's translated, but before it's rendered.
  374. *
  375. * This hook may be used, for example, to add a page-specific query string.
  376. * For performance reasons, only links that have $item['options']['alter'] == TRUE
  377. * will be passed into this hook. The $item['options']['alter'] flag should
  378. * generally be set using hook_menu_link_alter().
  379. *
  380. * @param $item
  381. * Associative array defining a menu link after _menu_link_translate()
  382. * @param $map
  383. * Associative array containing the menu $map (path parts and/or objects).
  384. * @return
  385. * None.
  386. */
  387. function hook_translated_menu_link_alter(&$item, $map) {
  388. if ($item['href'] == 'devel/cache/clear') {
  389. $item['localized_options']['query'] = drupal_get_destination();
  390. }
  391. }
  392. /**
  393. * Rewrite database queries, usually for access control.
  394. *
  395. * Add JOIN and WHERE statements to queries and decide whether the primary_field
  396. * shall be made DISTINCT. For node objects, primary field is always called nid.
  397. * For taxonomy terms, it is tid and for vocabularies it is vid. For comments,
  398. * it is cid. Primary table is the table where the primary object (node, file,
  399. * term_node etc.) is.
  400. *
  401. * You shall return an associative array. Possible keys are 'join', 'where' and
  402. * 'distinct'. The value of 'distinct' shall be 1 if you want that the
  403. * primary_field made DISTINCT.
  404. *
  405. * @param $query
  406. * Query to be rewritten.
  407. * @param $primary_table
  408. * Name or alias of the table which has the primary key field for this query.
  409. * Typical table names would be: {blocks}, {comments}, {forum}, {node},
  410. * {menu}, {term_data} or {vocabulary}. However, it is more common for
  411. * $primary_table to contain the usual table alias: b, c, f, n, m, t or v.
  412. * @param $primary_field
  413. * Name of the primary field.
  414. * @param $args
  415. * Array of additional arguments.
  416. * @return
  417. * An array of join statements, where statements, distinct decision.
  418. */
  419. function hook_db_rewrite_sql($query, $primary_table, $primary_field, $args) {
  420. switch ($primary_field) {
  421. case 'nid':
  422. // this query deals with node objects
  423. $return = array();
  424. if ($primary_table != 'n') {
  425. $return['join'] = "LEFT JOIN {node} n ON $primary_table.nid = n.nid";
  426. }
  427. $return['where'] = 'created >' . mktime(0, 0, 0, 1, 1, 2005);
  428. return $return;
  429. break;
  430. case 'tid':
  431. // this query deals with taxonomy objects
  432. break;
  433. case 'vid':
  434. // this query deals with vocabulary objects
  435. break;
  436. }
  437. }
  438. /**
  439. * Allows modules to declare their own Forms API element types and specify their
  440. * default values.
  441. *
  442. * This hook allows modules to declare their own form element types and to
  443. * specify their default values. The values returned by this hook will be
  444. * merged with the elements returned by hook_form() implementations and so
  445. * can return defaults for any Form APIs keys in addition to those explicitly
  446. * mentioned below.
  447. *
  448. * Each of the form element types defined by this hook is assumed to have
  449. * a matching theme function, e.g. theme_elementtype(), which should be
  450. * registered with hook_theme() as normal.
  451. *
  452. * For more information about custom element types see the explanation at
  453. * @link http://drupal.org/node/169815 http://drupal.org/node/169815 @endlink .
  454. *
  455. * @return
  456. * An associative array describing the element types being defined. The array
  457. * contains a sub-array for each element type, with the machine-readable type
  458. * name as the key. Each sub-array has a number of possible attributes:
  459. * - "#input": boolean indicating whether or not this element carries a value
  460. * (even if it's hidden).
  461. * - "#process": array of callback functions taking $element, $edit,
  462. * $form_state, and $complete_form.
  463. * - "#after_build": array of callback functions taking $element and $form_state.
  464. * - "#validate": array of callback functions taking $form and $form_state.
  465. * - "#element_validate": array of callback functions taking $element and
  466. * $form_state.
  467. * - "#pre_render": array of callback functions taking $element and $form_state.
  468. * - "#post_render": array of callback functions taking $element and $form_state.
  469. * - "#submit": array of callback functions taking $form and $form_state.
  470. */
  471. function hook_elements() {
  472. $type['filter_format'] = array('#input' => TRUE);
  473. return $type;
  474. }
  475. /**
  476. * Perform cleanup tasks.
  477. *
  478. * This hook is run at the end of each page request. It is often used for
  479. * page logging and printing out debugging information.
  480. *
  481. * Only use this hook if your code must run even for cached page views.
  482. * If you have code which must run once on all non cached pages, use
  483. * hook_init instead. Thats the usual case. If you implement this hook
  484. * and see an error like 'Call to undefined function', it is likely that
  485. * you are depending on the presence of a module which has not been loaded yet.
  486. * It is not loaded because Drupal is still in bootstrap mode.
  487. *
  488. * @param $destination
  489. * If this hook is invoked as part of a drupal_goto() call, then this argument
  490. * will be a fully-qualified URL that is the destination of the redirect.
  491. * Modules may use this to react appropriately; for example, nothing should
  492. * be output in this case, because PHP will then throw a "headers cannot be
  493. * modified" error when attempting the redirection.
  494. * @return
  495. * None.
  496. */
  497. function hook_exit($destination = NULL) {
  498. db_query('UPDATE {counter} SET hits = hits + 1 WHERE type = 1');
  499. }
  500. /**
  501. * Control access to private file downloads and specify HTTP headers.
  502. *
  503. * This hook allows modules enforce permissions on file downloads when the
  504. * private file download method is selected. Modules can also provide headers
  505. * to specify information like the file's name or MIME type.
  506. *
  507. * @param $filepath
  508. * String of the file's path.
  509. * @return
  510. * If the user does not have permission to access the file, return -1. If the
  511. * user has permission, return an array with the appropriate headers. If the file
  512. * is not controlled by the current module, the return value should be NULL.
  513. */
  514. function hook_file_download($filepath) {
  515. if ($filemime = db_result(db_query("SELECT filemime FROM {fileupload} WHERE filepath = '%s'", file_create_path($filepath)))) {
  516. if (user_access('access content')) {
  517. return array('Content-type:' . $filemime);
  518. }
  519. else {
  520. return -1;
  521. }
  522. }
  523. }
  524. /**
  525. * Define content filters.
  526. *
  527. * Content in Drupal is passed through all enabled filters before it is
  528. * output. This lets a module modify content to the site administrator's
  529. * liking.
  530. *
  531. * This hook contains all that is needed for having a module provide filtering
  532. * functionality.
  533. *
  534. * Depending on $op, different tasks are performed.
  535. *
  536. * A module can contain as many filters as it wants. The 'list' operation tells
  537. * the filter system which filters are available. Every filter has a numerical
  538. * 'delta' which is used to refer to it in every operation.
  539. *
  540. * Filtering is a two-step process. First, the content is 'prepared' by calling
  541. * the 'prepare' operation for every filter. The purpose of 'prepare' is to
  542. * escape HTML-like structures. For example, imagine a filter which allows the
  543. * user to paste entire chunks of programming code without requiring manual
  544. * escaping of special HTML characters like @< or @&. If the programming code
  545. * were left untouched, then other filters could think it was HTML and change
  546. * it. For most filters however, the prepare-step is not necessary, and they can
  547. * just return the input without changes.
  548. *
  549. * Filters should not use the 'prepare' step for anything other than escaping,
  550. * because that would short-circuits the control the user has over the order
  551. * in which filters are applied.
  552. *
  553. * The second step is the actual processing step. The result from the
  554. * prepare-step gets passed to all the filters again, this time with the
  555. * 'process' operation. It's here that filters should perform actual changing of
  556. * the content: transforming URLs into hyperlinks, converting smileys into
  557. * images, etc.
  558. *
  559. * An important aspect of the filtering system are 'input formats'. Every input
  560. * format is an entire filter setup: which filters to enable, in what order
  561. * and with what settings. Filters that provide settings should usually store
  562. * these settings per format.
  563. *
  564. * If the filter's behaviour depends on an extensive list and/or external data
  565. * (e.g. a list of smileys, a list of glossary terms) then filters are allowed
  566. * to provide a separate, global configuration page rather than provide settings
  567. * per format. In that case, there should be a link from the format-specific
  568. * settings to the separate settings page.
  569. *
  570. * For performance reasons content is only filtered once; the result is stored
  571. * in the cache table and retrieved the next time the piece of content is
  572. * displayed. If a filter's output is dynamic it can override the cache
  573. * mechanism, but obviously this feature should be used with caution: having one
  574. * 'no cache' filter in a particular input format disables caching for the
  575. * entire format, not just for one filter.
  576. *
  577. * Beware of the filter cache when developing your module: it is advised to set
  578. * your filter to 'no cache' while developing, but be sure to remove it again
  579. * if it's not needed. You can clear the cache by running the SQL query 'DELETE
  580. * FROM cache_filter';
  581. *
  582. * @param $op
  583. * Which filtering operation to perform. Possible values:
  584. * - list: provide a list of available filters.
  585. * Returns an associative array of filter names with numerical keys.
  586. * These keys are used for subsequent operations and passed back through
  587. * the $delta parameter.
  588. * - no cache: Return true if caching should be disabled for this filter.
  589. * - description: Return a short description of what this filter does.
  590. * - prepare: Return the prepared version of the content in $text.
  591. * - process: Return the processed version of the content in $text.
  592. * - settings: Return HTML form controls for the filter's settings. These
  593. * settings are stored with variable_set() when the form is submitted.
  594. * Remember to use the $format identifier in the variable and control names
  595. * to store settings per input format (e.g. "mymodule_setting_$format").
  596. * @param $delta
  597. * Which of the module's filters to use (applies to every operation except
  598. * 'list'). Modules that only contain one filter can ignore this parameter.
  599. * @param $format
  600. * Which input format the filter is being used in (applies to 'prepare',
  601. * 'process' and 'settings').
  602. * @param $text
  603. * The content to filter (applies to 'prepare' and 'process').
  604. * @param $cache_id
  605. * The cache id of the content.
  606. * @return
  607. * The return value depends on $op. The filter hook is designed so that a
  608. * module can return $text for operations it does not use/need.
  609. *
  610. * For a detailed usage example, see filter_example.module. For an example of
  611. * using multiple filters in one module, see filter_filter() and
  612. * filter_filter_tips().
  613. */
  614. function hook_filter($op, $delta = 0, $format = -1, $text = '', $cache_id = 0) {
  615. switch ($op) {
  616. case 'list':
  617. return array(0 => t('Code filter'));
  618. case 'description':
  619. return t('Allows users to post code verbatim using &lt;code&gt; and &lt;?php ?&gt; tags.');
  620. case 'prepare':
  621. // Note: we use [ and ] to replace < > during the filtering process.
  622. // For more information, see "Temporary placeholders and
  623. // delimiters" at http://drupal.org/node/209715.
  624. $text = preg_replace('@<code>(.+?)</code>@se', "'[codefilter-code]' . codefilter_escape('\\1') . '[/codefilter-code]'", $text);
  625. $text = preg_replace('@<(\?(php)?|%)(.+?)(\?|%)>@se', "'[codefilter-php]' . codefilter_escape('\\3') . '[/codefilter-php]'", $text);
  626. return $text;
  627. case "process":
  628. $text = preg_replace('@[codefilter-code](.+?)[/codefilter-code]@se', "codefilter_process_code('$1')", $text);
  629. $text = preg_replace('@[codefilter-php](.+?)[/codefilter-php]@se', "codefilter_process_php('$1')", $text);
  630. return $text;
  631. default:
  632. return $text;
  633. }
  634. }
  635. /**
  636. * Provide tips for using filters.
  637. *
  638. * A module's tips should be informative and to the point. Short tips are
  639. * preferably one-liners.
  640. *
  641. * @param $delta
  642. * Which of this module's filters to use. Modules which only implement one
  643. * filter can ignore this parameter.
  644. * @param $format
  645. * Which format we are providing tips for.
  646. * @param $long
  647. * If set to true, long tips are requested, otherwise short tips are needed.
  648. * @return
  649. * The text of the filter tip.
  650. *
  651. *
  652. */
  653. function hook_filter_tips($delta, $format, $long = FALSE) {
  654. if ($long) {
  655. return t('To post pieces of code, surround them with &lt;code&gt;...&lt;/code&gt; tags. For PHP code, you can use &lt;?php ... ?&gt;, which will also colour it based on syntax.');
  656. }
  657. else {
  658. return t('You may post code using &lt;code&gt;...&lt;/code&gt; (generic) or &lt;?php ... ?&gt; (highlighted PHP) tags.');
  659. }
  660. }
  661. /**
  662. * Insert closing HTML.
  663. *
  664. * This hook enables modules to insert HTML just before the \</body\> closing
  665. * tag of web pages. This is useful for adding JavaScript code to the footer
  666. * and for outputting debug information. It is not possible to add JavaScript
  667. * to the header at this point, and developers wishing to do so should use
  668. * hook_init() instead.
  669. *
  670. * @param $main
  671. * Whether the current page is the front page of the site.
  672. * @return
  673. * The HTML to be inserted.
  674. */
  675. function hook_footer($main = 0) {
  676. if (variable_get('dev_query', 0)) {
  677. return '<div style="clear:both;">'. devel_query_table() .'</div>';
  678. }
  679. }
  680. /**
  681. * Performs alterations to existing database schemas.
  682. *
  683. * When a module modifies the database structure of another module (by
  684. * changing, adding or removing fields, keys or indexes), it should
  685. * implement hook_schema_alter() to update the default $schema to take
  686. * its changes into account.
  687. *
  688. * See hook_schema() for details on the schema definition structure.
  689. *
  690. * @param $schema
  691. * Nested array describing the schemas for all modules.
  692. * @return
  693. * None.
  694. */
  695. function hook_schema_alter(&$schema) {
  696. // Add field to existing schema.
  697. $schema['users']['fields']['timezone_id'] = array(
  698. 'type' => 'int',
  699. 'not null' => TRUE,
  700. 'default' => 0,
  701. 'description' => 'Per-user timezone configuration.',
  702. );
  703. }
  704. /**
  705. * Perform alterations before a form is rendered.
  706. *
  707. * One popular use of this hook is to add form elements to the node form. When
  708. * altering a node form, the node object can be retrieved from $form['#node'].
  709. *
  710. * Note that instead of hook_form_alter(), which is called for all forms, you
  711. * can also use hook_form_FORM_ID_alter() to alter a specific form.
  712. *
  713. * @param $form
  714. * Nested array of form elements that comprise the form. The arguments
  715. * that drupal_get_form() was originally called with are available in the
  716. * array $form['#parameters'].
  717. * @param $form_state
  718. * A keyed array containing the current state of the form.
  719. * @param $form_id
  720. * String representing the name of the form itself. Typically this is the
  721. * name of the function that generated the form.
  722. */
  723. function hook_form_alter(&$form, &$form_state, $form_id) {
  724. if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
  725. $path = isset($form['#node']->path) ? $form['#node']->path : NULL;
  726. $form['path'] = array(
  727. '#type' => 'fieldset',
  728. '#title' => t('URL path settings'),
  729. '#collapsible' => TRUE,
  730. '#collapsed' => empty($path),
  731. '#access' => user_access('create url aliases'),
  732. '#weight' => 30,
  733. );
  734. $form['path']['path'] = array(
  735. '#type' => 'textfield',
  736. '#default_value' => $path,
  737. '#maxlength' => 128,
  738. '#collapsible' => TRUE,
  739. '#collapsed' => TRUE,
  740. '#description' => t('Optionally specify an alternative URL by which this node can be accessed. For example, type "about" when writing an about page. Use a relative path and don\'t add a trailing slash or the URL alias won\'t work.'),
  741. );
  742. if ($path) {
  743. $form['path']['pid'] = array(
  744. '#type' => 'value',
  745. '#value' => db_result(db_query("SELECT pid FROM {url_alias} WHERE dst = '%s' AND language = '%s'", $path, $form['#node']->language))
  746. );
  747. }
  748. }
  749. }
  750. /**
  751. * Provide a form-specific alteration instead of the global hook_form_alter().
  752. *
  753. * Modules can implement hook_form_FORM_ID_alter() to modify a specific form,
  754. * rather than implementing hook_form_alter() and checking the form ID, or
  755. * using long switch statements to alter multiple forms.
  756. *
  757. * Note that this hook fires before hook_form_alter(). Therefore all
  758. * implementations of hook_form_FORM_ID_alter() will run before all
  759. * implementations of hook_form_alter(), regardless of the module order.
  760. *
  761. * @param $form
  762. * Nested array of form elements that comprise the form. The arguments
  763. * that drupal_get_form() was originally called with are available in the
  764. * array $form['#parameters'].
  765. * @param $form_state
  766. * A keyed array containing the current state of the form.
  767. *
  768. * @see hook_form_alter()
  769. * @see drupal_prepare_form()
  770. */
  771. function hook_form_FORM_ID_alter(&$form, &$form_state) {
  772. // Modification for the form with the given form ID goes here. For example, if
  773. // FORM_ID is "user_register" this code would run only on the user
  774. // registration form.
  775. // Add a checkbox to registration form about agreeing to terms of use.
  776. $form['terms_of_use'] = array(
  777. '#type' => 'checkbox',
  778. '#title' => t("I agree with the website's terms and conditions."),
  779. '#required' => TRUE,
  780. );
  781. }
  782. /**
  783. * Map form_ids to builder functions.
  784. *
  785. * This hook allows modules to build multiple forms from a single form "factory"
  786. * function but each form will have a different form id for submission,
  787. * validation, theming or alteration by other modules.
  788. *
  789. * The callback arguments will be passed as parameters to the function. Callers
  790. * of drupal_get_form() are also able to pass in parameters. These will be
  791. * appended after those specified by hook_forms().
  792. *
  793. * See node_forms() for an actual example of how multiple forms share a common
  794. * building function.
  795. *
  796. * @param $form_id
  797. * The unique string identifying the desired form.
  798. * @param $args
  799. * An array containing the original arguments provided to drupal_get_form().
  800. * @return
  801. * An array keyed by form id with callbacks and optional, callback arguments.
  802. */
  803. function hook_forms($form_id, $args) {
  804. $forms['mymodule_first_form'] = array(
  805. 'callback' => 'mymodule_form_builder',
  806. 'callback arguments' => array('some parameter'),
  807. );
  808. $forms['mymodule_second_form'] = array(
  809. 'callback' => 'mymodule_form_builder',
  810. );
  811. return $forms;
  812. }
  813. /**
  814. * Provide online user help.
  815. *
  816. * By implementing hook_help(), a module can make documentation
  817. * available to the user for the module as a whole, or for specific paths.
  818. * Help for developers should usually be provided via function
  819. * header comments in the code, or in special API example files.
  820. *
  821. * For a detailed usage example, see page_example.module.
  822. *
  823. * @param $path
  824. * The router menu path, as defined in hook_menu(), for the help that
  825. * is being requested; e.g., 'admin/node' or 'user/edit'. If the router path
  826. * includes a % wildcard, then this will appear in $path; for example,
  827. * node pages would have $path equal to 'node/%' or 'node/%/view'. Your hook
  828. * implementation may also be called with special descriptors after a
  829. * "#" sign. Some examples:
  830. * - admin/help#modulename
  831. * The main module help text, displayed on the admin/help/modulename
  832. * page and linked to from the admin/help page.
  833. * - user/help#modulename
  834. * The help for a distributed authorization module (if applicable).
  835. * @param $arg
  836. * An array that corresponds to the return value of the arg() function, for
  837. * modules that want to provide help that is specific to certain values
  838. * of wildcards in $path. For example, you could provide help for the path
  839. * 'user/1' by looking for the path 'user/%' and $arg[1] == '1'. This
  840. * array should always be used rather than directly invoking arg(), because
  841. * your hook implementation may be called for other purposes besides building
  842. * the current page's help. Note that depending on which module is invoking
  843. * hook_help, $arg may contain only empty strings. Regardless, $arg[0] to
  844. * $arg[11] will always be set.
  845. * @return
  846. * A localized string containing the help text.
  847. */
  848. function hook_help($path, $arg) {
  849. switch ($path) {
  850. // Main module help for the block module
  851. case 'admin/help#block':
  852. return '<p>' . t('Blocks are boxes of content rendered into an area, or region, of a web page. The default theme Garland, for example, implements the regions "left sidebar", "right sidebar", "content", "header", and "footer", and a block may appear in any one of these areas. The <a href="@blocks">blocks administration page</a> provides a drag-and-drop interface for assigning a block to a region, and for controlling the order of blocks within regions.', array('@blocks' => url('admin/structure/block'))) . '</p>';
  853. // Help for another path in the block module
  854. case 'admin/build/block':
  855. return '<p>' . t('This page provides a drag-and-drop interface for assigning a block to a region, and for controlling the order of blocks within regions. Since not all themes implement the same regions, or display regions in the same way, blocks are positioned on a per-theme basis. Remember that your changes will not be saved until you click the <em>Save blocks</em> button at the bottom of the page.') . '</p>';
  856. }
  857. }
  858. /**
  859. * Outputs a cached page.
  860. *
  861. * By implementing page_cache_fastpath(), a special cache handler can skip
  862. * most of the bootstrap process, including the database connection.
  863. * This function is invoked during DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE.
  864. *
  865. * @return
  866. * TRUE if a page was output successfully.
  867. *
  868. * @see _drupal_bootstrap()
  869. */
  870. function page_cache_fastpath() {
  871. $page = mycache_fetch($base_root . request_uri(), 'cache_page');
  872. if (!empty($page)) {
  873. drupal_page_header();
  874. print $page;
  875. return TRUE;
  876. }
  877. }
  878. /**
  879. * Perform setup tasks. See also, hook_init.
  880. *
  881. * This hook is run at the beginning of the page request. It is typically
  882. * used to set up global parameters which are needed later in the request.
  883. *
  884. * Only use this hook if your code must run even for cached page views.This hook
  885. * is called before modules or most include files are loaded into memory.
  886. * It happens while Drupal is still in bootstrap mode.
  887. *
  888. * @return
  889. * None.
  890. */
  891. function hook_boot() {
  892. // we need user_access() in the shutdown function. make sure it gets loaded
  893. drupal_load('module', 'user');
  894. register_shutdown_function('devel_shutdown');
  895. }
  896. /**
  897. * Perform setup tasks. See also, hook_boot.
  898. *
  899. * This hook is run at the beginning of the page request. It is typically
  900. * used to set up global parameters which are needed later in the request.
  901. * when this hook is called, all modules are already loaded in memory.
  902. *
  903. * For example, this hook is a typical place for modules to add CSS or JS
  904. * that should be present on every page. This hook is not run on cached
  905. * pages - though CSS or JS added this way will be present on a cached page.
  906. *
  907. * @return
  908. * None.
  909. */
  910. function hook_init() {
  911. drupal_add_css(drupal_get_path('module', 'book') .'/book.css');
  912. }
  913. /**
  914. * Define internal Drupal links.
  915. *
  916. * This hook enables modules to add links to many parts of Drupal. Links
  917. * may be added in nodes or in the navigation block, for example.
  918. *
  919. * The returned array should be a keyed array of link entries. Each link can
  920. * be in one of two formats.
  921. *
  922. * The first format will use the l() function to render the link:
  923. * - attributes: Optional. See l() for usage.
  924. * - fragment: Optional. See l() for usage.
  925. * - href: Required. The URL of the link.
  926. * - html: Optional. See l() for usage.
  927. * - query: Optional. See l() for usage.
  928. * - title: Required. The name of the link.
  929. *
  930. * The second format can be used for non-links. Leaving out the href index will
  931. * select this format:
  932. * - title: Required. The text or HTML code to display.
  933. * - attributes: Optional. An associative array of HTML attributes to apply to the span tag.
  934. * - html: Optional. If not set to true, check_plain() will be run on the title before it is displayed.
  935. *
  936. * @param $type
  937. * An identifier declaring what kind of link is being requested.
  938. * Possible values:
  939. * - comment: Links to be placed below a comment being viewed.
  940. * - node: Links to be placed below a node being viewed.
  941. * @param $object
  942. * A node object or a comment object according to the $type.
  943. * @param $teaser
  944. * In case of node link: a 0/1 flag depending on whether the node is
  945. * displayed with its teaser or its full form.
  946. * @return
  947. * An array of the requested links.
  948. *
  949. */
  950. function hook_link($type, $object, $teaser = FALSE) {
  951. $links = array();
  952. if ($type == 'node' && isset($object->parent)) {
  953. if (!$teaser) {
  954. if (book_access('create', $object)) {
  955. $links['book_add_child'] = array(
  956. 'title' => t('add child page'),
  957. 'href' => "node/add/book/parent/$object->nid",
  958. );
  959. }
  960. if (user_access('see printer-friendly version')) {
  961. $links['book_printer'] = array(
  962. 'title' => t('printer-friendly version'),
  963. 'href' => 'book/export/html/'. $object->nid,
  964. 'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
  965. );
  966. }
  967. }
  968. }
  969. $links['sample_link'] = array(
  970. 'title' => t('go somewhere'),
  971. 'href' => 'node/add',
  972. 'query' => 'foo=bar',
  973. 'fragment' => 'anchorname',
  974. 'attributes' => array('title' => t('go to another page')),
  975. );
  976. // Example of a link that's not an anchor
  977. if ($type == 'video') {
  978. if (variable_get('video_playcounter', 1) && user_access('view play counter')) {
  979. $links['play_counter'] = array(
  980. 'title' => format_plural($object->play_counter, '1 play', '@count plays'),
  981. );
  982. }
  983. }
  984. return $links;
  985. }
  986. /**
  987. * Perform alterations before links on a node or comment are rendered.
  988. *
  989. * One popular use of this hook is to modify/remove links from other modules.
  990. * If you want to add a link to the links section of a node or comment, use
  991. * hook_link() instead.
  992. *
  993. * @param $links
  994. * Nested array of links for the node or comment keyed by providing module.
  995. * @param $node
  996. * A node object.
  997. * @param $comment
  998. * An optional comment object if the links are comment links. If not
  999. * provided, the links are node links.
  1000. *
  1001. * @see hook_link()
  1002. */
  1003. function hook_link_alter(&$links, $node, $comment = NULL) {
  1004. foreach ($links as $module => $link) {
  1005. if (strstr($module, 'taxonomy_term')) {
  1006. // Link back to the forum and not the taxonomy term page
  1007. $links[$module]['href'] = str_replace('taxonomy/term', 'forum', $link['href']);
  1008. }
  1009. }
  1010. }
  1011. /**
  1012. * Alter profile items before they are rendered.
  1013. *
  1014. * You may omit/add/re-sort/re-categorize, etc.
  1015. *
  1016. * @param $account
  1017. * A user object whose profile is being rendered. Profile items
  1018. * are stored in $account->content.
  1019. */
  1020. function hook_profile_alter(&$account) {
  1021. foreach ($account->content AS $key => $field) {
  1022. // do something
  1023. }
  1024. }
  1025. /**
  1026. * Alter any aspect of email sent by Drupal. You can use this hook to add a
  1027. * common site footer to all outgoing email, add extra header fields, and/or
  1028. * modify the email in any way. HTML-izing the outgoing email is one possibility.
  1029. * See also drupal_mail().
  1030. *
  1031. * @param $message
  1032. * A structured array containing the message to be altered. Keys in this
  1033. * array include:
  1034. * - 'id'
  1035. * An id to identify the mail sent. Look at module source code or
  1036. * drupal_mail() for possible id values.
  1037. * - 'to'
  1038. * The mail address or addresses the message will be sent to. The
  1039. * formatting of this string must comply with RFC 2822.
  1040. * - 'subject'
  1041. * Subject of the e-mail to be sent. This must not contain any newline
  1042. * characters, or the mail may not be sent properly.
  1043. * - 'body'
  1044. * An array of lines containing the message to be sent. Drupal will format
  1045. * the correct line endings for you.
  1046. * - 'from'
  1047. * The address the message will be marked as being from, which is either a
  1048. * custom address or the site-wide default email address.
  1049. * - 'headers'
  1050. * Associative array containing mail headers, such as From, Sender,
  1051. * MIME-Version, Content-Type, etc.
  1052. * - 'params'
  1053. * An array of optional parameters supplied by the caller of drupal_mail()
  1054. * that is used to build the message before hook_mail_alter() is invoked.
  1055. * - language'
  1056. * The language object used to build the message before hook_mail_alter()
  1057. * is invoked.
  1058. */
  1059. function hook_mail_alter(&$message) {
  1060. if ($message['id'] == 'modulename_messagekey') {
  1061. $message['body'][] = "--\nMail sent out from " . variable_get('sitename', t('Drupal'));
  1062. }
  1063. }
  1064. /**
  1065. * Define menu items and page callbacks.
  1066. *
  1067. * This hook enables modules to register paths in order to define how URL
  1068. * requests are handled. Paths may be registered for URL handling only, or they
  1069. * can register a link to be placed in a menu (usually the Navigation menu). A
  1070. * path and its associated information is commonly called a "menu router item".
  1071. * This hook is rarely called (for example, when modules are enabled), and
  1072. * its results are cached in the database.
  1073. *
  1074. * hook_menu() implementations return an associative array whose keys define
  1075. * paths and whose values are an associative array of properties for each
  1076. * path. (The complete list of properties is in the return value section below.)
  1077. *
  1078. * The definition for each path may include a page callback function, which is
  1079. * invoked when the registered path is requested. If there is no other
  1080. * registered path that fits the requested path better, any further path
  1081. * components are passed to the callback function. For example, your module
  1082. * could register path 'abc/def':
  1083. * @code
  1084. * function mymodule_menu() {
  1085. * $items['abc/def'] = array(
  1086. * 'page callback' => 'mymodule_abc_view',
  1087. * );
  1088. * return $items;
  1089. * }
  1090. *
  1091. * function mymodule_abc_view($ghi = 0, $jkl = '') {
  1092. * // ...
  1093. * }
  1094. * @endcode
  1095. * When path 'abc/def' is requested, no further path components are in the
  1096. * request, and no additional arguments are passed to the callback function (so
  1097. * $ghi and $jkl would take the default values as defined in the function
  1098. * signature). When 'abc/def/123/foo' is requested, $ghi will be '123' and
  1099. * $jkl will be 'foo'. Note that this automatic passing of optional path
  1100. * arguments applies only to page and theme callback functions.
  1101. *
  1102. * In addition to optional path arguments, the page callback and other callback
  1103. * functions may specify argument lists as arrays. These argument lists may
  1104. * contain both fixed/hard-coded argument values and integers that correspond
  1105. * to path components. When integers are used and the callback function is
  1106. * called, the corresponding path components will be substituted for the
  1107. * integers. That is, the integer 0 in an argument list will be replaced with
  1108. * the first path component, integer 1 with the second, and so on (path
  1109. * components are numbered starting from zero). To pass an integer without it
  1110. * being replaced with its respective path component, use the string value of
  1111. * the integer (e.g., '1') as the argument value. This substitution feature
  1112. * allows you to re-use a callback function for several different paths. For
  1113. * example:
  1114. * @code
  1115. * function mymodule_menu() {
  1116. * $items['abc/def'] = array(
  1117. * 'page callback' => 'mymodule_abc_view',
  1118. * 'page arguments' => array(1, 'foo'),
  1119. * );
  1120. * return $items;
  1121. * }
  1122. * @endcode
  1123. * When path 'abc/def' is requested, the page callback function will get 'def'
  1124. * as the first argument and (always) 'foo' as the second argument.
  1125. *
  1126. * If a page callback function uses an argument list array, and its path is
  1127. * requested with optional path arguments, then the list array's arguments are
  1128. * passed to the callback function first, followed by the optional path
  1129. * arguments. Using the above example, when path 'abc/def/bar/baz' is requested,
  1130. * mymodule_abc_view() will be called with 'def', 'foo', 'bar' and 'baz' as
  1131. * arguments, in that order.
  1132. *
  1133. * Wildcards within paths also work with integer substitution. For example,
  1134. * your module could register path 'my-module/%/edit':
  1135. * @code
  1136. * $items['my-module/%/edit'] = array(
  1137. * 'page callback' => 'mymodule_abc_edit',
  1138. * 'page arguments' => array(1),
  1139. * );
  1140. * @endcode
  1141. * When path 'my-module/foo/edit' is requested, integer 1 will be replaced
  1142. * with 'foo' and passed to the callback function.
  1143. *
  1144. * Registered paths may also contain special "auto-loader" wildcard components
  1145. * in the form of '%mymodule_abc', where the '%' part means that this path
  1146. * component is a wildcard, and the 'mymodule_abc' part defines the prefix for a
  1147. * load function, which here would be named mymodule_abc_load(). When a matching
  1148. * path is requested, your load function will receive as its first argument the
  1149. * path component in the position of the wildcard; load functions may also be
  1150. * passed additional arguments (see "load arguments" in the return value
  1151. * section below). For example, your module could register path
  1152. * 'my-module/%mymodule_abc/edit':
  1153. * @code
  1154. * $items['my-module/%mymodule_abc/edit'] = array(
  1155. * 'page callback' => 'mymodule_abc_edit',
  1156. * 'page arguments' => array(1),
  1157. * );
  1158. * @endcode
  1159. * When path 'my-module/123/edit' is requested, your load function
  1160. * mymodule_abc_load() will be invoked with the argument '123', and should
  1161. * load and return an "abc" object with internal id 123:
  1162. * @code
  1163. * function mymodule_abc_load($abc_id) {
  1164. * return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  1165. * }
  1166. * @endcode
  1167. * This 'abc' object will then be passed into the callback functions defined
  1168. * for the menu item, such as the page callback function mymodule_abc_edit()
  1169. * to replace the integer 1 in the argument array. Note that a load function
  1170. * should return FALSE when it is unable to provide a loadable object. For
  1171. * example, the node_load() function for the 'node/%node/edit' menu item will
  1172. * return FALSE for the path 'node/999/edit' if a node with a node ID of 999
  1173. * does not exist. The menu routing system will return a 404 error in this case.
  1174. *
  1175. * You can also make groups of menu items to be rendered (by default) as tabs
  1176. * on a page. To do that, first create one menu item of type MENU_NORMAL_ITEM,
  1177. * with your chosen path, such as 'foo'. Then duplicate that menu item, using a
  1178. * subdirectory path, such as 'foo/tab1', and changing the type to
  1179. * MENU_DEFAULT_LOCAL_TASK to make it the default tab for the group. Then add
  1180. * the additional tab items, with paths such as "foo/tab2" etc., with type
  1181. * MENU_LOCAL_TASK. Example:
  1182. * @code
  1183. * // Make "Foo settings" appear on the admin Config page
  1184. * $items['admin/config/foo'] = array(
  1185. * 'title' => 'Foo settings',
  1186. * 'type' => MENU_NORMAL_ITEM,
  1187. * // Page callback, etc. need to be added here.
  1188. * );
  1189. * // Make "Global settings" the main tab on the "Foo settings" page
  1190. * $items['admin/config/foo/global'] = array(
  1191. * 'title' => 'Global settings',
  1192. * 'type' => MENU_DEFAULT_LOCAL_TASK,
  1193. * // Access callback, page callback, and theme callback will be inherited
  1194. * // from 'admin/config/foo', if not specified here to override.
  1195. * );
  1196. * // Make an additional tab called "Node settings" on "Foo settings"
  1197. * $items['admin/config/foo/node'] = array(
  1198. * 'title' => 'Node settings',
  1199. * 'type' => MENU_LOCAL_TASK,
  1200. * // Page callback and theme callback will be inherited from
  1201. * // 'admin/config/foo', if not specified here to override.
  1202. * // Need to add access callback or access arguments.
  1203. * );
  1204. * @endcode
  1205. *
  1206. * @return
  1207. * An array of menu items. Each menu item has a key corresponding to the
  1208. * Drupal path being registered. The corresponding array value is an
  1209. * associative array that may contain the following key-value pairs:
  1210. * - "title": Required. The untranslated title of the menu item.
  1211. * - "title callback": Function to generate the title; defaults to t().
  1212. * If you require only the raw string to be output, set this to FALSE.
  1213. * - "title arguments": Arguments to send to t() or your custom callback,
  1214. * with path component substitution as described above.
  1215. * - "description": The untranslated description of the menu item.
  1216. * - "page callback": The function to call to display a web page when the user
  1217. * visits the path. If omitted, the parent menu item's callback will be used
  1218. * instead.
  1219. * - "page arguments": An array of arguments to pass to the page callback
  1220. * function, with path component substitution as described above.
  1221. * - "access callback": A function returning TRUE if the user has access
  1222. * rights to this menu item, and FALSE if not. It can also be a boolean
  1223. * constant instead of a function, and you can also use numeric values
  1224. * (will be cast to boolean). Defaults to user_access() unless a value is
  1225. * inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items
  1226. * can inherit access callbacks. To use the user_access() default callback,
  1227. * you must specify the permission to check as 'access arguments' (see
  1228. * below).
  1229. * - "access arguments": An array of arguments to pass to the access callback
  1230. * function, with path component substitution as described above. If the
  1231. * access callback is inherited (see above), the access arguments will be
  1232. * inherited with it, unless overridden in the child menu item.
  1233. * - "file": A file that will be included before the page callback is called;
  1234. * this allows page callback functions to be in separate files. The file
  1235. * should be relative to the implementing module's directory unless
  1236. * otherwise specified by the "file path" option. Does not apply to other
  1237. * callbacks (only page callback).
  1238. * - "file path": The path to the directory containing the file specified in
  1239. * "file". This defaults to the path to the module implementing the hook.
  1240. * - "load arguments": An array of arguments to be passed to each of the
  1241. * wildcard object loaders in the path, after the path argument itself.
  1242. * For example, if a module registers path node/%node/revisions/%/view
  1243. * with load arguments set to array(3), the '%node' in the path indicates
  1244. * that the loader function node_load() will be called with the second
  1245. * path component as the first argument. The 3 in the load arguments
  1246. * indicates that the fourth path component will also be passed to
  1247. * node_load() (numbering of path components starts at zero). So, if path
  1248. * node/12/revisions/29/view is requested, node_load(12, 29) will be called.
  1249. * There are also two "magic" values that can be used in load arguments.
  1250. * "%index" indicates the index of the wildcard path component. "%map"
  1251. * indicates the path components as an array. For example, if a module
  1252. * registers for several paths of the form 'user/%user_category/edit/*', all
  1253. * of them can use the same load function user_category_load(), by setting
  1254. * the load arguments to array('%map', '%index'). For instance, if the user
  1255. * is editing category 'foo' by requesting path 'user/32/edit/foo', the load
  1256. * function user_category_load() will be called with 32 as its first
  1257. * argument, the array ('user', 32, 'edit', 'foo') as the map argument,
  1258. * and 1 as the index argument (because %user_category is the second path
  1259. * component and numbering starts at zero). user_category_load() can then
  1260. * use these values to extract the information that 'foo' is the category
  1261. * being requested.
  1262. * - "weight": An integer that determines the relative position of items in
  1263. * the menu; higher-weighted items sink. Defaults to 0. Menu items with the
  1264. * same weight are ordered alphabetically.
  1265. * - "menu_name": Optional. Set this to a custom menu if you don't want your
  1266. * item to be placed in Navigation.
  1267. * - "tab_parent": For local task menu items, the path of the task's parent
  1268. * item; defaults to the same path without the last component (e.g., the
  1269. * default parent for 'admin/people/create' is 'admin/people').
  1270. * - "tab_root": For local task menu items, the path of the closest non-tab
  1271. * item; same default as "tab_parent".
  1272. * - "position": Position of the block ('left' or 'right') on the system
  1273. * administration page for this item.
  1274. * - "type": A bitmask of flags describing properties of the menu item.
  1275. * Many shortcut bitmasks are provided as constants in menu.inc:
  1276. * - MENU_NORMAL_ITEM: Normal menu items show up in the menu tree and can be
  1277. * moved/hidden by the administrator.
  1278. * - MENU_CALLBACK: Callbacks simply register a path so that the correct
  1279. * information is generated when the path is accessed.
  1280. * - MENU_SUGGESTED_ITEM: Modules may "suggest" menu items that the
  1281. * administrator may enable.
  1282. * - MENU_LOCAL_TASK: Local tasks are menu items that describe different
  1283. * displays of data, and are generally rendered as tabs.
  1284. * - MENU_DEFAULT_LOCAL_TASK: Every set of local tasks should provide one
  1285. * "default" task, which should display the same page as the parent item.
  1286. * If the "type" element is omitted, MENU_NORMAL_ITEM is assumed.
  1287. *
  1288. * For a detailed usage example, see page_example.module.
  1289. * For comprehensive documentation on the menu system, see
  1290. * http://drupal.org/node/102338.
  1291. */
  1292. function hook_menu() {
  1293. $items = array();
  1294. $items['example'] = array(
  1295. 'title' => 'Example Page',
  1296. 'page callback' => 'example_page',
  1297. 'access arguments' => array('access content'),
  1298. 'type' => MENU_SUGGESTED_ITEM,
  1299. );
  1300. $items['example/feed'] = array(
  1301. 'title' => 'Example RSS feed',
  1302. 'page callback' => 'example_feed',
  1303. 'access arguments' => array('access content'),
  1304. 'type' => MENU_CALLBACK,
  1305. );
  1306. return $items;
  1307. }
  1308. /**
  1309. * Alter the information parsed from module and theme .info files
  1310. *
  1311. * This hook is invoked in module_rebuild_cache() and in system_theme_data().
  1312. * A module may implement this hook in order to add to or alter the data
  1313. * generated by reading the .info file with drupal_parse_info_file().
  1314. *
  1315. * @param &$info
  1316. * The .info file contents, passed by reference so that it can be altered.
  1317. * @param $file
  1318. * Full information about the module or theme, including $file->name, and
  1319. * $file->filename
  1320. */
  1321. function hook_system_info_alter(&$info, $file) {
  1322. // Only fill this in if the .info file does not define a 'datestamp'.
  1323. if (empty($info['datestamp'])) {
  1324. $info['datestamp'] = filemtime($file->filename);
  1325. }
  1326. }
  1327. /**
  1328. * Alter the information about available updates for projects.
  1329. *
  1330. * @param $projects
  1331. * Reference to an array of information about available updates to each
  1332. * project installed on the system.
  1333. *
  1334. * @see update_calculate_project_data()
  1335. */
  1336. function hook_update_status_alter(&$projects) {
  1337. $settings = variable_get('update_advanced_project_settings', array());
  1338. foreach ($projects as $project => $project_info) {
  1339. if (isset($settings[$project]) && isset($settings[$project]['check']) &&
  1340. ($settings[$project]['check'] == 'never' ||
  1341. (isset($project_info['recommended']) &&
  1342. $settings[$project]['check'] === $project_info['recommended']))) {
  1343. $projects[$project]['status'] = UPDATE_NOT_CHECKED;
  1344. $projects[$project]['reason'] = t('Ignored from settings');
  1345. if (!empty($settings[$project]['notes'])) {
  1346. $projects[$project]['extra'][] = array(
  1347. 'class' => 'admin-note',
  1348. 'label' => t('Administrator note'),
  1349. 'data' => $settings[$project]['notes'],
  1350. );
  1351. }
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * Alter the list of projects before fetching data and comparing versions.
  1357. *
  1358. * Most modules will never need to implement this hook. It is for advanced
  1359. * interaction with the update status module: mere mortals need not apply.
  1360. * The primary use-case for this hook is to add projects to the list, for
  1361. * example, to provide update status data on disabled modules and themes. A
  1362. * contributed module might want to hide projects from the list, for example,
  1363. * if there is a site-specific module that doesn't have any official releases,
  1364. * that module could remove itself from this list to avoid "No available
  1365. * releases found" warnings on the available updates report. In rare cases, a
  1366. * module might want to alter the data associated with a project already in
  1367. * the list.
  1368. *
  1369. * @param $projects
  1370. * Reference to an array of the projects installed on the system. This
  1371. * includes all the metadata documented in the comments below for each
  1372. * project (either module or theme) that is currently enabled. The array is
  1373. * initially populated inside update_get_projects() with the help of
  1374. * _update_process_info_list(), so look there for examples of how to
  1375. * populate the array with real values.
  1376. *
  1377. * @see update_get_projects()
  1378. * @see _update_process_info_list()
  1379. */
  1380. function hook_update_projects_alter(&$projects) {
  1381. // Hide a site-specific module from the list.
  1382. unset($projects['site_specific_module']);
  1383. // Add a disabled module to the list.
  1384. // The key for the array should be the machine-readable project "short name".
  1385. $projects['disabled_project_name'] = array(
  1386. // Machine-readable project short name (same as the array key above).
  1387. 'name' => 'disabled_project_name',
  1388. // Array of values from the main .info file for this project.
  1389. 'info' => array(
  1390. 'name' => 'Some disabled module',
  1391. 'description' => 'A module not enabled on the site that you want to see in the available updates report.',
  1392. 'version' => '6.x-1.0',
  1393. 'core' => '6.x',
  1394. // The maximum file change time (the "ctime" returned by the filectime()
  1395. // PHP method) for all of the .info files included in this project.
  1396. '_info_file_ctime' => 1243888165,
  1397. ),
  1398. // The date stamp when the project was released, if known. If the disabled
  1399. // project was an officially packaged release from drupal.org, this will
  1400. // be included in the .info file as the 'datestamp' field. This only
  1401. // really matters for development snapshot releases that are regenerated,
  1402. // so it can be left undefined or set to 0 in most cases.
  1403. 'datestamp' => 1243888185,
  1404. // Any modules (or themes) included in this project. Keyed by machine-
  1405. // readable "short name", value is the human-readable project name printed
  1406. // in the UI.
  1407. 'includes' => array(
  1408. 'disabled_project' => 'Disabled module',
  1409. 'disabled_project_helper' => 'Disabled module helper module',
  1410. 'disabled_project_foo' => 'Disabled module foo add-on module',
  1411. ),
  1412. // Does this project contain a 'module', 'theme', 'disabled-module', or
  1413. // 'disabled-theme'?
  1414. 'project_type' => 'disabled-module',
  1415. );
  1416. }
  1417. /**
  1418. * Inform the node access system what permissions the user has.
  1419. *
  1420. * This hook is for implementation by node access modules. In this hook,
  1421. * the module grants a user different "grant IDs" within one or more
  1422. * "realms". In hook_node_access_records(), the realms and grant IDs are
  1423. * associated with permission to view, edit, and delete individual nodes.
  1424. *
  1425. * The realms and grant IDs can be arbitrarily defined by your node access
  1426. * module; it is common to use role IDs as grant IDs, but that is not
  1427. * required. Your module could instead maintain its own list of users, where
  1428. * each list has an ID. In that case, the return value of this hook would be
  1429. * an array of the list IDs that this user is a member of.
  1430. *
  1431. * A node access module may implement as many realms as necessary to
  1432. * properly define the access privileges for the nodes.
  1433. *
  1434. * @param $account
  1435. * The user object whose grants are requested.
  1436. * @param $op
  1437. * The node operation to be performed, such as "view", "update", or "delete".
  1438. *
  1439. * @return
  1440. * An array whose keys are "realms" of grants, and whose values are arrays of
  1441. * the grant IDs within this realm that this user is being granted.
  1442. *
  1443. * For a detailed example, see node_access_example.module.
  1444. *
  1445. * @ingroup node_access
  1446. */
  1447. function hook_node_grants($account, $op) {
  1448. if (user_access('access private content', $account)) {
  1449. $grants['example'] = array(1);
  1450. }
  1451. $grants['example_owner'] = array($account->uid);
  1452. return $grants;
  1453. }
  1454. /**
  1455. * Set permissions for a node to be written to the database.
  1456. *
  1457. * When a node is saved, a module implementing hook_node_access_records() will
  1458. * be asked if it is interested in the access permissions for a node. If it is
  1459. * interested, it must respond with an array of permissions arrays for that
  1460. * node.
  1461. *
  1462. * Each permissions item in the array is an array with the following elements:
  1463. * - 'realm': The name of a realm that the module has defined in
  1464. * hook_node_grants().
  1465. * - 'gid': A 'grant ID' from hook_node_grants().
  1466. * - 'grant_view': If set to TRUE a user that has been identified as a member
  1467. * of this gid within this realm can view this node.
  1468. * - 'grant_update': If set to TRUE a user that has been identified as a member
  1469. * of this gid within this realm can edit this node.
  1470. * - 'grant_delete': If set to TRUE a user that has been identified as a member
  1471. * of this gid within this realm can delete this node.
  1472. * - 'priority': If multiple modules seek to set permissions on a node, the
  1473. * realms that have the highest priority will win out, and realms with a lower
  1474. * priority will not be written. If there is any doubt, it is best to
  1475. * leave this 0.
  1476. *
  1477. * @ingroup node_access
  1478. */
  1479. function hook_node_access_records($node) {
  1480. if (node_access_example_disabling()) {
  1481. return;
  1482. }
  1483. // We only care about the node if it's been marked private. If not, it is
  1484. // treated just like any other node and we completely ignore it.
  1485. if ($node->private) {
  1486. $grants = array();
  1487. $grants[] = array(
  1488. 'realm' => 'example',
  1489. 'gid' => 1,
  1490. 'grant_view' => TRUE,
  1491. 'grant_update' => FALSE,
  1492. 'grant_delete' => FALSE,
  1493. 'priority' => 0,
  1494. );
  1495. // For the example_author array, the GID is equivalent to a UID, which
  1496. // means there are many many groups of just 1 user.
  1497. $grants[] = array(
  1498. 'realm' => 'example_author',
  1499. 'gid' => $node->uid,
  1500. 'grant_view' => TRUE,
  1501. 'grant_update' => TRUE,
  1502. 'grant_delete' => TRUE,
  1503. 'priority' => 0,
  1504. );
  1505. return $grants;
  1506. }
  1507. }
  1508. /**
  1509. * Add mass node operations.
  1510. *
  1511. * This hook enables modules to inject custom operations into the mass operations
  1512. * dropdown found at admin/content/node, by associating a callback function with
  1513. * the operation, which is called when the form is submitted. The callback function
  1514. * receives one initial argument, which is an array of the checked nodes.
  1515. *
  1516. * @return
  1517. * An array of operations. Each operation is an associative array that may
  1518. * contain the following key-value pairs:
  1519. * - "label": Required. The label for the operation, displayed in the dropdown menu.
  1520. * - "callback": Required. The function to call for the operation.
  1521. * - "callback arguments": Optional. An array of additional arguments to pass to
  1522. * the callback function.
  1523. *
  1524. */
  1525. function hook_node_operations() {
  1526. $operations = array(
  1527. 'approve' => array(
  1528. 'label' => t('Approve the selected posts'),
  1529. 'callback' => 'node_operations_approve',
  1530. ),
  1531. 'promote' => array(
  1532. 'label' => t('Promote the selected posts'),
  1533. 'callback' => 'node_operations_promote',
  1534. ),
  1535. 'sticky' => array(
  1536. 'label' => t('Make the selected posts sticky'),
  1537. 'callback' => 'node_operations_sticky',
  1538. ),
  1539. 'demote' => array(
  1540. 'label' => t('Demote the selected posts'),
  1541. 'callback' => 'node_operations_demote',
  1542. ),
  1543. 'unpublish' => array(
  1544. 'label' => t('Unpublish the selected posts'),
  1545. 'callback' => 'node_operations_unpublish',
  1546. ),
  1547. 'delete' => array(
  1548. 'label' => t('Delete the selected posts'),
  1549. ),
  1550. );
  1551. return $operations;
  1552. }
  1553. /**
  1554. * Act on nodes defined by other modules.
  1555. *
  1556. * Despite what its name might make you think, hook_nodeapi() is not
  1557. * reserved for node modules. On the contrary, it allows modules to react
  1558. * to actions affecting all kinds of nodes, regardless of whether that
  1559. * module defined the node.
  1560. *
  1561. * It is common to find hook_nodeapi() used in conjunction with
  1562. * hook_form_alter(). Modules use hook_form_alter() to place additional form
  1563. * elements onto the node edit form, and hook_nodeapi() is used to read and
  1564. * write those values to and from the database.
  1565. *
  1566. * @param &$node
  1567. * The node the action is being performed on.
  1568. * @param $op
  1569. * What kind of action is being performed. Possible values:
  1570. * - "alter": the $node->content array has been rendered, so the node body or
  1571. * teaser is filtered and now contains HTML. This op should only be used when
  1572. * text substitution, filtering, or other raw text operations are necessary.
  1573. * - "delete": The node is being deleted.
  1574. * - "delete revision": The revision of the node is deleted. You can delete data
  1575. * associated with that revision.
  1576. * - "insert": The node has just been created (inserted in the database).
  1577. * - "load": The node is about to be loaded from the database. This hook
  1578. * can be used to load additional data at this time.
  1579. * - "prepare": The node is about to be shown on the add/edit form.
  1580. * - "prepare translation": The node is being cloned for translation. Load
  1581. * additional data or copy values from $node->translation_source.
  1582. * - "print": Prepare a node view for printing. Used for printer-friendly
  1583. * view in book_module
  1584. * - "rss item": An RSS feed is generated. The module can return properties
  1585. * to be added to the RSS item generated for this node. See comment_nodeapi()
  1586. * and upload_nodeapi() for examples. The $node passed can also be modified
  1587. * to add or remove contents to the feed item.
  1588. * - "search result": The node is displayed as a search result. If you
  1589. * want to display extra information with the result, return it.
  1590. * - "presave": The node passed validation and is about to be saved. Modules may
  1591. * use this to make changes to the node before it is saved to the database.
  1592. * - "update": The node has just been updated in the database.
  1593. * - "update index": The node is being indexed. If you want additional
  1594. * information to be indexed which is not already visible through
  1595. * nodeapi "view", then you should return it here.
  1596. * - "validate": The user has just finished editing the node and is
  1597. * trying to preview or submit it. This hook can be used to check
  1598. * the node data. Errors should be set with form_set_error().
  1599. * - "view": The node content is being assembled before rendering. The module
  1600. * may add elements $node->content prior to rendering. This hook will be
  1601. * called after hook_view(). The format of $node->content is the same as
  1602. * used by Forms API.
  1603. * @param $a3
  1604. * - For "view" and "alter", passes in the $teaser parameter from node_view().
  1605. * - For "validate", passes in the $form parameter from node_validate().
  1606. * @param $a4
  1607. * - For "view" and "alter", passes in the $page parameter from node_view().
  1608. * @return
  1609. * This varies depending on the operation.
  1610. * - The "presave", "insert", "update", "delete", "print" and "view"
  1611. * operations have no return value.
  1612. * - The "load" operation should return an array containing pairs
  1613. * of fields => values to be merged into the node object.
  1614. *
  1615. * If you are writing a node module, do not use this hook to perform
  1616. * actions on your type of node alone. Instead, use the hooks set aside
  1617. * for node modules, such as hook_insert() and hook_form(). That said, for
  1618. * some operations, such as "delete revision" or "rss item" there is no
  1619. * corresponding hook so even the module defining the node will need to
  1620. * implement hook_nodeapi().
  1621. */
  1622. function hook_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  1623. switch ($op) {
  1624. case 'presave':
  1625. if ($node->nid && $node->moderate) {
  1626. // Reset votes when node is updated:
  1627. $node->score = 0;
  1628. $node->users = '';
  1629. $node->votes = 0;
  1630. }
  1631. break;
  1632. case 'insert':
  1633. case 'update':
  1634. if ($node->moderate && user_access('access submission queue')) {
  1635. drupal_set_message(t('The post is queued for approval'));
  1636. }
  1637. elseif ($node->moderate) {
  1638. drupal_set_message(t('The post is queued for approval. The editors will decide whether it should be published.'));
  1639. }
  1640. break;
  1641. case 'view':
  1642. $node->content['my_additional_field'] = array(
  1643. '#value' => theme('mymodule_my_additional_field', $additional_field),
  1644. '#weight' => 10,
  1645. );
  1646. break;
  1647. }
  1648. }
  1649. /**
  1650. * Allow modules to modify the OpenID request parameters.
  1651. *
  1652. * @param $op
  1653. * The operation to be performed.
  1654. * Possible values:
  1655. * - request: Modify parameters before they are sent to the OpenID provider.
  1656. * @param $request
  1657. * An associative array of parameter defaults to which to modify or append.
  1658. * @return
  1659. * An associative array of parameters to be merged with the default list.
  1660. *
  1661. */
  1662. function hook_openid($op, $request) {
  1663. if ($op == 'request') {
  1664. $request['openid.identity'] = 'http://myname.myopenid.com/';
  1665. }
  1666. return $request;
  1667. }
  1668. /**
  1669. * Define user permissions.
  1670. *
  1671. * This hook can supply permissions that the module defines, so that they
  1672. * can be selected on the user permissions page and used to grant or restrict
  1673. * access to actions the module performs.
  1674. *
  1675. * Permissions are checked using user_access().
  1676. *
  1677. * For a detailed usage example, see page_example.module.
  1678. *
  1679. * @return
  1680. * An array of permission strings. The strings must not be wrapped with
  1681. * the t() function, since the string extractor takes care of
  1682. * extracting permission names defined in the perm hook for
  1683. * translation.
  1684. */
  1685. function hook_perm() {
  1686. return array('administer my module');
  1687. }
  1688. /**
  1689. * Ping another server.
  1690. *
  1691. * This hook allows a module to notify other sites of updates on your
  1692. * Drupal site.
  1693. *
  1694. * @param $name
  1695. * The name of your Drupal site.
  1696. * @param $url
  1697. * The URL of your Drupal site.
  1698. * @return
  1699. * None.
  1700. */
  1701. function hook_ping($name = '', $url = '') {
  1702. $feed = url('node/feed');
  1703. $client = new xmlrpc_client('/RPC2', 'rpc.weblogs.com', 80);
  1704. $message = new xmlrpcmsg('weblogUpdates.ping',
  1705. array(new xmlrpcval($name), new xmlrpcval($url)));
  1706. $result = $client->send($message);
  1707. if (!$result || $result->faultCode()) {
  1708. watchdog('error', 'failed to notify "weblogs.com" (site)');
  1709. }
  1710. unset($client);
  1711. }
  1712. /**
  1713. * Define a custom search routine.
  1714. *
  1715. * This hook allows a module to perform searches on content it defines
  1716. * (custom node types, users, or comments, for example) when a site search
  1717. * is performed.
  1718. *
  1719. * Note that you can use form API to extend the search. You will need to use
  1720. * hook_form_alter() to add any additional required form elements. You can
  1721. * process their values on submission using a custom validation function.
  1722. * You will need to merge any custom search values into the search keys
  1723. * using a key:value syntax. This allows all search queries to have a clean
  1724. * and permanent URL. See node_form_alter() for an example.
  1725. *
  1726. * The example given here is for node.module, which uses the indexed search
  1727. * capabilities. To do this, node module also implements hook_update_index()
  1728. * which is used to create and maintain the index.
  1729. *
  1730. * We call do_search() with the keys, the module name, and extra SQL fragments
  1731. * to use when searching. See hook_update_index() for more information.
  1732. *
  1733. * @param $op
  1734. * A string defining which operation to perform:
  1735. * - 'admin': The hook should return a form array, containing any fieldsets
  1736. * the module wants to add to the Search settings page at
  1737. * admin/settings/search.
  1738. * - 'name': The hook should return a translated name defining the type of
  1739. * items that are searched for with this module ('content', 'users', ...).
  1740. * - 'reset': The search index is going to be rebuilt. Modules which use
  1741. * hook_update_index() should update their indexing bookkeeping so that it
  1742. * starts from scratch the next time hook_update_index() is called.
  1743. * - 'search': The hook should perform a search using the keywords in $keys.
  1744. * - 'status': If the module implements hook_update_index(), it should return
  1745. * an array containing the following keys:
  1746. * - remaining: The amount of items that still need to be indexed.
  1747. * - total: The total amount of items (both indexed and unindexed).
  1748. * @param $keys
  1749. * The search keywords as entered by the user.
  1750. * @return
  1751. * This varies depending on the operation.
  1752. * - 'admin': The form array for the Search settings page at
  1753. * admin/settings/search.
  1754. * - 'name': The translated string of 'Content'.
  1755. * - 'reset': None.
  1756. * - 'search': An array of search results. To use the default search result
  1757. * display, each item should have the following keys':
  1758. * - 'link': Required. The URL of the found item.
  1759. * - 'type': The type of item.
  1760. * - 'title': Required. The name of the item.
  1761. * - 'user': The author of the item.
  1762. * - 'date': A timestamp when the item was last modified.
  1763. * - 'extra': An array of optional extra information items.
  1764. * - 'snippet': An excerpt or preview to show with the result (can be
  1765. * generated with search_excerpt()).
  1766. * - 'status': An associative array with the key-value pairs:
  1767. * - 'remaining': The number of items left to index.
  1768. * - 'total': The total number of items to index.
  1769. *
  1770. * @ingroup search
  1771. */
  1772. function hook_search($op = 'search', $keys = NULL) {
  1773. switch ($op) {
  1774. case 'name':
  1775. return t('Content');
  1776. case 'reset':
  1777. db_query("UPDATE {search_dataset} SET reindex = %d WHERE type = 'node'", time());
  1778. return;
  1779. case 'status':
  1780. $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
  1781. $remaining = db_result(db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE n.status = 1 AND (d.sid IS NULL OR d.reindex <> 0)"));
  1782. return array('remaining' => $remaining, 'total' => $total);
  1783. case 'admin':
  1784. $form = array();
  1785. // Output form for defining rank factor weights.
  1786. $form['content_ranking'] = array(
  1787. '#type' => 'fieldset',
  1788. '#title' => t('Content ranking'),
  1789. );
  1790. $form['content_ranking']['#theme'] = 'node_search_admin';
  1791. $form['content_ranking']['info'] = array(
  1792. '#value' => '<em>'. t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') .'</em>'
  1793. );
  1794. $ranking = array('node_rank_relevance' => t('Keyword relevance'),
  1795. 'node_rank_recent' => t('Recently posted'));
  1796. if (module_exists('comment')) {
  1797. $ranking['node_rank_comments'] = t('Number of comments');
  1798. }
  1799. if (module_exists('statistics') && variable_get('statistics_count_content_views', 0)) {
  1800. $ranking['node_rank_views'] = t('Number of views');
  1801. }
  1802. // Note: reversed to reflect that higher number = higher ranking.
  1803. $options = drupal_map_assoc(range(0, 10));
  1804. foreach ($ranking as $var => $title) {
  1805. $form['content_ranking']['factors'][$var] = array(
  1806. '#title' => $title,
  1807. '#type' => 'select',
  1808. '#options' => $options,
  1809. '#default_value' => variable_get($var, 5),
  1810. );
  1811. }
  1812. return $form;
  1813. case 'search':
  1814. // Build matching conditions
  1815. list($join1, $where1) = _db_rewrite_sql();
  1816. $arguments1 = array();
  1817. $conditions1 = 'n.status = 1';
  1818. if ($type = search_query_extract($keys, 'type')) {
  1819. $types = array();
  1820. foreach (explode(',', $type) as $t) {
  1821. $types[] = "n.type = '%s'";
  1822. $arguments1[] = $t;
  1823. }
  1824. $conditions1 .= ' AND ('. implode(' OR ', $types) .')';
  1825. $keys = search_query_insert($keys, 'type');
  1826. }
  1827. if ($category = search_query_extract($keys, 'category')) {
  1828. $categories = array();
  1829. foreach (explode(',', $category) as $c) {
  1830. $categories[] = "tn.tid = %d";
  1831. $arguments1[] = $c;
  1832. }
  1833. $conditions1 .= ' AND ('. implode(' OR ', $categories) .')';
  1834. $join1 .= ' INNER JOIN {term_node} tn ON n.vid = tn.vid';
  1835. $keys = search_query_insert($keys, 'category');
  1836. }
  1837. // Build ranking expression (we try to map each parameter to a
  1838. // uniform distribution in the range 0..1).
  1839. $ranking = array();
  1840. $arguments2 = array();
  1841. $join2 = '';
  1842. // Used to avoid joining on node_comment_statistics twice
  1843. $stats_join = FALSE;
  1844. $total = 0;
  1845. if ($weight = (int)variable_get('node_rank_relevance', 5)) {
  1846. // Average relevance values hover around 0.15
  1847. $ranking[] = '%d * i.relevance';
  1848. $arguments2[] = $weight;
  1849. $total += $weight;
  1850. }
  1851. if ($weight = (int)variable_get('node_rank_recent', 5)) {
  1852. // Exponential decay with half-life of 6 months, starting at last indexed node
  1853. $ranking[] = '%d * POW(2, (GREATEST(MAX(n.created), MAX(n.changed), MAX(c.last_comment_timestamp)) - %d) * 6.43e-8)';
  1854. $arguments2[] = $weight;
  1855. $arguments2[] = (int)variable_get('node_cron_last', 0);
  1856. $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
  1857. $stats_join = TRUE;
  1858. $total += $weight;
  1859. }
  1860. if (module_exists('comment') && $weight = (int)variable_get('node_rank_comments', 5)) {
  1861. // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
  1862. $scale = variable_get('node_cron_comments_scale', 0.0);
  1863. $ranking[] = '%d * (2.0 - 2.0 / (1.0 + MAX(c.comment_count) * %f))';
  1864. $arguments2[] = $weight;
  1865. $arguments2[] = $scale;
  1866. if (!$stats_join) {
  1867. $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
  1868. }
  1869. $total += $weight;
  1870. }
  1871. if (module_exists('statistics') && variable_get('statistics_count_content_views', 0) &&
  1872. $weight = (int)variable_get('node_rank_views', 5)) {
  1873. // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
  1874. $scale = variable_get('node_cron_views_scale', 0.0);
  1875. $ranking[] = '%d * (2.0 - 2.0 / (1.0 + MAX(nc.totalcount) * %f))';
  1876. $arguments2[] = $weight;
  1877. $arguments2[] = $scale;
  1878. $join2 .= ' LEFT JOIN {node_counter} nc ON nc.nid = i.sid';
  1879. $total += $weight;
  1880. }
  1881. // When all search factors are disabled (ie they have a weight of zero),
  1882. // the default score is based only on keyword relevance and there is no need to
  1883. // adjust the score of each item.
  1884. if ($total == 0) {
  1885. $select2 = 'i.relevance AS score';
  1886. $total = 1;
  1887. }
  1888. else {
  1889. $select2 = implode(' + ', $ranking) . ' AS score';
  1890. }
  1891. // Do search.
  1892. $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid '. $join1, $conditions1 . (empty($where1) ? '' : ' AND '. $where1), $arguments1, $select2, $join2, $arguments2);
  1893. // Load results.
  1894. $results = array();
  1895. foreach ($find as $item) {
  1896. // Build the node body.
  1897. $node = node_load($item->sid);
  1898. $node->build_mode = NODE_BUILD_SEARCH_RESULT;
  1899. $node = node_build_content($node, FALSE, FALSE);
  1900. $node->body = drupal_render($node->content);
  1901. // Fetch comments for snippet.
  1902. $node->body .= module_invoke('comment', 'nodeapi', $node, 'update index');
  1903. // Fetch terms for snippet.
  1904. $node->body .= module_invoke('taxonomy', 'nodeapi', $node, 'update index');
  1905. $extra = node_invoke_nodeapi($node, 'search result');
  1906. $results[] = array(
  1907. 'link' => url('node/'. $item->sid, array('absolute' => TRUE)),
  1908. 'type' => check_plain(node_get_types('name', $node)),
  1909. 'title' => $node->title,
  1910. 'user' => theme('username', $node),
  1911. 'date' => $node->changed,
  1912. 'node' => $node,
  1913. 'extra' => $extra,
  1914. 'score' => $item->score / $total,
  1915. 'snippet' => search_excerpt($keys, $node->body),
  1916. );
  1917. }
  1918. return $results;
  1919. }
  1920. }
  1921. /**
  1922. * Preprocess text for the search index.
  1923. *
  1924. * This hook is called both for text added to the search index, as well as
  1925. * the keywords users have submitted for searching.
  1926. *
  1927. * This is required for example to allow Japanese or Chinese text to be
  1928. * searched. As these languages do not use spaces, it needs to be split into
  1929. * separate words before it can be indexed. There are various external
  1930. * libraries for this.
  1931. *
  1932. * @param $text
  1933. * The text to split. This is a single piece of plain-text that was
  1934. * extracted from between two HTML tags. Will not contain any HTML entities.
  1935. * @return
  1936. * The text after processing.
  1937. */
  1938. function hook_search_preprocess($text) {
  1939. // Do processing on $text
  1940. return $text;
  1941. }
  1942. /**
  1943. * Override the rendering of search results.
  1944. *
  1945. * A module that implements hook_search() to define a type of search
  1946. * may implement this hook in order to override the default theming of
  1947. * its search results, which is otherwise themed using
  1948. * theme('search_results').
  1949. *
  1950. * Note that by default, theme('search_results') and
  1951. * theme('search_result') work together to create a definition
  1952. * list. So your hook_search_page() implementation should probably do
  1953. * this as well.
  1954. *
  1955. * @see search-result.tpl.php
  1956. * @see search-results.tpl.php
  1957. *
  1958. * @param $results
  1959. * An array of search results.
  1960. * @return
  1961. * An HTML string containing the formatted search results, with
  1962. * a pager included.
  1963. */
  1964. function hook_search_page($results) {
  1965. $output = '<dl class="search-results">';
  1966. foreach ($results as $entry) {
  1967. $output .= theme('search_result', $entry, $type);
  1968. }
  1969. $output .= '</dl>';
  1970. $output .= theme('pager', NULL);
  1971. return $output;
  1972. }
  1973. /**
  1974. * Act on taxonomy changes.
  1975. *
  1976. * This hook allows modules to take action when the terms and vocabularies
  1977. * in the taxonomy are modified.
  1978. *
  1979. * @param $op
  1980. * What is being done to $array. Possible values:
  1981. * - "delete"
  1982. * - "insert"
  1983. * - "update"
  1984. * @param $type
  1985. * What manner of item $array is. Possible values:
  1986. * - "term"
  1987. * - "vocabulary"
  1988. * @param $array
  1989. * The item on which $op is being performed. Possible values:
  1990. * - for vocabularies, 'insert' and 'update' ops:
  1991. * $form_values from taxonomy_form_vocabulary_submit()
  1992. * - for vocabularies, 'delete' op:
  1993. * $vocabulary from taxonomy_get_vocabulary() cast to an array
  1994. * - for terms, 'insert' and 'update' ops:
  1995. * $form_values from taxonomy_form_term_submit()
  1996. * - for terms, 'delete' op:
  1997. * $term from taxonomy_get_term() cast to an array
  1998. * @return
  1999. * None.
  2000. */
  2001. function hook_taxonomy($op, $type, $array = NULL) {
  2002. if ($type == 'vocabulary' && ($op == 'insert' || $op == 'update')) {
  2003. if (variable_get('forum_nav_vocabulary', '') == ''
  2004. && in_array('forum', $array['nodes'])) {
  2005. // since none is already set, silently set this vocabulary as the
  2006. // navigation vocabulary
  2007. variable_set('forum_nav_vocabulary', $array['vid']);
  2008. }
  2009. }
  2010. }
  2011. /**
  2012. * Register a module (or theme's) theme implementations.
  2013. *
  2014. * Modules and themes implementing this hook return an array of arrays. The key
  2015. * to each sub-array is the internal name of the hook, and the array contains
  2016. * information about the hook. Each array may contain the following elements:
  2017. *
  2018. * - arguments: (required) An array of arguments that this theme hook uses. This
  2019. * value allows the theme layer to properly utilize templates. The array keys
  2020. * represent the name of the variable, and the value will be used as the
  2021. * default value if not passed to the theme() function. These arguments must
  2022. * be in the same order that they will be given to the theme() function.
  2023. * Default values will only be passed to templates. If you want your theme
  2024. * function to assume defaults, specify them as usual in the argument list in
  2025. * the theme_HOOK_NAME() default implementation.
  2026. * - file: The file the implementation resides in. This file will be included
  2027. * prior to the theme being rendered, to make sure that the function or
  2028. * preprocess function (as needed) is actually loaded; this makes it possible
  2029. * to split theme functions out into separate files quite easily.
  2030. * - path: Override the path of the file to be used. Ordinarily the module or
  2031. * theme path will be used, but if the file will not be in the default path,
  2032. * include it here. This path should be relative to the Drupal root directory.
  2033. * - template: If specified, this theme implementation is a template, and this
  2034. * is the template file without an extension. Do not put .tpl.php on this
  2035. * file; that extension will be added automatically by the default rendering
  2036. * engine (which is PHPTemplate). If 'path', above, is specified, the template
  2037. * should also be in this path.
  2038. * - function: If specified, this will be the function name to invoke for this
  2039. * implementation. If neither 'template' nor 'function' is specified, a
  2040. * default function name will be assumed. For example, if a module registers
  2041. * the 'node' theme hook, 'theme_node' will be assigned to its function. If
  2042. * the chameleon theme registers the node hook, it will be assigned
  2043. * 'chameleon_node' as its function.
  2044. * - pattern: A regular expression pattern to be used to allow this theme
  2045. * implementation to have a dynamic name. The convention is to use __ to
  2046. * differentiate the dynamic portion of the theme. For example, to allow
  2047. * forums to be themed individually, the pattern might be: 'forum__'. Then,
  2048. * when the forum is themed, call: theme(array('forum__'. $tid, 'forum'),
  2049. * $forum).
  2050. * - preprocess functions: A list of functions used to preprocess this data.
  2051. * Ordinarily this won't be used; it's automatically filled in. By default,
  2052. * for a module this will be filled in as template_preprocess_HOOK. For a
  2053. * theme this will be filled in as phptemplate_preprocess and
  2054. * phptemplate_preprocess_HOOK as well as themename_preprocess and
  2055. * themename_preprocess_HOOK.
  2056. * - override preprocess functions: Set to TRUE when a theme does NOT want the
  2057. * standard preprocess functions to run. This can be used to give a theme FULL
  2058. * control over how variables are set. For example, if a theme wants total
  2059. * control over how certain variables in the page.tpl.php are set, this can be
  2060. * set to true. Please keep in mind that when this is use by a theme, that
  2061. * theme becomes responsible for making sure necessary variables are set.
  2062. * - type: (automatically derived) Where the theme hook is defined: 'module',
  2063. * 'theme_engine', or 'theme'.
  2064. * - theme path: (automatically derived) The directory path of the theme or
  2065. * module, so that it doesn't need to be looked up.
  2066. * - theme paths: (automatically derived) An array of template suggestions where
  2067. * .tpl.php files related to this theme hook may be found.
  2068. *
  2069. * The following parameters are all optional.
  2070. *
  2071. * @param $existing
  2072. * An array of existing implementations that may be used for override
  2073. * purposes. This is primarily useful for themes that may wish to examine
  2074. * existing implementations to extract data (such as arguments) so that
  2075. * it may properly register its own, higher priority implementations.
  2076. * @param $type
  2077. * What 'type' is being processed. This is primarily useful so that themes
  2078. * tell if they are the actual theme being called or a parent theme.
  2079. * May be one of:
  2080. * - module: A module is being checked for theme implementations.
  2081. * - base_theme_engine: A theme engine is being checked for a theme which is a
  2082. * parent of the actual theme being used.
  2083. * - theme_engine: A theme engine is being checked for the actual theme being
  2084. * used.
  2085. * - base_theme: A base theme is being checked for theme implementations.
  2086. * - theme: The actual theme in use is being checked.
  2087. * @param $theme
  2088. * The actual name of theme that is being being checked (mostly only useful
  2089. * for theme engine).
  2090. * @param $path
  2091. * The directory path of the theme or module, so that it doesn't need to be
  2092. * looked up.
  2093. *
  2094. * @return
  2095. * A keyed array of theme hooks.
  2096. */
  2097. function hook_theme($existing, $type, $theme, $path) {
  2098. return array(
  2099. 'forum_display' => array(
  2100. 'arguments' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
  2101. ),
  2102. 'forum_list' => array(
  2103. 'arguments' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
  2104. ),
  2105. 'forum_topic_list' => array(
  2106. 'arguments' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
  2107. ),
  2108. 'forum_icon' => array(
  2109. 'arguments' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0),
  2110. ),
  2111. 'forum_topic_navigation' => array(
  2112. 'arguments' => array('node' => NULL),
  2113. ),
  2114. 'node' => array(
  2115. 'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
  2116. 'template' => 'node',
  2117. ),
  2118. 'node_filter_form' => array(
  2119. 'arguments' => array('form' => NULL),
  2120. 'file' => 'node.admin.inc',
  2121. ),
  2122. );
  2123. }
  2124. /**
  2125. * Alter the theme registry information returned from hook_theme().
  2126. *
  2127. * The theme registry stores information about all available theme hooks,
  2128. * including which callback functions those hooks will call when triggered,
  2129. * what template files are exposed by these hooks, and so on.
  2130. *
  2131. * Note that this hook is only executed as the theme cache is re-built.
  2132. * Changes here will not be visible until the next cache clear.
  2133. *
  2134. * The $theme_registry array is keyed by theme hook name, and contains the
  2135. * information returned from hook_theme(), as well as additional properties
  2136. * added by _theme_process_registry().
  2137. *
  2138. * For example:
  2139. * @code
  2140. * $theme_registry['user_profile'] = array(
  2141. * 'arguments' => array(
  2142. * 'account' => NULL,
  2143. * ),
  2144. * 'template' => 'modules/user/user-profile',
  2145. * 'file' => 'modules/user/user.pages.inc',
  2146. * 'type' => 'module',
  2147. * 'theme path' => 'modules/user',
  2148. * 'theme paths' => array(
  2149. * 0 => 'modules/user',
  2150. * ),
  2151. * 'preprocess functions' => array(
  2152. * 0 => 'template_preprocess',
  2153. * 1 => 'template_preprocess_user_profile',
  2154. * ),
  2155. * );
  2156. * @endcode
  2157. *
  2158. * @param $theme_registry
  2159. * The entire cache of theme registry information, post-processing.
  2160. *
  2161. * @see hook_theme()
  2162. * @see _theme_process_registry()
  2163. */
  2164. function hook_theme_registry_alter(&$theme_registry) {
  2165. // Kill the next/previous forum topic navigation links.
  2166. foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
  2167. if ($value == 'template_preprocess_forum_topic_navigation') {
  2168. unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
  2169. }
  2170. }
  2171. }
  2172. /**
  2173. * Preprocess theme variables for template files.
  2174. *
  2175. * This hook allows modules to preprocess theme variables for theme templates.
  2176. * It is only called for theme hooks implemented as template files, but
  2177. * not for those implemented as theme functions. The purpose of this hook is
  2178. * to allow modules to add to or override variables for all template files.
  2179. *
  2180. * For more detailed information, see theme().
  2181. *
  2182. * @param $variables
  2183. * The variables array (modify in place).
  2184. * @param $hook
  2185. * The name of the theme hook.
  2186. */
  2187. function hook_preprocess(&$variables, $hook) {
  2188. // Add the name of the current theme hook as a variable
  2189. $variables['theme_hook'] = $hook;
  2190. }
  2191. /**
  2192. * Preprocess theme variables for a specific theme hook.
  2193. *
  2194. * This hook allows modules to preprocess theme variables for a specific theme
  2195. * hook. It should only be used if a module needs to override or add to the
  2196. * theme preprocessing for a theme hook it didn't define.
  2197. *
  2198. * Note that, as all preprocess hooks, this hook is only invoked for theme hooks
  2199. * implemented as template files, but not those implemented as theme functions.
  2200. *
  2201. * For more detailed information, see theme().
  2202. *
  2203. * @param $variables
  2204. * The variables array (modify in place).
  2205. */
  2206. function hook_preprocess_HOOK(&$variables) {
  2207. $variables['drupal_major_version'] = '6.x';
  2208. }
  2209. /**
  2210. * Update Drupal's full-text index for this module.
  2211. *
  2212. * Modules can implement this hook if they want to use the full-text indexing
  2213. * mechanism in Drupal.
  2214. *
  2215. * This hook is called every cron run if search.module is enabled. A module
  2216. * should check which of its items were modified or added since the last
  2217. * run. It is advised that you implement a throttling mechanism which indexes
  2218. * at most 'search_cron_limit' items per run (see example below).
  2219. *
  2220. * You should also be aware that indexing may take too long and be aborted if
  2221. * there is a PHP time limit. That's why you should update your internal
  2222. * bookkeeping multiple times per run, preferably after every item that
  2223. * is indexed.
  2224. *
  2225. * Per item that needs to be indexed, you should call search_index() with
  2226. * its content as a single HTML string. The search indexer will analyse the
  2227. * HTML and use it to assign higher weights to important words (such as
  2228. * titles). It will also check for links that point to nodes, and use them to
  2229. * boost the ranking of the target nodes.
  2230. *
  2231. * @ingroup search
  2232. */
  2233. function hook_update_index() {
  2234. $last = variable_get('node_cron_last', 0);
  2235. $limit = (int)variable_get('search_cron_limit', 100);
  2236. $result = db_query_range('SELECT n.nid, c.last_comment_timestamp FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND n.moderate = 0 AND (n.created > %d OR n.changed > %d OR c.last_comment_timestamp > %d) ORDER BY GREATEST(n.created, n.changed, c.last_comment_timestamp) ASC', $last, $last, $last, 0, $limit);
  2237. while ($node = db_fetch_object($result)) {
  2238. $last_comment = $node->last_comment_timestamp;
  2239. $node = node_load(array('nid' => $node->nid));
  2240. // We update this variable per node in case cron times out, or if the node
  2241. // cannot be indexed (PHP nodes which call drupal_goto, for example).
  2242. // In rare cases this can mean a node is only partially indexed, but the
  2243. // chances of this happening are very small.
  2244. variable_set('node_cron_last', max($last_comment, $node->changed, $node->created));
  2245. // Get node output (filtered and with module-specific fields).
  2246. if (node_hook($node, 'view')) {
  2247. node_invoke($node, 'view', false, false);
  2248. }
  2249. else {
  2250. $node = node_prepare($node, false);
  2251. }
  2252. // Allow modules to change $node->body before viewing.
  2253. node_invoke_nodeapi($node, 'view', false, false);
  2254. $text = '<h1>'. drupal_specialchars($node->title) .'</h1>'. $node->body;
  2255. // Fetch extra data normally not visible
  2256. $extra = node_invoke_nodeapi($node, 'update index');
  2257. foreach ($extra as $t) {
  2258. $text .= $t;
  2259. }
  2260. // Update index
  2261. search_index($node->nid, 'node', $text);
  2262. }
  2263. }
  2264. /**
  2265. * Act on user account actions.
  2266. *
  2267. * This hook allows modules to react when operations are performed on user
  2268. * accounts.
  2269. *
  2270. * @param $op
  2271. * What kind of action is being performed. Possible values (in alphabetical
  2272. * order):
  2273. * - after_update: The user object has been updated and changed. Use this
  2274. * (probably along with 'insert') if you want to reuse some information from
  2275. * the user object.
  2276. * - categories: A set of user information categories is requested.
  2277. * - delete: The user account is being deleted. The module should remove its
  2278. * custom additions to the user object from the database.
  2279. * - form: The user account edit form is about to be displayed. The module
  2280. * should present the form elements it wishes to inject into the form.
  2281. * - insert: The user account is being added. The module should save its
  2282. * custom additions to the user object into the database and set the saved
  2283. * fields to NULL in $edit.
  2284. * - load: The user account is being loaded. The module may respond to this
  2285. * and insert additional information into the user object.
  2286. * - login: The user just logged in.
  2287. * - logout: The user just logged out.
  2288. * - register: The user account registration form is about to be displayed.
  2289. * The module should present the form elements it wishes to inject into the
  2290. * form.
  2291. * - submit: Modify the account before it gets saved.
  2292. * - update: The user account is being changed. The module should save its
  2293. * custom additions to the user object into the database and set the saved
  2294. * fields to NULL in $edit.
  2295. * - validate: The user account is about to be modified. The module should
  2296. * validate its custom additions to the user object, registering errors as
  2297. * necessary.
  2298. * - view: The user's account information is being displayed. The module
  2299. * should format its custom additions for display, and add them to the
  2300. * $account->content array.
  2301. * @param $edit
  2302. * The array of form values submitted by the user.
  2303. * @param $account
  2304. * The user object on which the operation is being performed.
  2305. * @param $category
  2306. * The active category of user information being edited.
  2307. *
  2308. * @return
  2309. * This varies depending on the operation.
  2310. * - categories: An array of associative arrays representing the categories
  2311. * added by the implementing module. Each array can have the following
  2312. * keys:
  2313. * - name: The internal name of the category.
  2314. * - title: The human-readable, localized name of the category.
  2315. * - weight: An integer specifying the category's sort ordering.
  2316. * - access callback: Name of a menu access callback function to use when
  2317. * editing this category. Defaults to using user_edit_access() if not
  2318. * specified. See hook_menu() for more information on menu access
  2319. * callbacks.
  2320. * - access arguments: Arguments for the access callback function.
  2321. * Defaults to array(1) if not specified.
  2322. * - delete: None.
  2323. * - form, register: An array containing the form elements to add to the form.
  2324. * - insert: None.
  2325. * - load: None.
  2326. * - login: None.
  2327. * - logout: None.
  2328. * - submit: None.
  2329. * - update: None.
  2330. * - validate: None.
  2331. * - view: None.
  2332. */
  2333. function hook_user($op, &$edit, &$account, $category = NULL) {
  2334. if ($op == 'form' && $category == 'account') {
  2335. $form['comment_settings'] = array(
  2336. '#type' => 'fieldset',
  2337. '#title' => t('Comment settings'),
  2338. '#collapsible' => TRUE,
  2339. '#weight' => 4);
  2340. $form['comment_settings']['signature'] = array(
  2341. '#type' => 'textarea',
  2342. '#title' => t('Signature'),
  2343. '#default_value' => $edit['signature'],
  2344. '#description' => t('Your signature will be publicly displayed at the end of your comments.'));
  2345. return $form;
  2346. }
  2347. }
  2348. /**
  2349. * Add mass user operations.
  2350. *
  2351. * This hook enables modules to inject custom operations into the mass operations
  2352. * dropdown found at admin/user/user, by associating a callback function with
  2353. * the operation, which is called when the form is submitted. The callback function
  2354. * receives one initial argument, which is an array of the checked users.
  2355. *
  2356. * @return
  2357. * An array of operations. Each operation is an associative array that may
  2358. * contain the following key-value pairs:
  2359. * - "label": Required. The label for the operation, displayed in the dropdown menu.
  2360. * - "callback": Required. The function to call for the operation.
  2361. * - "callback arguments": Optional. An array of additional arguments to pass to
  2362. * the callback function.
  2363. *
  2364. */
  2365. function hook_user_operations() {
  2366. $operations = array(
  2367. 'unblock' => array(
  2368. 'label' => t('Unblock the selected users'),
  2369. 'callback' => 'user_user_operations_unblock',
  2370. ),
  2371. 'block' => array(
  2372. 'label' => t('Block the selected users'),
  2373. 'callback' => 'user_user_operations_block',
  2374. ),
  2375. 'delete' => array(
  2376. 'label' => t('Delete the selected users'),
  2377. ),
  2378. );
  2379. return $operations;
  2380. }
  2381. /**
  2382. * Register XML-RPC callbacks.
  2383. *
  2384. * This hook lets a module register callback functions to be called when
  2385. * particular XML-RPC methods are invoked by a client.
  2386. *
  2387. * @return
  2388. * An array which maps XML-RPC methods to Drupal functions. Each array
  2389. * element is either a pair of method => function or an array with four
  2390. * entries:
  2391. * - The XML-RPC method name (for example, module.function).
  2392. * - The Drupal callback function (for example, module_function).
  2393. * - The method signature is an array of XML-RPC types. The first element
  2394. * of this array is the type of return value and then you should write a
  2395. * list of the types of the parameters. XML-RPC types are the following
  2396. * (See the types at @link http://www.xmlrpc.com/spec http://www.xmlrpc.com/spec @endlink ):
  2397. * - "boolean": 0 (false) or 1 (true).
  2398. * - "double": a floating point number (for example, -12.214).
  2399. * - "int": a integer number (for example, -12).
  2400. * - "array": an array without keys (for example, array(1, 2, 3)).
  2401. * - "struct": an associative array or an object (for example,
  2402. * array('one' => 1, 'two' => 2)).
  2403. * - "date": when you return a date, then you may either return a
  2404. * timestamp (time(), mktime() etc.) or an ISO8601 timestamp. When
  2405. * date is specified as an input parameter, then you get an object,
  2406. * which is described in the function xmlrpc_date
  2407. * - "base64": a string containing binary data, automatically
  2408. * encoded/decoded automatically.
  2409. * - "string": anything else, typically a string.
  2410. * - A descriptive help string, enclosed in a t() function for translation
  2411. * purposes.
  2412. * Both forms are shown in the example.
  2413. */
  2414. function hook_xmlrpc() {
  2415. return array(
  2416. 'drupal.login' => 'drupal_login',
  2417. array(
  2418. 'drupal.site.ping',
  2419. 'drupal_directory_ping',
  2420. array('boolean', 'string', 'string', 'string', 'string', 'string'),
  2421. t('Handling ping request'))
  2422. );
  2423. }
  2424. /**
  2425. * Log an event message
  2426. *
  2427. * This hook allows modules to route log events to custom destinations, such as
  2428. * SMS, Email, pager, syslog, ...etc.
  2429. *
  2430. * @param $log_entry
  2431. * An associative array containing the following keys:
  2432. * - type: The type of message for this entry. For contributed modules, this is
  2433. * normally the module name. Do not use 'debug', use severity WATCHDOG_DEBUG instead.
  2434. * - user: The user object for the user who was logged in when the event happened.
  2435. * - request_uri: The Request URI for the page the event happened in.
  2436. * - referer: The page that referred the use to the page where the event occurred.
  2437. * - ip: The IP address where the request for the page came from.
  2438. * - timestamp: The UNIX timetamp of the date/time the event occurred
  2439. * - severity: One of the following values as defined in RFC 3164 http://www.faqs.org/rfcs/rfc3164.html
  2440. * WATCHDOG_EMERG Emergency: system is unusable
  2441. * WATCHDOG_ALERT Alert: action must be taken immediately
  2442. * WATCHDOG_CRITICAL Critical: critical conditions
  2443. * WATCHDOG_ERROR Error: error conditions
  2444. * WATCHDOG_WARNING Warning: warning conditions
  2445. * WATCHDOG_NOTICE Notice: normal but significant condition
  2446. * WATCHDOG_INFO Informational: informational messages
  2447. * WATCHDOG_DEBUG Debug: debug-level messages
  2448. * - link: an optional link provided by the module that called the watchdog() function.
  2449. * - message: The text of the message to be logged.
  2450. *
  2451. * @return
  2452. * None.
  2453. */
  2454. function hook_watchdog($log_entry) {
  2455. global $base_url, $language;
  2456. $severity_list = array(
  2457. WATCHDOG_EMERG => t('Emergency'),
  2458. WATCHDOG_ALERT => t('Alert'),
  2459. WATCHDOG_CRITICAL => t('Critical'),
  2460. WATCHDOG_ERROR => t('Error'),
  2461. WATCHDOG_WARNING => t('Warning'),
  2462. WATCHDOG_NOTICE => t('Notice'),
  2463. WATCHDOG_INFO => t('Info'),
  2464. WATCHDOG_DEBUG => t('Debug'),
  2465. );
  2466. $to = 'someone@example.com';
  2467. $params = array();
  2468. $params['subject'] = t('[@site_name] @severity_desc: Alert from your web site', array(
  2469. '@site_name' => variable_get('site_name', 'Drupal'),
  2470. '@severity_desc' => $severity_list[$log_entry['severity']]
  2471. ));
  2472. $params['message'] = "\nSite: @base_url";
  2473. $params['message'] .= "\nSeverity: (@severity) @severity_desc";
  2474. $params['message'] .= "\nTimestamp: @timestamp";
  2475. $params['message'] .= "\nType: @type";
  2476. $params['message'] .= "\nIP Address: @ip";
  2477. $params['message'] .= "\nRequest URI: @request_uri";
  2478. $params['message'] .= "\nReferrer URI: @referer_uri";
  2479. $params['message'] .= "\nUser: (@uid) @name";
  2480. $params['message'] .= "\nLink: @link";
  2481. $params['message'] .= "\nMessage: \n\n@message";
  2482. $params['message'] = t($params['message'], array(
  2483. '@base_url' => $base_url,
  2484. '@severity' => $log_entry['severity'],
  2485. '@severity_desc' => $severity_list[$log_entry['severity']],
  2486. '@timestamp' => format_date($log_entry['timestamp']),
  2487. '@type' => $log_entry['type'],
  2488. '@ip' => $log_entry['ip'],
  2489. '@request_uri' => $log_entry['request_uri'],
  2490. '@referer_uri' => $log_entry['referer'],
  2491. '@uid' => $log_entry['user']->uid,
  2492. '@name' => $log_entry['user']->name,
  2493. '@link' => strip_tags($log_entry['link']),
  2494. '@message' => strip_tags($log_entry['message']),
  2495. ));
  2496. drupal_mail('emaillog', 'log', $to, $language, $params);
  2497. }
  2498. /**
  2499. * Prepare a message based on parameters; called from drupal_mail().
  2500. *
  2501. * @param $key
  2502. * An identifier of the mail.
  2503. * @param $message
  2504. * An array to be filled in. Keys in this array include:
  2505. * - 'id':
  2506. * An id to identify the mail sent. Look at module source code
  2507. * or drupal_mail() for possible id values.
  2508. * - 'to':
  2509. * The address or addresses the message will be sent to. The
  2510. * formatting of this string must comply with RFC 2822.
  2511. * - 'subject':
  2512. * Subject of the e-mail to be sent. This must not contain any
  2513. * newline characters, or the mail may not be sent properly.
  2514. * drupal_mail() sets this to an empty string when the hook is invoked.
  2515. * - 'body':
  2516. * An array of lines containing the message to be sent. Drupal will format
  2517. * the correct line endings for you. drupal_mail() sets this to an empty array
  2518. * when the hook is invoked.
  2519. * - 'from':
  2520. * The address the message will be marked as being from, which is set by
  2521. * drupal_mail() to either a custom address or the site-wide default email
  2522. * address when the hook is invoked.
  2523. * - 'headers:
  2524. * Associative array containing mail headers, such as From, Sender, MIME-Version,
  2525. * Content-Type, etc. drupal_mail() pre-fills several headers in this array.
  2526. * @param $params
  2527. * An arbitrary array of parameters set by the caller to drupal_mail.
  2528. */
  2529. function hook_mail($key, &$message, $params) {
  2530. $account = $params['account'];
  2531. $context = $params['context'];
  2532. $variables = array(
  2533. '%site_name' => variable_get('site_name', 'Drupal'),
  2534. '%username' => $account->name,
  2535. );
  2536. if ($context['hook'] == 'taxonomy') {
  2537. $object = $params['object'];
  2538. $vocabulary = taxonomy_vocabulary_load($object->vid);
  2539. $variables += array(
  2540. '%term_name' => $object->name,
  2541. '%term_description' => $object->description,
  2542. '%term_id' => $object->tid,
  2543. '%vocabulary_name' => $vocabulary->name,
  2544. '%vocabulary_description' => $vocabulary->description,
  2545. '%vocabulary_id' => $vocabulary->vid,
  2546. );
  2547. }
  2548. // Node-based variable translation is only available if we have a node.
  2549. if (isset($params['node'])) {
  2550. $node = $params['node'];
  2551. $variables += array(
  2552. '%uid' => $node->uid,
  2553. '%node_url' => url('node/'. $node->nid, array('absolute' => TRUE)),
  2554. '%node_type' => node_get_types('name', $node),
  2555. '%title' => $node->title,
  2556. '%teaser' => $node->teaser,
  2557. '%body' => $node->body,
  2558. );
  2559. }
  2560. $subject = strtr($context['subject'], $variables);
  2561. $body = strtr($context['message'], $variables);
  2562. $message['subject'] .= str_replace(array("\r", "\n"), '', $subject);
  2563. $message['body'][] = drupal_html_to_text($body);
  2564. }
  2565. /**
  2566. * Add a list of cache tables to be cleared.
  2567. *
  2568. * This hook allows your module to add cache table names to the list of cache
  2569. * tables that will be cleared by the Clear button on the Performance page or
  2570. * whenever drupal_flush_all_caches is invoked.
  2571. *
  2572. * @see drupal_flush_all_caches()
  2573. * @see system_clear_cache_submit()
  2574. *
  2575. * @param None.
  2576. *
  2577. * @return
  2578. * An array of cache table names.
  2579. */
  2580. function hook_flush_caches() {
  2581. return array('cache_example');
  2582. }
  2583. /**
  2584. * Allows modules to provide an alternative path for the terms it manages.
  2585. *
  2586. * For vocabularies not maintained by taxonomy.module, give the maintaining
  2587. * module a chance to provide a path for terms in that vocabulary.
  2588. *
  2589. * "Not maintained by taxonomy.module" is misleading. It means that the vocabulary
  2590. * table contains a module name in the 'module' column. Any module may update this
  2591. * column and will then be called to provide an alternative path for the terms
  2592. * it recognizes (manages).
  2593. *
  2594. * This hook should be used rather than hard-coding a "taxonomy/term/xxx" path.
  2595. *
  2596. * @see taxonomy_term_path()
  2597. *
  2598. * @param $term
  2599. * A term object.
  2600. * @return
  2601. * An internal Drupal path.
  2602. */
  2603. function hook_term_path($term) {
  2604. return 'taxonomy/term/'. $term->tid;
  2605. }
  2606. /**
  2607. * Allows modules to define their own text groups that can be translated.
  2608. *
  2609. * @param $op
  2610. * Type of operation. Currently, only supports 'groups'.
  2611. */
  2612. function hook_locale($op = 'groups') {
  2613. switch ($op) {
  2614. case 'groups':
  2615. return array('custom' => t('Custom'));
  2616. }
  2617. }
  2618. /**
  2619. * custom_url_rewrite_outbound is not a hook, it's a function you can add to
  2620. * settings.php to alter all links generated by Drupal. This function is called from url().
  2621. * This function is called very frequently (100+ times per page) so performance is
  2622. * critical.
  2623. *
  2624. * This function should change the value of $path and $options by reference.
  2625. *
  2626. * @param $path
  2627. * The alias of the $original_path as defined in the database.
  2628. * If there is no match in the database it'll be the same as $original_path
  2629. * @param $options
  2630. * An array of link attributes such as querystring and fragment. See url().
  2631. * @param $original_path
  2632. * The unaliased Drupal path that is being linked to.
  2633. */
  2634. function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  2635. global $user;
  2636. // Change all 'node' to 'article'.
  2637. if (preg_match('|^node(/.*)|', $path, $matches)) {
  2638. $path = 'article'. $matches[1];
  2639. }
  2640. // Create a path called 'e' which lands the user on her profile edit page.
  2641. if ($path == 'user/'. $user->uid .'/edit') {
  2642. $path = 'e';
  2643. }
  2644. }
  2645. /**
  2646. * custom_url_rewrite_inbound is not a hook, it's a function you can add to
  2647. * settings.php to alter incoming requests so they map to a Drupal path.
  2648. * This function is called before modules are loaded and
  2649. * the menu system is initialized and it changes $_GET['q'].
  2650. *
  2651. * This function should change the value of $result by reference.
  2652. *
  2653. * @param $result
  2654. * The Drupal path based on the database. If there is no match in the database it'll be the same as $path.
  2655. * @param $path
  2656. * The path to be rewritten.
  2657. * @param $path_language
  2658. * An optional language code to rewrite the path into.
  2659. */
  2660. function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  2661. global $user;
  2662. // Change all article/x requests to node/x
  2663. if (preg_match('|^article(/.*)|', $path, $matches)) {
  2664. $result = 'node'. $matches[1];
  2665. }
  2666. // Redirect a path called 'e' to the user's profile edit page.
  2667. if ($path == 'e') {
  2668. $result = 'user/'. $user->uid .'/edit';
  2669. }
  2670. }
  2671. /**
  2672. * Perform alterations on translation links.
  2673. *
  2674. * A translation link may need to point to a different path or use a translated
  2675. * link text before going through l(), which will just handle the path aliases.
  2676. *
  2677. * @param $links
  2678. * Nested array of links keyed by language code.
  2679. * @param $path
  2680. * The current path.
  2681. * @return
  2682. * None.
  2683. */
  2684. function hook_translation_link_alter(&$links, $path) {
  2685. global $language;
  2686. if (isset($links[$language])) {
  2687. foreach ($links[$language] as $link) {
  2688. $link['attributes']['class'] .= ' active-language';
  2689. }
  2690. }
  2691. }
  2692. /**
  2693. * @} End of "addtogroup hooks".
  2694. */
Login or register to post comments