block.module 39 KB

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