block.module 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. <?php
  2. /**
  3. * @file
  4. * Controls the visual building blocks a page is constructed with.
  5. */
  6. /**
  7. * Denotes that a block is not enabled in any region and should not be shown.
  8. */
  9. define('BLOCK_REGION_NONE', -1);
  10. /**
  11. * Users cannot control whether or not they see this block.
  12. */
  13. define('BLOCK_CUSTOM_FIXED', 0);
  14. /**
  15. * Shows this block by default, but lets individual users hide it.
  16. */
  17. define('BLOCK_CUSTOM_ENABLED', 1);
  18. /**
  19. * Hides this block by default but lets individual users show it.
  20. */
  21. define('BLOCK_CUSTOM_DISABLED', 2);
  22. /**
  23. * Shows this block on every page except the listed pages.
  24. */
  25. define('BLOCK_VISIBILITY_NOTLISTED', 0);
  26. /**
  27. * Shows this block on only the listed pages.
  28. */
  29. define('BLOCK_VISIBILITY_LISTED', 1);
  30. /**
  31. * Shows this block if the associated PHP code returns TRUE.
  32. */
  33. define('BLOCK_VISIBILITY_PHP', 2);
  34. /**
  35. * Implements hook_help().
  36. */
  37. function block_help($path, $arg) {
  38. switch ($path) {
  39. case 'admin/help#block':
  40. $output = '';
  41. $output .= '<h3>' . t('About') . '</h3>';
  42. $output .= '<p>' . t('The Block module allows you to create boxes of content, which are rendered into an area, or region, of one or more pages of a website. The core Seven administration theme, for example, implements the regions "Content", "Help", "Dashboard main", and "Dashboard sidebar", and a block may appear in any one of these regions. 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. For more information, see the online handbook entry for <a href="@block">Block module</a>.', array('@block' => 'http://drupal.org/documentation/modules/block/', '@blocks' => url('admin/structure/block'))) . '</p>';
  43. $output .= '<h3>' . t('Uses') . '</h3>';
  44. $output .= '<dl>';
  45. $output .= '<dt>' . t('Positioning content') . '</dt>';
  46. $output .= '<dd>' . t('When working with blocks, remember that all themes do <em>not</em> implement the same regions, or display regions in the same way. Blocks are positioned on a per-theme basis. Users with the <em>Administer blocks</em> permission can disable blocks. Disabled blocks are listed on the <a href="@blocks">Blocks administration page</a>, but are not displayed in any region.', array('@block' => 'http://drupal.org/documentation/modules/block/', '@blocks' => url('admin/structure/block'))) . '</dd>';
  47. $output .= '<dt>' . t('Controlling visibility') . '</dt>';
  48. $output .= '<dd>' . t('Blocks can be configured to be visible only on certain pages, only to users of certain roles, or only on pages displaying certain <a href="@content-type">content types</a>. Administrators can also allow specific blocks to be enabled or disabled by users when they edit their <a href="@user">My account</a> page. Some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.', array('@content-type' => url('admin/structure/types'), '@user' => url('user'))) . '</dd>';
  49. $output .= '<dt>' . t('Creating custom blocks') . '</dt>';
  50. $output .= '<dd>' . t('Users with the <em>Administer blocks</em> permission can <a href="@block-add">add custom blocks</a>, which are then listed on the <a href="@blocks">Blocks administration page</a>. Once created, custom blocks behave just like default and module-generated blocks.', array('@blocks' => url('admin/structure/block'), '@block-add' => url('admin/structure/block/add'))) . '</dd>';
  51. $output .= '</dl>';
  52. return $output;
  53. case 'admin/structure/block/add':
  54. return '<p>' . t('Use this page to create a new custom block.') . '</p>';
  55. }
  56. if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {
  57. $demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', 'bartik');
  58. $themes = list_themes();
  59. $output = '<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. Click the <em>configure</em> link next to each block to configure its specific title and visibility settings.') . '</p>';
  60. $output .= '<p>' . l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';
  61. return $output;
  62. }
  63. }
  64. /**
  65. * Implements hook_theme().
  66. */
  67. function block_theme() {
  68. return array(
  69. 'block' => array(
  70. 'render element' => 'elements',
  71. 'template' => 'block',
  72. ),
  73. 'block_admin_display_form' => array(
  74. 'template' => 'block-admin-display-form',
  75. 'file' => 'block.admin.inc',
  76. 'render element' => 'form',
  77. ),
  78. );
  79. }
  80. /**
  81. * Implements hook_permission().
  82. */
  83. function block_permission() {
  84. return array(
  85. 'administer blocks' => array(
  86. 'title' => t('Administer blocks'),
  87. ),
  88. );
  89. }
  90. /**
  91. * Implements hook_menu().
  92. */
  93. function block_menu() {
  94. $default_theme = variable_get('theme_default', 'bartik');
  95. $items['admin/structure/block'] = array(
  96. 'title' => 'Blocks',
  97. 'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
  98. 'page callback' => 'block_admin_display',
  99. 'page arguments' => array($default_theme),
  100. 'access arguments' => array('administer blocks'),
  101. 'file' => 'block.admin.inc',
  102. );
  103. $items['admin/structure/block/manage/%/%'] = array(
  104. 'title' => 'Configure block',
  105. 'page callback' => 'drupal_get_form',
  106. 'page arguments' => array('block_admin_configure', 4, 5),
  107. 'access arguments' => array('administer blocks'),
  108. 'file' => 'block.admin.inc',
  109. );
  110. $items['admin/structure/block/manage/%/%/configure'] = array(
  111. 'title' => 'Configure block',
  112. 'type' => MENU_DEFAULT_LOCAL_TASK,
  113. 'context' => MENU_CONTEXT_INLINE,
  114. );
  115. $items['admin/structure/block/manage/%/%/delete'] = array(
  116. 'title' => 'Delete block',
  117. 'page callback' => 'drupal_get_form',
  118. 'page arguments' => array('block_custom_block_delete', 4, 5),
  119. 'access arguments' => array('administer blocks'),
  120. 'type' => MENU_LOCAL_TASK,
  121. 'context' => MENU_CONTEXT_NONE,
  122. 'file' => 'block.admin.inc',
  123. );
  124. $items['admin/structure/block/add'] = array(
  125. 'title' => 'Add block',
  126. 'page callback' => 'drupal_get_form',
  127. 'page arguments' => array('block_add_block_form'),
  128. 'access arguments' => array('administer blocks'),
  129. 'type' => MENU_LOCAL_ACTION,
  130. 'file' => 'block.admin.inc',
  131. );
  132. foreach (list_themes() as $key => $theme) {
  133. $items['admin/structure/block/list/' . $key] = array(
  134. 'title' => $theme->info['name'],
  135. 'page arguments' => array($key),
  136. 'type' => $key == $default_theme ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
  137. 'weight' => $key == $default_theme ? -10 : 0,
  138. 'access callback' => '_block_themes_access',
  139. 'access arguments' => array($theme),
  140. 'file' => 'block.admin.inc',
  141. );
  142. if ($key != $default_theme) {
  143. $items['admin/structure/block/list/' . $key . '/add'] = array(
  144. 'title' => 'Add block',
  145. 'page callback' => 'drupal_get_form',
  146. 'page arguments' => array('block_add_block_form'),
  147. 'access arguments' => array('administer blocks'),
  148. 'type' => MENU_LOCAL_ACTION,
  149. 'file' => 'block.admin.inc',
  150. );
  151. }
  152. $items['admin/structure/block/demo/' . $key] = array(
  153. 'title' => $theme->info['name'],
  154. 'page callback' => 'block_admin_demo',
  155. 'page arguments' => array($key),
  156. 'type' => MENU_CALLBACK,
  157. 'access callback' => '_block_themes_access',
  158. 'access arguments' => array($theme),
  159. 'theme callback' => '_block_custom_theme',
  160. 'theme arguments' => array($key),
  161. 'file' => 'block.admin.inc',
  162. );
  163. }
  164. return $items;
  165. }
  166. /**
  167. * Menu item access callback - only admin or enabled themes can be accessed.
  168. */
  169. function _block_themes_access($theme) {
  170. return user_access('administer blocks') && drupal_theme_access($theme);
  171. }
  172. /**
  173. * Theme callback for the block configuration pages.
  174. *
  175. * @param $theme
  176. * The theme whose blocks are being configured. If not set, the default theme
  177. * is assumed.
  178. * @return
  179. * The theme that should be used for the block configuration page, or NULL
  180. * to indicate that the default theme should be used.
  181. */
  182. function _block_custom_theme($theme = NULL) {
  183. // We return exactly what was passed in, to guarantee that the page will
  184. // always be displayed using the theme whose blocks are being configured.
  185. return $theme;
  186. }
  187. /**
  188. * Implements hook_block_info().
  189. */
  190. function block_block_info() {
  191. $blocks = array();
  192. $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
  193. foreach ($result as $block) {
  194. $blocks[$block->bid]['info'] = $block->info;
  195. // Not worth caching.
  196. $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
  197. }
  198. return $blocks;
  199. }
  200. /**
  201. * Implements hook_block_configure().
  202. */
  203. function block_block_configure($delta = 0) {
  204. if ($delta) {
  205. $custom_block = block_custom_block_get($delta);
  206. }
  207. else {
  208. $custom_block = array();
  209. }
  210. return block_custom_block_form($custom_block);
  211. }
  212. /**
  213. * Implements hook_block_save().
  214. */
  215. function block_block_save($delta = 0, $edit = array()) {
  216. block_custom_block_save($edit, $delta);
  217. }
  218. /**
  219. * Implements hook_block_view().
  220. *
  221. * Generates the administrator-defined blocks for display.
  222. */
  223. function block_block_view($delta = '') {
  224. $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
  225. $data['subject'] = NULL;
  226. $data['content'] = check_markup($block->body, $block->format, '', TRUE);
  227. return $data;
  228. }
  229. /**
  230. * Implements hook_page_build().
  231. *
  232. * Renders blocks into their regions.
  233. */
  234. function block_page_build(&$page) {
  235. global $theme;
  236. // The theme system might not yet be initialized. We need $theme.
  237. drupal_theme_initialize();
  238. // Fetch a list of regions for the current theme.
  239. $all_regions = system_region_list($theme);
  240. $item = menu_get_item();
  241. if ($item['path'] != 'admin/structure/block/demo/' . $theme) {
  242. // Load all region content assigned via blocks.
  243. foreach (array_keys($all_regions) as $region) {
  244. // Assign blocks to region.
  245. if ($blocks = block_get_blocks_by_region($region)) {
  246. $page[$region] = $blocks;
  247. }
  248. }
  249. // Once we've finished attaching all blocks to the page, clear the static
  250. // cache to allow modules to alter the block list differently in different
  251. // contexts. For example, any code that triggers hook_page_build() more
  252. // than once in the same page request may need to alter the block list
  253. // differently each time, so that only certain parts of the page are
  254. // actually built. We do not clear the cache any earlier than this, though,
  255. // because it is used each time block_get_blocks_by_region() gets called
  256. // above.
  257. drupal_static_reset('block_list');
  258. }
  259. else {
  260. // Append region description if we are rendering the regions demo page.
  261. $item = menu_get_item();
  262. if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
  263. $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
  264. foreach ($visible_regions as $region) {
  265. $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
  266. $page[$region]['block_description'] = array(
  267. '#markup' => $description,
  268. '#weight' => 15,
  269. );
  270. }
  271. $page['page_top']['backlink'] = array(
  272. '#type' => 'link',
  273. '#title' => t('Exit block region demonstration'),
  274. '#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),
  275. // Add the "overlay-restore" class to indicate this link should restore
  276. // the context in which the region demonstration page was opened.
  277. '#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),
  278. '#weight' => -10,
  279. );
  280. }
  281. }
  282. }
  283. /**
  284. * Gets a renderable array of a region containing all enabled blocks.
  285. *
  286. * @param $region
  287. * The requested region.
  288. *
  289. * @return
  290. * A renderable array of a region containing all enabled blocks.
  291. */
  292. function block_get_blocks_by_region($region) {
  293. $build = array();
  294. if ($list = block_list($region)) {
  295. $build = _block_get_renderable_array($list);
  296. }
  297. return $build;
  298. }
  299. /**
  300. * Gets an array of blocks suitable for drupal_render().
  301. *
  302. * @param $list
  303. * A list of blocks such as that returned by block_list().
  304. *
  305. * @return
  306. * A renderable array.
  307. */
  308. function _block_get_renderable_array($list = array()) {
  309. $weight = 0;
  310. $build = array();
  311. foreach ($list as $key => $block) {
  312. $build[$key] = $block->content;
  313. unset($block->content);
  314. // Add contextual links for this block; skip the main content block, since
  315. // contextual links are basically output as tabs/local tasks already. Also
  316. // skip the help block, since we assume that most users do not need or want
  317. // to perform contextual actions on the help block, and the links needlessly
  318. // draw attention on it.
  319. if ($key != 'system_main' && $key != 'system_help') {
  320. $build[$key]['#contextual_links']['block'] = array('admin/structure/block/manage', array($block->module, $block->delta));
  321. }
  322. $build[$key] += array(
  323. '#block' => $block,
  324. '#weight' => ++$weight,
  325. );
  326. $build[$key]['#theme_wrappers'][] ='block';
  327. }
  328. $build['#sorted'] = TRUE;
  329. return $build;
  330. }
  331. /**
  332. * Updates the 'block' DB table with the blocks currently exported by modules.
  333. *
  334. * @param $theme
  335. * The theme to rehash blocks for. If not provided, defaults to the currently
  336. * used theme.
  337. *
  338. * @return
  339. * Blocks currently exported by modules.
  340. */
  341. function _block_rehash($theme = NULL) {
  342. global $theme_key;
  343. drupal_theme_initialize();
  344. if (!isset($theme)) {
  345. // If theme is not specifically set, rehash for the current theme.
  346. $theme = $theme_key;
  347. }
  348. $regions = system_region_list($theme);
  349. // These are the blocks the function will return.
  350. $blocks = array();
  351. // These are the blocks defined by code and modified by the database.
  352. $current_blocks = array();
  353. // These are {block}.bid values to be kept.
  354. $bids = array();
  355. $or = db_or();
  356. // Gather the blocks defined by modules.
  357. foreach (module_implements('block_info') as $module) {
  358. $module_blocks = module_invoke($module, 'block_info');
  359. foreach ($module_blocks as $delta => $block) {
  360. // Compile a condition to retrieve this block from the database.
  361. $condition = db_and()
  362. ->condition('module', $module)
  363. ->condition('delta', $delta);
  364. $or->condition($condition);
  365. // Add identifiers.
  366. $block['module'] = $module;
  367. $block['delta'] = $delta;
  368. $block['theme'] = $theme;
  369. $current_blocks[$module][$delta] = $block;
  370. }
  371. }
  372. // Save the blocks defined in code for alter context.
  373. $code_blocks = $current_blocks;
  374. $database_blocks = db_select('block', 'b', array('fetch' => PDO::FETCH_ASSOC))
  375. ->fields('b')
  376. ->condition($or)
  377. ->condition('theme', $theme)
  378. ->execute();
  379. $original_database_blocks = array();
  380. foreach ($database_blocks as $block) {
  381. $module = $block['module'];
  382. $delta = $block['delta'];
  383. $original_database_blocks[$module][$delta] = $block;
  384. // The cache mode can only by set from hook_block_info(), so that has
  385. // precedence over the database's value.
  386. if (isset($current_blocks[$module][$delta]['cache'])) {
  387. $block['cache'] = $current_blocks[$module][$delta]['cache'];
  388. }
  389. // Preserve info which is not in the database.
  390. $block['info'] = $current_blocks[$module][$delta]['info'];
  391. // Blocks stored in the database override the blocks defined in code.
  392. $current_blocks[$module][$delta] = $block;
  393. // Preserve this block.
  394. $bids[$block['bid']] = $block['bid'];
  395. }
  396. drupal_alter('block_info', $current_blocks, $theme, $code_blocks);
  397. foreach ($current_blocks as $module => $module_blocks) {
  398. foreach ($module_blocks as $delta => $block) {
  399. if (!isset($block['pages'])) {
  400. // {block}.pages is type 'text', so it cannot have a
  401. // default value, and not null, so we need to provide
  402. // value if the module did not.
  403. $block['pages'] = '';
  404. }
  405. // Make sure weight is set.
  406. if (!isset($block['weight'])) {
  407. $block['weight'] = 0;
  408. }
  409. if (!empty($block['region']) && $block['region'] != BLOCK_REGION_NONE && !isset($regions[$block['region']]) && $block['status'] == 1) {
  410. drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $block['info'], '%region' => $block['region'])), 'warning');
  411. // Disabled modules are moved into the BLOCK_REGION_NONE later so no
  412. // need to move the block to another region.
  413. $block['status'] = 0;
  414. }
  415. // Set region to none if not enabled and make sure status is set.
  416. if (empty($block['status'])) {
  417. $block['status'] = 0;
  418. $block['region'] = BLOCK_REGION_NONE;
  419. }
  420. // There is no point saving disabled blocks. Still, we need to save them
  421. // because the 'title' attribute is saved to the {blocks} table.
  422. if (isset($block['bid'])) {
  423. // If the block has a bid property, it comes from the database and
  424. // the record needs to be updated, so set the primary key to 'bid'
  425. // before passing to drupal_write_record().
  426. $primary_keys = array('bid');
  427. // Remove a block from the list of blocks to keep if it became disabled.
  428. unset($bids[$block['bid']]);
  429. }
  430. else {
  431. $primary_keys = array();
  432. }
  433. // If the block is new or differs from the original database block, save
  434. // it. To determine whether there was a change it is enough to examine
  435. // the values for the keys in the original database record as that
  436. // contained every database field.
  437. if (!$primary_keys || array_diff_assoc($original_database_blocks[$module][$delta], $block)) {
  438. drupal_write_record('block', $block, $primary_keys);
  439. // Make it possible to test this.
  440. $block['saved'] = TRUE;
  441. }
  442. // Add to the list of blocks we return.
  443. $blocks[] = $block;
  444. }
  445. }
  446. if ($bids) {
  447. // Remove disabled that are no longer defined by the code from the
  448. // database.
  449. db_delete('block')
  450. ->condition('bid', $bids, 'NOT IN')
  451. ->condition('theme', $theme)
  452. ->execute();
  453. }
  454. return $blocks;
  455. }
  456. /**
  457. * Returns information from database about a user-created (custom) block.
  458. *
  459. * @param $bid
  460. * ID of the block to get information for.
  461. *
  462. * @return
  463. * Associative array of information stored in the database for this block.
  464. * Array keys:
  465. * - bid: Block ID.
  466. * - info: Block description.
  467. * - body: Block contents.
  468. * - format: Filter ID of the filter format for the body.
  469. */
  470. function block_custom_block_get($bid) {
  471. return db_query("SELECT * FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
  472. }
  473. /**
  474. * Form constructor for the custom block form.
  475. *
  476. * @param $edit
  477. * (optional) An associative array of information retrieved by
  478. * block_custom_get_block() if an existing block is being edited, or an empty
  479. * array otherwise. Defaults to array().
  480. *
  481. * @ingroup forms
  482. */
  483. function block_custom_block_form($edit = array()) {
  484. $edit += array(
  485. 'info' => '',
  486. 'body' => '',
  487. );
  488. $form['info'] = array(
  489. '#type' => 'textfield',
  490. '#title' => t('Block description'),
  491. '#default_value' => $edit['info'],
  492. '#maxlength' => 64,
  493. '#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
  494. '#required' => TRUE,
  495. '#weight' => -18,
  496. );
  497. $form['body_field']['#weight'] = -17;
  498. $form['body_field']['body'] = array(
  499. '#type' => 'text_format',
  500. '#title' => t('Block body'),
  501. '#default_value' => $edit['body'],
  502. '#format' => isset($edit['format']) ? $edit['format'] : NULL,
  503. '#rows' => 15,
  504. '#description' => t('The content of the block as shown to the user.'),
  505. '#required' => TRUE,
  506. '#weight' => -17,
  507. );
  508. return $form;
  509. }
  510. /**
  511. * Saves a user-created block in the database.
  512. *
  513. * @param $edit
  514. * Associative array of fields to save. Array keys:
  515. * - info: Block description.
  516. * - body: Associative array of body value and format. Array keys:
  517. * - value: Block contents.
  518. * - format: Filter ID of the filter format for the body.
  519. * @param $delta
  520. * Block ID of the block to save.
  521. *
  522. * @return
  523. * Always returns TRUE.
  524. */
  525. function block_custom_block_save($edit, $delta) {
  526. db_update('block_custom')
  527. ->fields(array(
  528. 'body' => $edit['body']['value'],
  529. 'info' => $edit['info'],
  530. 'format' => $edit['body']['format'],
  531. ))
  532. ->condition('bid', $delta)
  533. ->execute();
  534. return TRUE;
  535. }
  536. /**
  537. * Implements hook_form_FORM_ID_alter() for user_profile_form().
  538. */
  539. function block_form_user_profile_form_alter(&$form, &$form_state) {
  540. if ($form['#user_category'] == 'account') {
  541. $account = $form['#user'];
  542. $rids = array_keys($account->roles);
  543. $result = db_query("SELECT DISTINCT b.* FROM {block} b LEFT JOIN {block_role} r ON b.module = r.module AND b.delta = r.delta WHERE b.status = 1 AND b.custom <> 0 AND (r.rid IN (:rids) OR r.rid IS NULL) ORDER BY b.weight, b.module", array(':rids' => $rids));
  544. $blocks = array();
  545. foreach ($result as $block) {
  546. $data = module_invoke($block->module, 'block_info');
  547. if ($data[$block->delta]['info']) {
  548. $blocks[$block->module][$block->delta] = array(
  549. '#type' => 'checkbox',
  550. '#title' => check_plain($data[$block->delta]['info']),
  551. '#default_value' => isset($account->data['block'][$block->module][$block->delta]) ? $account->data['block'][$block->module][$block->delta] : ($block->custom == 1),
  552. );
  553. }
  554. }
  555. // Only display the fieldset if there are any personalizable blocks.
  556. if ($blocks) {
  557. $form['block'] = array(
  558. '#type' => 'fieldset',
  559. '#title' => t('Personalize blocks'),
  560. '#description' => t('Blocks consist of content or information that complements the main content of the page. Enable or disable optional blocks using the checkboxes below.'),
  561. '#weight' => 3,
  562. '#collapsible' => TRUE,
  563. '#tree' => TRUE,
  564. );
  565. $form['block'] += $blocks;
  566. }
  567. }
  568. }
  569. /**
  570. * Implements hook_user_presave().
  571. */
  572. function block_user_presave(&$edit, $account, $category) {
  573. if (isset($edit['block'])) {
  574. $edit['data']['block'] = $edit['block'];
  575. }
  576. }
  577. /**
  578. * Initializes blocks for enabled themes.
  579. *
  580. * @param $theme_list
  581. * An array of theme names.
  582. */
  583. function block_themes_enabled($theme_list) {
  584. foreach ($theme_list as $theme) {
  585. block_theme_initialize($theme);
  586. }
  587. }
  588. /**
  589. * Assigns an initial, default set of blocks for a theme.
  590. *
  591. * This function is called the first time a new theme is enabled. The new theme
  592. * gets a copy of the default theme's blocks, with the difference that if a
  593. * particular region isn't available in the new theme, the block is assigned
  594. * to the new theme's default region.
  595. *
  596. * @param $theme
  597. * The name of a theme.
  598. */
  599. function block_theme_initialize($theme) {
  600. // Initialize theme's blocks if none already registered.
  601. $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
  602. if (!$has_blocks) {
  603. $default_theme = variable_get('theme_default', 'bartik');
  604. // Apply only to new theme's visible regions.
  605. $regions = system_region_list($theme, REGIONS_VISIBLE);
  606. $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
  607. foreach ($result as $block) {
  608. // If the region isn't supported by the theme, assign the block to the theme's default region.
  609. if ($block['status'] && !isset($regions[$block['region']])) {
  610. $block['region'] = system_default_region($theme);
  611. }
  612. $block['theme'] = $theme;
  613. unset($block['bid']);
  614. drupal_write_record('block', $block);
  615. }
  616. }
  617. }
  618. /**
  619. * Returns all blocks in the specified region for the current user.
  620. *
  621. * @param $region
  622. * The name of a region.
  623. *
  624. * @return
  625. * An array of block objects, indexed with the module name and block delta
  626. * concatenated with an underscore, thus: MODULE_DELTA. If you are displaying
  627. * your blocks in one or two sidebars, you may check whether this array is
  628. * empty to see how many columns are going to be displayed.
  629. *
  630. * @todo
  631. * Now that the block table has a primary key, we should use that as the
  632. * array key instead of MODULE_DELTA.
  633. */
  634. function block_list($region) {
  635. $blocks = &drupal_static(__FUNCTION__);
  636. if (!isset($blocks)) {
  637. $blocks = _block_load_blocks();
  638. }
  639. // Create an empty array if there are no entries.
  640. if (!isset($blocks[$region])) {
  641. $blocks[$region] = array();
  642. }
  643. else {
  644. $blocks[$region] = _block_render_blocks($blocks[$region]);
  645. }
  646. return $blocks[$region];
  647. }
  648. /**
  649. * Loads a block object from the database.
  650. *
  651. * This function returns the first block matching the module and delta
  652. * parameters, so it should not be used for theme-specific functionality.
  653. *
  654. * @param $module
  655. * Name of the module that implements the block to load.
  656. * @param $delta
  657. * Unique ID of the block within the context of $module. Pass NULL to return
  658. * an empty block object for $module.
  659. *
  660. * @return
  661. * A block object.
  662. */
  663. function block_load($module, $delta) {
  664. if (isset($delta)) {
  665. $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  666. }
  667. // If the block does not exist in the database yet return a stub block
  668. // object.
  669. if (empty($block)) {
  670. $block = new stdClass();
  671. $block->module = $module;
  672. $block->delta = $delta;
  673. }
  674. return $block;
  675. }
  676. /**
  677. * Loads blocks' information from the database.
  678. *
  679. * @return
  680. * An array of blocks grouped by region.
  681. */
  682. function _block_load_blocks() {
  683. global $theme_key;
  684. $query = db_select('block', 'b');
  685. $result = $query
  686. ->fields('b')
  687. ->condition('b.theme', $theme_key)
  688. ->condition('b.status', 1)
  689. ->orderBy('b.region')
  690. ->orderBy('b.weight')
  691. ->orderBy('b.module')
  692. ->addTag('block_load')
  693. ->addTag('translatable')
  694. ->execute();
  695. $block_info = $result->fetchAllAssoc('bid');
  696. // Allow modules to modify the block list.
  697. drupal_alter('block_list', $block_info);
  698. $blocks = array();
  699. foreach ($block_info as $block) {
  700. $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  701. }
  702. return $blocks;
  703. }
  704. /**
  705. * Implements hook_block_list_alter().
  706. *
  707. * Checks the page, user role, and user-specific visibility settings.
  708. * Removes the block if the visibility conditions are not met.
  709. */
  710. function block_block_list_alter(&$blocks) {
  711. global $user, $theme_key;
  712. // Build an array of roles for each block.
  713. $block_roles = array();
  714. $result = db_query('SELECT module, delta, rid FROM {block_role}');
  715. foreach ($result as $record) {
  716. $block_roles[$record->module][$record->delta][] = $record->rid;
  717. }
  718. foreach ($blocks as $key => $block) {
  719. if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
  720. // This block was added by a contrib module, leave it in the list.
  721. continue;
  722. }
  723. // If a block has no roles associated, it is displayed for every role.
  724. // For blocks with roles associated, if none of the user's roles matches
  725. // the settings from this block, remove it from the block list.
  726. if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
  727. // No match.
  728. unset($blocks[$key]);
  729. continue;
  730. }
  731. // Use the user's block visibility setting, if necessary.
  732. if ($block->custom != BLOCK_CUSTOM_FIXED) {
  733. if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
  734. $enabled = $user->data['block'][$block->module][$block->delta];
  735. }
  736. else {
  737. $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
  738. }
  739. }
  740. else {
  741. $enabled = TRUE;
  742. }
  743. // Limited visibility blocks must list at least one page.
  744. if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
  745. $enabled = FALSE;
  746. }
  747. if (!$enabled) {
  748. unset($blocks[$key]);
  749. continue;
  750. }
  751. // Match path if necessary.
  752. if ($block->pages) {
  753. // Convert path to lowercase. This allows comparison of the same path
  754. // with different case. Ex: /Page, /page, /PAGE.
  755. $pages = drupal_strtolower($block->pages);
  756. if ($block->visibility < BLOCK_VISIBILITY_PHP) {
  757. // Convert the Drupal path to lowercase
  758. $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  759. // Compare the lowercase internal and lowercase path alias (if any).
  760. $page_match = drupal_match_path($path, $pages);
  761. if ($path != $_GET['q']) {
  762. $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
  763. }
  764. // When $block->visibility has a value of 0 (BLOCK_VISIBILITY_NOTLISTED),
  765. // the block is displayed on all pages except those listed in $block->pages.
  766. // When set to 1 (BLOCK_VISIBILITY_LISTED), it is displayed only on those
  767. // pages listed in $block->pages.
  768. $page_match = !($block->visibility xor $page_match);
  769. }
  770. elseif (module_exists('php')) {
  771. $page_match = php_eval($block->pages);
  772. }
  773. else {
  774. $page_match = FALSE;
  775. }
  776. }
  777. else {
  778. $page_match = TRUE;
  779. }
  780. if (!$page_match) {
  781. unset($blocks[$key]);
  782. }
  783. }
  784. }
  785. /**
  786. * Render the content and subject for a set of blocks.
  787. *
  788. * @param $region_blocks
  789. * An array of block objects such as returned for one region by _block_load_blocks().
  790. *
  791. * @return
  792. * An array of visible blocks as expected by drupal_render().
  793. */
  794. function _block_render_blocks($region_blocks) {
  795. $cacheable = TRUE;
  796. // We preserve the submission of forms in blocks, by fetching from cache only
  797. // if the request method is 'GET' (or 'HEAD').
  798. if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
  799. $cacheable = FALSE;
  800. }
  801. // Block caching is not usually compatible with node access modules, so by
  802. // default it is disabled when node access modules exist. However, it can be
  803. // allowed by using the variable 'block_cache_bypass_node_grants'.
  804. elseif (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants'))) {
  805. $cacheable = FALSE;
  806. }
  807. // Proceed to loop over all blocks in order to compute their respective cache
  808. // identifiers; this allows us to do one single cache_get_multiple() call
  809. // instead of doing one cache_get() call per block.
  810. $cached_blocks = array();
  811. $cids = array();
  812. if ($cacheable) {
  813. foreach ($region_blocks as $key => $block) {
  814. if (!isset($block->content)) {
  815. if (($cid = _block_get_cache_id($block))) {
  816. $cids[$key] = $cid;
  817. }
  818. }
  819. }
  820. if ($cids) {
  821. // We cannot pass $cids in directly because cache_get_multiple() will
  822. // modify it, and we need to use it later on in this function.
  823. $cid_values = array_values($cids);
  824. $cached_blocks = cache_get_multiple($cid_values, 'cache_block');
  825. }
  826. }
  827. foreach ($region_blocks as $key => $block) {
  828. // Render the block content if it has not been created already.
  829. if (!isset($block->content)) {
  830. // Erase the block from the static array - we'll put it back if it has
  831. // content.
  832. unset($region_blocks[$key]);
  833. $cid = empty($cids[$key]) ? NULL : $cids[$key];
  834. // Try fetching the block from the previously loaded cache entries.
  835. if (isset($cached_blocks[$cid])) {
  836. $array = $cached_blocks[$cid]->data;
  837. }
  838. else {
  839. $array = module_invoke($block->module, 'block_view', $block->delta);
  840. // Valid PHP function names cannot contain hyphens.
  841. $delta = str_replace('-', '_', $block->delta);
  842. // Allow modules to modify the block before it is viewed, via either
  843. // hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
  844. drupal_alter(array('block_view', "block_view_{$block->module}_{$delta}"), $array, $block);
  845. if (isset($cid)) {
  846. cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
  847. }
  848. }
  849. if (isset($array) && is_array($array)) {
  850. foreach ($array as $k => $v) {
  851. $block->$k = $v;
  852. }
  853. }
  854. if (isset($block->content) && $block->content) {
  855. // Normalize to the drupal_render() structure.
  856. if (is_string($block->content)) {
  857. $block->content = array('#markup' => $block->content);
  858. }
  859. // Override default block title if a custom display title is present.
  860. if ($block->title) {
  861. // Check plain here to allow module generated titles to keep any
  862. // markup.
  863. $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
  864. }
  865. if (!isset($block->subject)) {
  866. $block->subject = '';
  867. }
  868. $region_blocks["{$block->module}_{$block->delta}"] = $block;
  869. }
  870. }
  871. }
  872. return $region_blocks;
  873. }
  874. /**
  875. * Assemble the cache_id to use for a given block.
  876. *
  877. * The cache_id string reflects the viewing context for the current block
  878. * instance, obtained by concatenating the relevant context information
  879. * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
  880. * constants). Two block instances can use the same cached content when
  881. * they share the same cache_id.
  882. *
  883. * Theme and language contexts are automatically differentiated.
  884. *
  885. * @param $block
  886. * @return
  887. * The string used as cache_id for the block.
  888. */
  889. function _block_get_cache_id($block) {
  890. global $user;
  891. // User 1 being out of the regular 'roles define permissions' schema,
  892. // it brings too many chances of having unwanted output get in the cache
  893. // and later be served to other users. We therefore exclude user 1 from
  894. // block caching.
  895. if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
  896. // Start with common sub-patterns: block identification, theme, language.
  897. $cid_parts[] = $block->module;
  898. $cid_parts[] = $block->delta;
  899. $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
  900. return implode(':', $cid_parts);
  901. }
  902. }
  903. /**
  904. * Implements hook_flush_caches().
  905. */
  906. function block_flush_caches() {
  907. // Rehash blocks for active themes. We don't use list_themes() here,
  908. // because if MAINTENANCE_MODE is defined it skips reading the database,
  909. // and we can't tell which themes are active.
  910. $themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
  911. foreach ($themes as $theme) {
  912. _block_rehash($theme->name);
  913. }
  914. return array('cache_block');
  915. }
  916. /**
  917. * Processes variables for block.tpl.php.
  918. *
  919. * Prepares the values passed to the theme_block function to be passed
  920. * into a pluggable template engine. Uses block properties to generate a
  921. * series of template file suggestions. If none are found, the default
  922. * block.tpl.php is used.
  923. *
  924. * Most themes utilize their own copy of block.tpl.php. The default is located
  925. * inside "modules/block/block.tpl.php". Look in there for the full list of
  926. * variables.
  927. *
  928. * The $variables array contains the following arguments:
  929. * - $block
  930. *
  931. * @see block.tpl.php
  932. */
  933. function template_preprocess_block(&$variables) {
  934. $block_counter = &drupal_static(__FUNCTION__, array());
  935. $variables['block'] = $variables['elements']['#block'];
  936. // All blocks get an independent counter for each region.
  937. if (!isset($block_counter[$variables['block']->region])) {
  938. $block_counter[$variables['block']->region] = 1;
  939. }
  940. // Same with zebra striping.
  941. $variables['block_zebra'] = ($block_counter[$variables['block']->region] % 2) ? 'odd' : 'even';
  942. $variables['block_id'] = $block_counter[$variables['block']->region]++;
  943. // Create the $content variable that templates expect.
  944. $variables['content'] = $variables['elements']['#children'];
  945. $variables['classes_array'][] = drupal_html_class('block-' . $variables['block']->module);
  946. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
  947. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
  948. // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  949. // Theme suggestions should only contain underscores, because within
  950. // drupal_find_theme_templates(), underscores are converted to hyphens to
  951. // match template file names, and then converted back to underscores to match
  952. // pre-processing and other function names. So if your theme suggestion
  953. // contains a hyphen, it will end up as an underscore after this conversion,
  954. // and your function names won't be recognized. So, we need to convert
  955. // hyphens to underscores in block deltas for the theme suggestions.
  956. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . strtr($variables['block']->delta, '-', '_');
  957. // Create a valid HTML ID and make sure it is unique.
  958. $variables['block_html_id'] = drupal_html_id('block-' . $variables['block']->module . '-' . $variables['block']->delta);
  959. }
  960. /**
  961. * Implements hook_user_role_delete().
  962. *
  963. * Removes deleted role from blocks that use it.
  964. */
  965. function block_user_role_delete($role) {
  966. db_delete('block_role')
  967. ->condition('rid', $role->rid)
  968. ->execute();
  969. }
  970. /**
  971. * Implements hook_menu_delete().
  972. */
  973. function block_menu_delete($menu) {
  974. db_delete('block')
  975. ->condition('module', 'menu')
  976. ->condition('delta', $menu['menu_name'])
  977. ->execute();
  978. db_delete('block_role')
  979. ->condition('module', 'menu')
  980. ->condition('delta', $menu['menu_name'])
  981. ->execute();
  982. }
  983. /**
  984. * Implements hook_form_FORM_ID_alter().
  985. */
  986. function block_form_system_performance_settings_alter(&$form, &$form_state) {
  987. $disabled = (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants')));
  988. $form['caching']['block_cache'] = array(
  989. '#type' => 'checkbox',
  990. '#title' => t('Cache blocks'),
  991. '#default_value' => variable_get('block_cache', FALSE),
  992. '#disabled' => $disabled,
  993. '#description' => $disabled ? t('Block caching is inactive because you have enabled modules defining content access restrictions.') : NULL,
  994. '#weight' => -1,
  995. );
  996. }
  997. /**
  998. * Implements hook_admin_paths().
  999. */
  1000. function block_admin_paths() {
  1001. $paths = array(
  1002. // Exclude the block demonstration page from admin (overlay) treatment.
  1003. // This allows us to present this page in its true form, full page.
  1004. 'admin/structure/block/demo/*' => FALSE,
  1005. );
  1006. return $paths;
  1007. }
  1008. /**
  1009. * Implements hook_modules_uninstalled().
  1010. *
  1011. * Cleans up {block} and {block_role} tables from modules' blocks.
  1012. */
  1013. function block_modules_uninstalled($modules) {
  1014. db_delete('block')
  1015. ->condition('module', $modules, 'IN')
  1016. ->execute();
  1017. db_delete('block_role')
  1018. ->condition('module', $modules, 'IN')
  1019. ->execute();
  1020. }