blockreference.module

Tracking 6.x-1.x branch
  1. drupal
    1. 6 contributions/blockreference/blockreference.module

Defines a field type for referencing a block from a node.

Functions & methods

NameDescription
blockreference_allowed_valuesImplementation of hook_allowed_values().
blockreference_autocompleteRetrieve a pipe delimited string of autocomplete suggestions
blockreference_autocomplete_processProcess an individual element.
blockreference_autocomplete_validateValidate an autocomplete element.
blockreference_autocomplete_valueValue for a blockreference autocomplete element.
blockreference_content_is_emptyImplementation of hook_content_is_empty().
blockreference_elementsImplementation of FAPI hook_elements().
blockreference_fieldImplementation of hook_field().
blockreference_field_formatter_infoImplementation of hook_field_formatter_info().
blockreference_field_infoImplementation of hook_field_info().
blockreference_field_settingsImplementation of hook_field_settings().
blockreference_get_block_modulesGet an array of block modules, where the keys are the module short name and the values are the module name as set in the .info file.
blockreference_menuImplementation of hook_menu().
blockreference_select_processProcess an individual element.
blockreference_select_sort_processProcess an individual element.
blockreference_select_validateValidate an select element.
blockreference_themeImplementation of hook_theme().
blockreference_widgetImplementation of hook_widget().
blockreference_widget_infoImplementation of hook_widget_info().
theme_blockreference_autocomplete
theme_blockreference_formatter_defaultTheme function for 'default' blockreference field formatter.
theme_blockreference_formatter_plainTheme function for 'plain' blockreference field formatter.
theme_blockreference_formatter_titleTheme function for 'title' blockreference field formatter.
theme_blockreference_formatter_without_titleTheme function for 'without_title' blockreference field formatter.
theme_blockreference_item_advanced
theme_blockreference_item_simple
theme_blockreference_selectFAPI theme for an individual elements.
theme_blockreference_select_sort
_blockreference_item
_blockreference_potential_referencesFetch an array of all candidate referenced blocks, for use in presenting the selection form to the user.
_theme_blockreference_formatter_get_blockHelper function for theming normal block views, returns appropriate block.

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * Defines a field type for referencing a block from a node.
  5. */
  6. /**
  7. * Implementation of hook_menu().
  8. */
  9. function blockreference_menu() {
  10. $items = array();
  11. $items['blockreference/autocomplete'] = array(
  12. 'title' => 'Blockreference autocomplete',
  13. 'page callback' => 'blockreference_autocomplete',
  14. 'access arguments' => array('access content'),
  15. 'type' => MENU_CALLBACK
  16. );
  17. return $items;
  18. }
  19. /**
  20. * Implementation of hook_theme().
  21. */
  22. function blockreference_theme() {
  23. return array(
  24. 'blockreference_item_simple' => array(
  25. 'arguments' => array('item' => NULL),
  26. ),
  27. 'blockreference_item_advanced' => array(
  28. 'arguments' => array('item' => NULL, 'view' => NULL),
  29. ),
  30. 'blockreference_select' => array(
  31. 'arguments' => array('element' => NULL),
  32. ),
  33. 'blockreference_select_sort' => array(
  34. 'arguments' => array('element' => NULL),
  35. ),
  36. 'blockreference_autocomplete' => array(
  37. 'arguments' => array('element' => NULL),
  38. ),
  39. 'blockreference_formatter_default' => array(
  40. 'arguments' => array('element'),
  41. ),
  42. 'blockreference_formatter_without_title' => array(
  43. 'arguments' => array('element'),
  44. ),
  45. 'blockreference_formatter_plain' => array(
  46. 'arguments' => array('element'),
  47. ),
  48. 'blockreference_formatter_title' => array(
  49. 'arguments' => array('element'),
  50. ),
  51. );
  52. }
  53. /**
  54. * Implementation of hook_field_info().
  55. *
  56. * Here we indicate that the content module will use its default
  57. * handling for the view of this field.
  58. *
  59. * Callbacks can be omitted if default handing is used.
  60. * They're included here just so this module can be used
  61. * as an example for custom modules that might do things
  62. * differently.
  63. */
  64. function blockreference_field_info() {
  65. return array(
  66. 'blockreference' => array(
  67. 'label' => t('Block reference'),
  68. 'description' => t('Store the ID of a related block as an integer value.'),
  69. 'callbacks' => array(
  70. 'tables' => CONTENT_CALLBACK_DEFAULT,
  71. 'arguments' => CONTENT_CALLBACK_DEFAULT,
  72. ),
  73. ),
  74. );
  75. }
  76. /**
  77. * Get an array of block modules, where the keys are the module short name and
  78. * the values are the module name as set in the .info file.
  79. */
  80. function blockreference_get_block_modules() {
  81. $block_modules = array();
  82. // Get current list of modules
  83. $files = drupal_system_listing('\.module$', 'modules', 'name', 0);
  84. // Extract current files from database.
  85. system_get_files_database($files, 'module');
  86. // Get modules that define blocks.
  87. $modules = module_implements('block', TRUE);
  88. foreach ($modules as $module) {
  89. if (isset($files[$module])) {
  90. $file = &$files[$module];
  91. // Look for the info file.
  92. $file->info = drupal_parse_info_file(dirname($file->filename) . '/' . $file->name . '.info');
  93. $block_modules[$module] = isset($file->info['name']) ? $file->info['name'] : ucfirst($module);
  94. }
  95. }
  96. return $block_modules;
  97. }
  98. /**
  99. * Implementation of hook_field_settings().
  100. */
  101. function blockreference_field_settings($op, $field) {
  102. switch ($op) {
  103. case 'form':
  104. $form = array();
  105. $form['referenceable_regions'] = array(
  106. '#type' => 'checkboxes',
  107. '#title' => t('Regions containing blocks that can be referenced'),
  108. '#multiple' => TRUE,
  109. '#default_value' => !empty($field['referenceable_regions']) ? $field['referenceable_regions'] : array(),
  110. '#options' => array('' => '(Disabled)') + system_region_list(variable_get('theme_default', 'garland')),
  111. '#description' => t('If no regions are selected, blocks from all regions will be available.'),
  112. );
  113. $form['referenceable_modules'] = array(
  114. '#type' => 'checkboxes',
  115. '#title' => t('Modules defining blocks that can be referenced'),
  116. '#multiple' => TRUE,
  117. '#default_value' => !empty($field['referenceable_modules']) ? $field['referenceable_modules'] : array(),
  118. '#options' => blockreference_get_block_modules(),
  119. '#description' => t('If no modules are selected, blocks from all modules will be available.'),
  120. );
  121. $form['referenceable_operator'] = array(
  122. '#type' => 'radios',
  123. '#title' => t('Operator to use if referenceable regions and referenceable modules are selected.'),
  124. '#default_value' => !empty($field['referenceable_operator'])
  125. ? $field['referenceable_operator']
  126. : 'AND',
  127. '#options' => array(
  128. 'AND' => '<strong>AND</strong> - ' . t('Block must be both contained in a referenceable region and defined by a referenceable module.'),
  129. 'OR' => '<strong>OR</strong> - ' . t('Block must be either contained in a referenceable region or defined by a referenceable module.'),
  130. ),
  131. '#description' => t('If regions and modules are selected, choose operator to use when retrieving blocks list.'),
  132. );
  133. return $form;
  134. case 'save':
  135. $settings = array('referenceable_regions', 'referenceable_modules', 'referenceable_operator');
  136. return $settings;
  137. case 'database columns':
  138. $columns = array(
  139. 'bid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => FALSE),
  140. );
  141. return $columns;
  142. case 'views data':
  143. $data = content_views_field_views_data($field);
  144. $db_info = content_database_info($field);
  145. $table_alias = content_views_tablename($field);
  146. // Filter: swap the handler to the 'in' operator.
  147. $data[$table_alias][$field['field_name'] .'_bid']['filter']['handler'] = 'content_handler_filter_many_to_one';
  148. $data["node_$table_alias"]['table']['join']['node'] = array(
  149. 'table' => 'node',
  150. 'field' => 'vid',
  151. 'left_table' => $table_alias,
  152. 'left_field' => 'vid',
  153. );
  154. $data[$table_alias][$field['field_name'] .'_bid']['argument']['handler'] = 'content_handler_argument_reference';
  155. $data[$table_alias][$field['field_name'] .'_bid']['argument']['name table'] = "node_$table_alias";
  156. $data[$table_alias][$field['field_name'] .'_bid']['argument']['name field'] = 'title';
  157. // Relationship: add a relationship for related block.
  158. $data[$table_alias][$field['field_name'] .'_bid']['relationship'] = array(
  159. 'base' => 'blocks',
  160. 'field' => $db_info['columns']['bid']['column'],
  161. 'handler' => 'content_handler_relationship',
  162. 'label' => t($field['widget']['label']),
  163. 'content_field_name' => $field['field_name'],
  164. );
  165. return $data;
  166. }
  167. }
  168. /**
  169. * Implementation of hook_field().
  170. */
  171. function blockreference_field($op, &$node, $field, &$items, $teaser, $page) {
  172. switch ($op) {
  173. case 'validate':
  174. $refs = _blockreference_potential_references($field, TRUE);
  175. foreach ($items as $delta => $item) {
  176. if (is_array($item) && !empty($item['error_field'])) {
  177. $error_field = $item['error_field'];
  178. unset($item['error_field']);
  179. if (!empty($item['bid'])) {
  180. if (!in_array($item['bid'], array_keys($refs))) {
  181. form_set_error($error_field, t("%name : This block can't be referenced.", array('%name' => t($field['widget']['label']))));
  182. }
  183. }
  184. }
  185. }
  186. return $items;
  187. }
  188. }
  189. /**
  190. * Implementation of hook_content_is_empty().
  191. */
  192. function blockreference_content_is_empty($item, $field) {
  193. if (empty($item['bid'])) {
  194. return TRUE;
  195. }
  196. return FALSE;
  197. }
  198. /**
  199. * Implementation of hook_field_formatter_info().
  200. */
  201. function blockreference_field_formatter_info() {
  202. return array(
  203. 'default' => array(
  204. 'label' => t('Default'),
  205. 'field types' => array('blockreference'),
  206. 'multiple values' => CONTENT_HANDLE_CORE,
  207. ),
  208. 'without_title' => array(
  209. 'label' => t('Normal, without title'),
  210. 'field types' => array('blockreference'),
  211. 'multiple values' => CONTENT_HANDLE_CORE,
  212. ),
  213. 'plain' => array(
  214. 'label' => t('Plain (info)'),
  215. 'field types' => array('blockreference'),
  216. 'multiple values' => CONTENT_HANDLE_CORE,
  217. ),
  218. 'title' => array(
  219. 'label' => t('Title only'),
  220. 'field types' => array('blockreference'),
  221. 'multiple values' => CONTENT_HANDLE_CORE,
  222. ),
  223. );
  224. }
  225. /**
  226. * Helper function for theming normal block views, returns appropriate block.
  227. */
  228. function _theme_blockreference_formatter_get_block($element) {
  229. if (!empty($element['#item']['bid']) && is_numeric($element['#item']['bid'])) {
  230. $block = db_fetch_object(db_query(db_rewrite_sql("SELECT * FROM {blocks} WHERE bid = ". $element['#item']['bid'], 'blocks', 'bid')));
  231. $block->enabled = TRUE;
  232. $block->status = TRUE;
  233. $block->page_match = TRUE;
  234. // Code adapted from the block module.
  235. if (!count(module_implements('node_grants')) && $_SERVER['REQUEST_METHOD'] == 'GET' && ($cid = _block_get_cache_id($block)) && ($cache = cache_get($cid, 'cache_block'))) {
  236. $block_view = $cache->data;
  237. }
  238. else {
  239. $block_view = module_invoke($block->module, 'block', 'view', $block->delta);
  240. if (isset($cid)) {
  241. cache_set($cid, $block_view, 'cache_block', CACHE_TEMPORARY);
  242. }
  243. }
  244. $block->content = $block_view['content'];
  245. $block->subject = $block->title ? $block->title : $block_view['subject'];
  246. }
  247. return $block;
  248. }
  249. /**
  250. * Theme function for 'default' blockreference field formatter.
  251. */
  252. function theme_blockreference_formatter_default($element) {
  253. $block = _theme_blockreference_formatter_get_block($element);
  254. $output = '';
  255. if ($block->content) {
  256. $output = theme('block', $block);
  257. }
  258. return $output;
  259. }
  260. /**
  261. * Theme function for 'without_title' blockreference field formatter.
  262. */
  263. function theme_blockreference_formatter_without_title($element) {
  264. $block = _theme_blockreference_formatter_get_block($element);
  265. $block->subject = ''; // Without title
  266. $output = '';
  267. if ($block->content) {
  268. $output = theme('block', $block);
  269. }
  270. return $output;
  271. }
  272. /**
  273. * Theme function for 'plain' blockreference field formatter.
  274. */
  275. function theme_blockreference_formatter_plain($element) {
  276. $output = '';
  277. if (isset($element['#item']['bid'])) {
  278. $args[] = $element['#item']['bid'];
  279. $result = db_query(db_rewrite_sql("SELECT b.module, b.delta FROM {blocks} b WHERE b.bid = '%s'", 'blocks', 'bid', $args), $args);
  280. $block = db_fetch_object($result);
  281. $info = module_invoke($block->module, 'block', 'list');
  282. $output = $info[$block->delta]['info'];
  283. }
  284. return $output;
  285. }
  286. /**
  287. * Theme function for 'title' blockreference field formatter.
  288. */
  289. function theme_blockreference_formatter_title($element) {
  290. $field_name = $element['#field_name'];
  291. $field = content_fields($field_name);
  292. $output = '';
  293. if (!empty($element['#item']['bid']) && is_numeric($element['#item']['bid'])) {
  294. $block = db_fetch_object(db_query(db_rewrite_sql("SELECT * FROM {blocks} WHERE bid = ". $element['#item']['bid'], 'blocks', 'bid')));
  295. $block->enabled = TRUE;
  296. $block->status = TRUE;
  297. $block->page_match = TRUE;
  298. $block_view = module_invoke($block->module, 'block', 'view', $block->delta);
  299. $subject = $block->title ? $block->title : $block_view['subject'];
  300. if ($block_view['content']) {
  301. $output = check_plain($subject);
  302. }
  303. }
  304. return $output;
  305. }
  306. /**
  307. * Implementation of hook_widget_info().
  308. *
  309. * We need custom handling of multiple values for the blockreference_select
  310. * widget because we need to combine them into a options list rather
  311. * than display multiple elements.
  312. *
  313. * We will use the content module's default handling for default value.
  314. *
  315. * Callbacks can be omitted if default handing is used.
  316. * They're included here just so this module can be used
  317. * as an example for custom modules that might do things
  318. * differently.
  319. */
  320. function blockreference_widget_info() {
  321. return array(
  322. 'blockreference_select' => array(
  323. 'label' => t('Select list'),
  324. 'field types' => array('blockreference'),
  325. 'multiple values' => CONTENT_HANDLE_MODULE,
  326. 'callbacks' => array(
  327. 'default value' => CONTENT_CALLBACK_DEFAULT,
  328. ),
  329. ),
  330. 'blockreference_select_sort' => array(
  331. 'label' => t('Select list (with drag-and-drop sort)'),
  332. 'field types' => array('blockreference'),
  333. 'multiple values' => CONTENT_HANDLE_CORE,
  334. 'callbacks' => array(
  335. 'default value' => CONTENT_CALLBACK_DEFAULT,
  336. ),
  337. ),
  338. 'blockreference_autocomplete' => array(
  339. 'label' => t('Autocomplete text field'),
  340. 'field types' => array('blockreference'),
  341. 'multiple values' => CONTENT_HANDLE_CORE,
  342. 'callbacks' => array(
  343. 'default value' => CONTENT_CALLBACK_DEFAULT,
  344. ),
  345. ),
  346. );
  347. }
  348. /**
  349. * Implementation of FAPI hook_elements().
  350. *
  351. * Any FAPI callbacks needed for individual widgets can be declared here,
  352. * and the element will be passed to those callbacks for processing.
  353. *
  354. * Drupal will automatically theme the element using a theme with
  355. * the same name as the hook_elements key.
  356. *
  357. * Autocomplete_path is not used by text_widget but other widgets can use it
  358. * (see blockreference and userreference).
  359. */
  360. function blockreference_elements() {
  361. return array(
  362. 'blockreference_select' => array(
  363. '#input' => TRUE,
  364. '#columns' => array('uid'), '#delta' => 0,
  365. '#process' => array('blockreference_select_process'),
  366. ),
  367. 'blockreference_select_sort' => array(
  368. '#input' => TRUE,
  369. '#columns' => array('uid'), '#delta' => 0,
  370. '#process' => array('blockreference_select_sort_process'),
  371. ),
  372. 'blockreference_autocomplete' => array(
  373. '#input' => TRUE,
  374. '#columns' => array('name'), '#delta' => 0,
  375. '#process' => array('blockreference_autocomplete_process'),
  376. '#autocomplete_path' => FALSE,
  377. ),
  378. );
  379. }
  380. /**
  381. * Implementation of hook_widget().
  382. *
  383. * Attach a single form element to the form. It will be built out and
  384. * validated in the callback(s) listed in hook_elements. We build it
  385. * out in the callbacks rather than here in hook_widget so it can be
  386. * plugged into any module that can provide it with valid
  387. * $field information.
  388. *
  389. * Content module will set the weight, field name and delta values
  390. * for each form element. This is a change from earlier CCK versions
  391. * where the widget managed its own multiple values.
  392. *
  393. * If there are multiple values for this field, the content module will
  394. * call this function as many times as needed.
  395. *
  396. * @param $form
  397. * the entire form array, $form['#node'] holds node information
  398. * @param $form_state
  399. * the form_state, $form_state['values'][$field['field_name']]
  400. * holds the field's form values.
  401. * @param $field
  402. * the field array
  403. * @param $items
  404. * array of default values for this field
  405. * @param $delta
  406. * the order of this item in the array of subelements (0, 1, 2, etc)
  407. *
  408. * @return
  409. * the form item for a single element for this field
  410. */
  411. function blockreference_widget(&$form, &$form_state, $field, $items, $delta = 0) {
  412. switch ($field['widget']['type']) {
  413. case 'blockreference_select':
  414. $element = array(
  415. '#type' => 'blockreference_select',
  416. '#default_value' => $items,
  417. );
  418. break;
  419. case 'blockreference_select_sort':
  420. $element = array(
  421. '#type' => 'blockreference_select_sort',
  422. '#default_value' => isset($items[$delta]) ? $items[$delta] : NULL,
  423. );
  424. break;
  425. case 'blockreference_autocomplete':
  426. $element = array(
  427. '#type' => 'blockreference_autocomplete',
  428. '#default_value' => isset($items[$delta]) ? $items[$delta] : NULL,
  429. '#value_callback' => 'blockreference_autocomplete_value',
  430. );
  431. break;
  432. }
  433. return $element;
  434. }
  435. /**
  436. * Value for a blockreference autocomplete element.
  437. *
  438. * Substitute in the block title for the block bid.
  439. */
  440. function blockreference_autocomplete_value($element, $edit = FALSE) {
  441. $field_key = $element['#columns'][0];
  442. if (!empty($element['#default_value'][$field_key])) {
  443. $bid = $element['#default_value'][$field_key];
  444. $args[] = $bid;
  445. $result = db_query(db_rewrite_sql("SELECT b.module, b.delta FROM {blocks} b WHERE b.bid = '%d'", 'blocks', 'bid', $args), $args);
  446. $block = db_fetch_object($result);
  447. $info = module_invoke($block->module, 'block', 'list');
  448. $value = $info[$block->delta]['info'];
  449. $value .= ' [bid:'. $bid .']';
  450. return array($field_key => $value);
  451. }
  452. return array($field_key => NULL);
  453. }
  454. /**
  455. * Process an individual element.
  456. *
  457. * Build the form element. When creating a form using FAPI #process,
  458. * note that $element['#value'] is already set.
  459. *
  460. * The $fields array is in $form['#field_info'][$element['#field_name']].
  461. */
  462. function blockreference_select_process($element, $edit, $form_state, $form) {
  463. // The blockreference_select widget doesn't need to create its own
  464. // element, it can wrap around the optionwidgets_select element.
  465. // Add a validation step where the value can be unwrapped.
  466. $field_key = $element['#columns'][0];
  467. $element[$field_key] = array(
  468. '#type' => 'optionwidgets_select',
  469. '#default_value' => isset($element['#value']) ? $element['#value'] : '',
  470. // The following values were set by the content module and need
  471. // to be passed down to the nested element.
  472. '#field_name' => $element['#field_name'],
  473. '#delta' => $element['#delta'],
  474. '#columns' => $element['#columns'],
  475. '#title' => $element['#title'],
  476. '#required' => $element['#required'],
  477. '#description' => $element['#description'],
  478. );
  479. if (empty($element[$field_key]['#element_validate'])) {
  480. $element[$field_key]['#element_validate'] = array();
  481. }
  482. array_unshift($element[$field_key]['#element_validate'], 'optionwidgets_validate', 'blockreference_select_validate');
  483. return $element;
  484. }
  485. /**
  486. * Process an individual element.
  487. *
  488. * Build the form element. When creating a form using FAPI #process,
  489. * note that $element['#value'] is already set.
  490. *
  491. * The $fields array is in $form['#field_info'][$element['#field_name']].
  492. */
  493. function blockreference_select_sort_process($element, $edit, $form_state, $form) {
  494. $field = $form['#field_info'][$element['#field_name']];
  495. $field_key = $element['#columns'][0];
  496. $element[$field_key] = array(
  497. '#type' => 'select',
  498. '#options' => blockreference_allowed_values($field),
  499. '#multiple' => 0,
  500. '#default_value' => isset($element['#value'][$element['#columns'][0]]) ? $element['#value'][$element['#columns'][0]] : '',
  501. // The following values were set by the content module and need
  502. // to be passed down to the nested element.
  503. '#field_name' => $element['#field_name'],
  504. '#delta' => $element['#delta'],
  505. '#columns' => $element['#columns'],
  506. '#title' => $element['#title'],
  507. '#required' => $element['#required'],
  508. '#description' => $element['#description'],
  509. );
  510. return $element;
  511. }
  512. /**
  513. * Process an individual element.
  514. *
  515. * Build the form element. When creating a form using FAPI #process,
  516. * note that $element['#value'] is already set.
  517. *
  518. */
  519. function blockreference_autocomplete_process($element, $edit, $form_state, $form) {
  520. // The blockreference autocomplete widget doesn't need to create its own
  521. // element, it can wrap around the text_textfield element and add an autocomplete
  522. // path and some extra processing to it.
  523. // Add a validation step where the value can be unwrapped.
  524. $field_key = $element['#columns'][0];
  525. $element[$field_key] = array(
  526. '#type' => 'text_textfield',
  527. '#default_value' => isset($element['#value']) ? $element['#value'] : '',
  528. '#autocomplete_path' => 'blockreference/autocomplete/'. $element['#field_name'],
  529. // The following values were set by the content module and need
  530. // to be passed down to the nested element.
  531. '#field_name' => $element['#field_name'],
  532. '#delta' => $element['#delta'],
  533. '#columns' => $element['#columns'],
  534. '#title' => $element['#title'],
  535. '#required' => $element['#required'],
  536. '#description' => $element['#description'],
  537. );
  538. if (empty($element[$field_key]['#element_validate'])) {
  539. $element[$field_key]['#element_validate'] = array();
  540. }
  541. array_unshift($element[$field_key]['#element_validate'], 'blockreference_autocomplete_validate');
  542. return $element;
  543. }
  544. /**
  545. * Validate an select element.
  546. *
  547. * Remove the wrapper layer and set the right element's value.
  548. * We don't know exactly where this element is, so we drill down
  549. * through the element until we get to our key.
  550. */
  551. function blockreference_select_validate($element, &$form_state) {
  552. $field_key = $element['#columns'][0];
  553. $new_parents = array();
  554. $value = $form_state['values'];
  555. foreach ($element['#parents'] as $parent) {
  556. $value = $value[$parent];
  557. if ($parent == $field_key) {
  558. $element['#parents'] = $new_parents;
  559. form_set_value($element, $value, $form_state);
  560. break;
  561. }
  562. $new_parents[] = $parent;
  563. }
  564. }
  565. /**
  566. * Validate an autocomplete element.
  567. *
  568. * Remove the wrapper layer and set the right element's value.
  569. */
  570. function blockreference_autocomplete_validate($element, &$form_state) {
  571. $field_name = $element['#field_name'];
  572. $field = content_fields($field_name);
  573. $field_key = $element['#columns'][0];
  574. $delta = $element['#delta'];
  575. $value = $element['#value'][$field_key];
  576. $bid = NULL;
  577. if (!empty($value)) {
  578. preg_match('/^(?:\s*|(.*) )?\[\s*bid\s*:\s*(\d+)\s*\]$/', $value, $matches);
  579. if (!empty($matches)) {
  580. // explicit bid
  581. list(, $info, $bid) = $matches;
  582. $args[] = $bid;
  583. $result = db_query(db_rewrite_sql("SELECT b.module, b.delta FROM {blocks} b WHERE b.bid = '%s'", 'blocks', 'bid', $args), $args);
  584. $block = db_fetch_object($result);
  585. $info = module_invoke($block->module, 'block', 'list');
  586. $block->info = $info[$block->delta]['info'];
  587. if (!empty($title) && ($b = db_fetch_object($result)) && $info != $b->info) {
  588. form_set_error($element[$field_key], t('%name: Title mismatch. Please check your selection.'), array('%name' => t($element[$field_key]['#title'])));
  589. }
  590. }
  591. else {
  592. // no explicit bid
  593. // TODO :
  594. // the best thing would be to present the user with an additional form,
  595. // allowing the user to choose between valid candidates with the same title
  596. // ATM, we pick the first matching candidate...
  597. $bids = _blockreference_potential_references($field, FALSE, $value, TRUE);
  598. $bid = (!empty($bids)) ? array_shift(array_keys($bids)) : 0;
  599. }
  600. }
  601. form_set_value($element, $bid, $form_state);
  602. return $element;
  603. }
  604. /**
  605. * Implementation of hook_allowed_values().
  606. */
  607. function blockreference_allowed_values($field) {
  608. $options = _blockreference_potential_references($field, TRUE);
  609. foreach ($options as $key => $value) {
  610. $options[$key] = _blockreference_item($field, $value);
  611. }
  612. natcasesort($options);
  613. if (!$field['required']) {
  614. $options = array(0 => ' - '. t('none') .' - ') + $options;
  615. }
  616. return $options;
  617. }
  618. /**
  619. * Fetch an array of all candidate referenced blocks,
  620. * for use in presenting the selection form to the user.
  621. *
  622. * @param $field
  623. * Array containing field data.
  624. * @param $return_full_blocks
  625. * Whether to return full blocks.
  626. * @param $string
  627. * Filter string to match blocks.
  628. * @param $exact_string
  629. * Strictly match string like for validation.
  630. *
  631. */
  632. function _blockreference_potential_references($field, $return_full_blocks = FALSE, $string = '', $exact_string = FALSE) {
  633. static $block_info = array();
  634. $related_regions = array();
  635. $related_modules = array();
  636. $related_clauses = array();
  637. $args = array();
  638. // Handle related regions - this will be used in extra query conditions.
  639. if (isset($field['referenceable_regions']) && is_array($field['referenceable_regions'])) {
  640. foreach ($field['referenceable_regions'] as $related_region) {
  641. if ($related_region !== 0 && $related_region != '0') {
  642. if (isset($related_region)) {
  643. $related_regions[] = " b.region = '%s'";
  644. $args[] = $related_region;
  645. }
  646. }
  647. }
  648. }
  649. if (!empty($related_regions)) {
  650. $related_clauses[] = implode(' OR ', $related_regions);
  651. }
  652. // Handle related modules - this will be used in extra query conditions.
  653. if (isset($field['referenceable_modules']) && is_array($field['referenceable_modules'])) {
  654. foreach ($field['referenceable_modules'] as $related_module) {
  655. if ($related_module !== 0 && $related_module != '0') {
  656. $related_modules[] = " b.module = '%s'";
  657. $args[] = $related_module;
  658. }
  659. }
  660. }
  661. if (!empty($related_modules)) {
  662. $related_clauses[] = implode(' OR ', $related_modules);
  663. }
  664. // Assemble the extra query condition.
  665. $related_operator = !empty($field['referenceable_operator']) ? $field['referenceable_operator'] : 'AND';
  666. $related_clause = !empty($related_clauses) ? ' AND (('. implode(') ' . $related_operator . ' (', $related_clauses) .'))' : '';
  667. // Assemble the query.
  668. $result = db_query(
  669. 'SELECT b.bid, b.module, b.delta, b.title, b.region '.
  670. 'FROM {blocks} b '.
  671. "WHERE b.theme = '". variable_get('theme_default', 'garland') ."'".
  672. $related_clause .' '.
  673. 'ORDER BY b.region, b.weight',
  674. $args
  675. );
  676. // Execute the query, test each row, and return the blocks or block info.
  677. $rows = array();
  678. while ($block = db_fetch_object($result)) {
  679. if (!isset($block_info[$block->module][$block->delta])) {
  680. $block_info[$block->module] = module_invoke($block->module, 'block', 'list');
  681. }
  682. $block->info = $block_info[$block->module][$block->delta]['info'];
  683. if (
  684. (
  685. $exact_string &&
  686. !empty($string) &&
  687. $string == $block->info
  688. ) ||
  689. (
  690. !empty($string) &&
  691. (
  692. (!empty($block->info) && stripos($block->info, $string) !== FALSE) ||
  693. (!empty($block->title) && stripos($block->title, $string) !== FALSE) ||
  694. (!empty($block->module) && stripos($block->module . ' ' . $block->delta, $string) !== FALSE) ||
  695. (!empty($block->bid) && stripos($block->bid, $string) !== FALSE)
  696. )
  697. ) ||
  698. (
  699. empty($string)
  700. )
  701. ) {
  702. $rows[$block->bid] = $return_full_blocks ? $block : $block->info;
  703. }
  704. }
  705. drupal_alter('blockreference_potential_references', $rows, $field, $return_full_blocks, $string, $exact_string);
  706. return $rows;
  707. }
  708. /**
  709. * Retrieve a pipe delimited string of autocomplete suggestions
  710. */
  711. function blockreference_autocomplete($field_name, $string = '') {
  712. // If the request has a '/' in the search text, then the menu system will have
  713. // split it into multiple arguments, recover the intended $string.
  714. $args = func_get_args();
  715. // Shift off the $field_name argument.
  716. array_shift($args);
  717. $string = implode('/', $args);
  718. $fields = content_fields();
  719. $field = $fields[$field_name];
  720. $matches = array();
  721. $references = _blockreference_potential_references($field, TRUE, $string);
  722. foreach ($references as $rowbid => $rowname) {
  723. $matches[_blockreference_item($field, $rowname) .' [bid:'. $rowbid .']'] = _blockreference_item($field, $rowname);
  724. }
  725. drupal_json($matches);
  726. }
  727. function _blockreference_item($field, $item, $html = FALSE) {
  728. $output = theme('blockreference_item_simple', $item);
  729. $output = $html ? check_plain($output) : $output;
  730. return $output;
  731. }
  732. function theme_blockreference_item_advanced($item, $field_names, $view) {
  733. $item_fields = array();
  734. $item = (array) $item;
  735. foreach ($item as $delta => $value) {
  736. // remove link tags (ex : for block titles)
  737. $value = preg_replace('/<a[^>]*>(.*)<\/a>/iU', '$1', $value);
  738. if (!empty($value)) {
  739. $item_fields[] = "<span class='view-field view-data-$field_names[$delta]'>$value</span>";;
  740. }
  741. }
  742. $output = implode(' - ', $item_fields);
  743. $output = "<span class='view-item view-item-$view->name'>$output</span>";
  744. return $output;
  745. }
  746. function theme_blockreference_item_simple($item) {
  747. return $item->info;
  748. }
  749. /**
  750. * FAPI theme for an individual elements.
  751. *
  752. * The textfield or select is already rendered by the
  753. * textfield or select themes and the html output
  754. * lives in $element['#children']. Override this theme to
  755. * make custom changes to the output.
  756. *
  757. * $element['#field_name'] contains the field name
  758. * $element['#delta] is the position of this element in the group
  759. */
  760. function theme_blockreference_select($element) {
  761. return $element['#children'];
  762. }
  763. function theme_blockreference_select_sort($element) {
  764. return $element['#children'];
  765. }
  766. function theme_blockreference_autocomplete($element) {
  767. return $element['#children'];
  768. }