block.module 39 KB

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