block.module 38 KB

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