block.module 39 KB

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