block.module 39 KB

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