/[drupal]/contributions/modules/cck/nodereference.module
ViewVC logotype

Contents of /contributions/modules/cck/nodereference.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.120 - (show annotations) (download) (as text)
Mon Mar 24 01:59:03 2008 UTC (20 months ago) by yched
Branch: MAIN
Changes since 1.119: +5 -5 lines
File MIME type: text/x-php
#186775 followup : secure other noderef formatters against non existing referenced nodes.
1 <?php
2 // $Id: nodereference.module,v 1.119 2008/03/24 01:52:57 yched Exp $
3
4 /**
5 * @file
6 * Defines a field type for referencing one node from another.
7 */
8
9 /**
10 * Implementation of hook_menu().
11 */
12 function nodereference_menu() {
13 $items = array();
14 $items['nodereference/autocomplete'] = array(
15 'title' => t('Nodereference autocomplete'),
16 'page callback' => 'nodereference_autocomplete',
17 'access arguments' => array('access content'),
18 'type' => MENU_CALLBACK
19 );
20 return $items;
21 }
22
23 /**
24 * Implementation of hook_theme().
25 */
26 function nodereference_theme() {
27 return array(
28 'nodereference_item_simple' => array(
29 'arguments' => array('item' => NULL),
30 ),
31 'nodereference_item_advanced' => array(
32 'arguments' => array('item' => NULL, 'view' => NULL),
33 ),
34 'nodereference_select' => array(
35 'arguments' => array('element' => NULL),
36 ),
37 'nodereference_autocomplete' => array(
38 'arguments' => array('element' => NULL),
39 ),
40 'nodereference_formatter_default' => array(
41 'arguments' => array('element'),
42 ),
43 'nodereference_formatter_full' => array(
44 'arguments' => array('element'),
45 'function' => 'theme_nodereference_formatter_full_teaser',
46 ),
47 'nodereference_formatter_teaser' => array(
48 'arguments' => array('element'),
49 'function' => 'theme_nodereference_formatter_full_teaser',
50 ),
51 );
52 }
53
54 /**
55 * Implementation of hook_field_info().
56 *
57 * Here we indicate that the content module will use its default
58 * handling for the view of this field.
59 *
60 * Callbacks can be omitted if default handing is used.
61 * They're included here just so this module can be used
62 * as an example for custom modules that might do things
63 * differently.
64 */
65 function nodereference_field_info() {
66 return array(
67 'nodereference' => array(
68 'label' => t('Node Reference'),
69 'description' => t('Store the id of a related node as an integer value.'),
70 'callbacks' => array(
71 'tables' => CONTENT_CALLBACK_DEFAULT,
72 'arguments' => CONTENT_CALLBACK_DEFAULT,
73 ),
74 ),
75 );
76 }
77
78 /**
79 * Implementation of hook_field_settings().
80 */
81 function nodereference_field_settings($op, $field) {
82 switch ($op) {
83 case 'form':
84 $form = array();
85 $form['referenceable_types'] = array(
86 '#type' => 'checkboxes',
87 '#title' => t('Content types that can be referenced'),
88 '#multiple' => TRUE,
89 '#default_value' => is_array($field['referenceable_types']) ? $field['referenceable_types'] : array(),
90 '#options' => node_get_types('names'),
91 );
92 if (module_exists('views')) {
93 $views = array('--' => '--');
94 $all_views = views_get_all_views();
95 foreach ($all_views as $view) {
96 $views[t('Existing Views')][$view->name] = $view->name;
97 }
98
99 if (count($views) > 1) {
100 $form['advanced'] = array(
101 '#type' => 'fieldset',
102 '#title' => t('Advanced - Nodes that can be referenced (View)'),
103 '#collapsible' => TRUE,
104 '#collapsed' => !isset($field['advanced_view']) || $field['advanced_view'] == '--',
105 );
106 $form['advanced']['advanced_view'] = array(
107 '#type' => 'select',
108 '#title' => t('View'),
109 '#options' => $views,
110 '#default_value' => isset($field['advanced_view']) ? $field['advanced_view'] : '--',
111 '#description' => t('Choose the "Views module" view that selects the nodes that can be referenced.<br>Note :<ul><li>This will discard the "Content types" settings above. Use the view\'s "filters" section instead.</li><li>Use the view\'s "fields" section to display additional informations about candidate nodes on node creation/edition form.</li><li>Use the view\'s "sort criteria" section to determine the order in which candidate nodes will be displayed.</li></ul>'),
112 );
113 $form['advanced']['advanced_view_args'] = array(
114 '#type' => 'textfield',
115 '#title' => t('View arguments'),
116 '#default_value' => isset($field['advanced_view_args']) ? $field['advanced_view_args'] : '',
117 '#required' => FALSE,
118 '#description' => t('Provide a comma separated list of arguments to pass to the view.'),
119 );
120 }
121 }
122 return $form;
123
124 case 'save':
125 $settings = array('referenceable_types');
126 if (module_exists('views')) {
127 $settings[] = 'advanced_view';
128 $settings[] = 'advanced_view_args';
129 }
130 return $settings;
131
132 case 'database columns':
133 $columns = array(
134 'nid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => FALSE),
135 );
136 return $columns;
137
138 case 'filters':
139 return array(
140 'default' => array(
141 'list' => '_nodereference_filter_handler',
142 'list-type' => 'list',
143 'operator' => 'views_handler_operator_or',
144 'value-type' => 'array',
145 'extra' => array('field' => $field),
146 ),
147 );
148
149 case 'views data':
150 $data = content_views_field_views_data($field);
151 $db_info = content_database_info($field);
152 $table_alias = 'node_data_'. $field['field_name'];
153
154 $data[$table_alias][$field['field_name']]['relationship'] = array(
155 'base' => 'node',
156 'field' => $db_info['columns']['nid']['column'],
157 'handler' => 'views_handler_relationship',
158 );
159 return $data;
160 }
161 }
162
163 /**
164 * Implementation of hook_field().
165 */
166 function nodereference_field($op, &$node, $field, &$items, $teaser, $page) {
167 switch ($op) {
168 case 'validate':
169 $refs = _nodereference_potential_references($field, TRUE);
170 foreach ($items as $delta => $item) {
171 if (is_array($item) && !empty($item['error_field'])) {
172 $error_field = $item['error_field'];
173 unset($item['error_field']);
174 if (!empty($item['nid'])) {
175 if (!in_array($item['nid'], array_keys($refs))) {
176 form_set_error($error_field, t('%name : This post can\'t be referenced.', array('%name' => t($field['widget']['label']))));
177 }
178 }
179 }
180 }
181 return $items;
182 }
183 }
184
185 /**
186 * Implementation of hook_content_is_empty().
187 */
188 function nodereference_content_is_empty($item, $field) {
189 if (empty($item['nid'])) {
190 return TRUE;
191 }
192 return FALSE;
193 }
194
195 /**
196 * Implementation of hook_field_formatter_info().
197 */
198 function nodereference_field_formatter_info() {
199 return array(
200 'default' => array(
201 'label' => t('Title (link)'),
202 'field types' => array('nodereference'),
203 'multiple values' => CONTENT_HANDLE_CORE,
204 ),
205 'plain' => array(
206 'label' => t('Title (no link)'),
207 'field types' => array('nodereference'),
208 'multiple values' => CONTENT_HANDLE_CORE,
209 ),
210 'full' => array(
211 'label' => t('Full node'),
212 'field types' => array('nodereference'),
213 'multiple values' => CONTENT_HANDLE_CORE,
214 ),
215 'teaser' => array(
216 'label' => t('Teaser'),
217 'field types' => array('nodereference'),
218 'multiple values' => CONTENT_HANDLE_CORE,
219 ),
220 );
221 }
222
223 /**
224 * Theme function for 'default' nodereference field formatter.
225 */
226 function theme_nodereference_formatter_default($element) {
227 $output = '';
228 if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid']) && ($title = _nodereference_titles($element['#item']['nid']))) {
229 $output = l($title, 'node/'. $element['#item']['nid']);
230 }
231 return $output;
232 }
233
234 /**
235 * Theme function for 'plain' nodereference field formatter.
236 */
237 function theme_nodereference_formatter_plain($element) {
238 $output = '';
239 if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid']) && ($title = _nodereference_titles($element['#item']['nid']))) {
240 $output = check_plain($title);
241 }
242 return $output;
243 }
244
245 /**
246 * Proxy theme function for 'full' and 'teaser' nodereference field formatters.
247 */
248 function theme_nodereference_formatter_full_teaser($element) {
249 static $recursion_queue = array();
250 $output = '';
251 if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid'])) {
252 // If no 'referencing node' is set, we are starting a new 'reference thread'
253 if (!isset($node->referencing_node)) {
254 $recursion_queue = array();
255 }
256 $recursion_queue[] = $node->nid;
257 if (in_array($element['#item']['nid'], $recursion_queue)) {
258 // Prevent infinite recursion caused by reference cycles :
259 // if the node has already been rendered earlier in this 'thread',
260 // we fall back to 'default' (node title) formatter.
261 return theme('nodereference_formatter_default', $element);
262 }
263 if ($referenced_node = node_load($element['#item']['nid'])) {
264 $referenced_node->referencing_node = $node;
265 $referenced_node->referencing_field = $field;
266 _nodereference_titles($element['#item']['nid'], $referenced_node->title);
267 $output = node_view($referenced_node, $element['#formatter'] == 'teaser');
268 }
269 }
270 return $output;
271 }
272
273 /**
274 * Helper function for formatters.
275 *
276 * Store node titles collected in the curent request.
277 */
278 function _nodereference_titles($nid, $known_title = NULL) {
279 static $titles = array();
280 if (!isset($titles[$nid])) {
281 $title = $known_title ? $known_title : db_result(db_query("SELECT title FROM {node} WHERE nid=%d", $nid));
282 $titles[$nid] = $title ? $title : '';
283 }
284 return $titles[$nid];
285 }
286
287 /**
288 * Implementation of hook_widget_info().
289 *
290 * We need custom handling of multiple values for the nodereference_select
291 * widget because we need to combine them into a options list rather
292 * than display multiple elements.
293 *
294 * We will use the content module's default handling for default value.
295 *
296 * Callbacks can be omitted if default handing is used.
297 * They're included here just so this module can be used
298 * as an example for custom modules that might do things
299 * differently.
300 */
301 function nodereference_widget_info() {
302 return array(
303 'nodereference_select' => array(
304 'label' => t('Select List'),
305 'field types' => array('nodereference'),
306 'multiple values' => CONTENT_HANDLE_MODULE,
307 'callbacks' => array(
308 'default value' => CONTENT_CALLBACK_DEFAULT,
309 ),
310 ),
311 'nodereference_autocomplete' => array(
312 'label' => t('Autocomplete Text Field'),
313 'field types' => array('nodereference'),
314 'multiple values' => CONTENT_HANDLE_CORE,
315 'callbacks' => array(
316 'default value' => CONTENT_CALLBACK_DEFAULT,
317 ),
318 ),
319 );
320 }
321
322 /**
323 * Implementation of FAPI hook_elements().
324 *
325 * Any FAPI callbacks needed for individual widgets can be declared here,
326 * and the element will be passed to those callbacks for processing.
327 *
328 * Drupal will automatically theme the element using a theme with
329 * the same name as the hook_elements key.
330 *
331 * Autocomplete_path is not used by text_widget but other widgets can use it
332 * (see nodereference and userreference).
333 */
334 function nodereference_elements() {
335 return array(
336 'nodereference_select' => array(
337 '#input' => TRUE,
338 '#columns' => array('uid'), '#delta' => 0,
339 '#process' => array('nodereference_select_process'),
340 ),
341 'nodereference_autocomplete' => array(
342 '#input' => TRUE,
343 '#columns' => array('name'), '#delta' => 0,
344 '#process' => array('nodereference_autocomplete_process'),
345 '#autocomplete_path' => FALSE,
346 ),
347 );
348 }
349
350 /**
351 * Implementation of hook_widget().
352 *
353 * Attach a single form element to the form. It will be built out and
354 * validated in the callback(s) listed in hook_elements. We build it
355 * out in the callbacks rather than here in hook_widget so it can be
356 * plugged into any module that can provide it with valid
357 * $field information.
358 *
359 * Content module will set the weight, field name and delta values
360 * for each form element. This is a change from earlier CCK versions
361 * where the widget managed its own multiple values.
362 *
363 * If there are multiple values for this field, the content module will
364 * call this function as many times as needed.
365 *
366 * @param $form
367 * the entire form array, $form['#node'] holds node information
368 * @param $form_state
369 * the form_state, $form_state['values'][$field['field_name']]
370 * holds the field's form values.
371 * @param $field
372 * the field array
373 * @param $items
374 * array of default values for this field
375 * @param $delta
376 * the order of this item in the array of subelements (0, 1, 2, etc)
377 *
378 * @return
379 * the form item for a single element for this field
380 */
381 function nodereference_widget(&$form, &$form_state, $field, $items, $delta = 0) {
382 switch ($field['widget']['type']) {
383 case 'nodereference_select':
384 $element = array(
385 '#type' => 'nodereference_select',
386 '#default_value' => $items,
387 );
388 break;
389
390 case 'nodereference_autocomplete':
391 $element = array(
392 '#type' => 'nodereference_autocomplete',
393 '#default_value' => isset($items[$delta]) ? $items[$delta] : NULL,
394 '#value_callback' => 'nodereference_autocomplete_value',
395 );
396 break;
397 }
398 return $element;
399 }
400
401 /**
402 * Value for a nodereference autocomplete element.
403 *
404 * Substitute in the node title for the node nid.
405 */
406 function nodereference_autocomplete_value($element, $edit = FALSE) {
407 $field_key = $element['#columns'][0];
408 if (!empty($element['#default_value'][$field_key])) {
409 $nid = $element['#default_value'][$field_key];
410 $value = db_result(db_query(db_rewrite_sql('SELECT n.title FROM {node} n WHERE n.nid = %d'), $nid));
411 $value .= ' [nid:'. $nid .']';
412 return array($field_key => $value);
413 }
414 return array($field_key => NULL);
415 }
416
417 /**
418 * Process an individual element.
419 *
420 * Build the form element. When creating a form using FAPI #process,
421 * note that $element['#value'] is already set.
422 *
423 * The $fields array is in $form['#field_info'][$element['#field_name']].
424 */
425 function nodereference_select_process($element, $edit, $form_state, $form) {
426 // The nodereference_select widget doesn't need to create its own
427 // element, it can wrap around the optionwidgets_select element.
428 // Add a validation step where the value can be unwrapped.
429 $field_key = $element['#columns'][0];
430 $element[$field_key] = array(
431 '#type' => 'optionwidgets_select',
432 '#default_value' => isset($element['#value']) ? $element['#value'] : '',
433 '#element_validate' => array('optionwidgets_validate', 'nodereference_select_validate'),
434
435 // The following values were set by the content module and need
436 // to be passed down to the nested element.
437 '#field_name' => $element['#field_name'],
438 '#delta' => $element['#delta'],
439 '#columns' => $element['#columns'],
440 '#title' => $element['#title'],
441 '#required' => $element['#required'],
442 '#description' => $element['#description'],
443 );
444 return $element;
445 }
446
447 /**
448 * Process an individual element.
449 *
450 * Build the form element. When creating a form using FAPI #process,
451 * note that $element['#value'] is already set.
452 *
453 */
454 function nodereference_autocomplete_process($element, $edit, $form_state, $form) {
455 // The nodereference autocomplete widget doesn't need to create its own
456 // element, it can wrap around the text_textfield element and add an autocomplete
457 // path and some extra processing to it.
458 // Add a validation step where the value can be unwrapped.
459 $field_key = $element['#columns'][0];
460
461 $element[$field_key] = array(
462 '#type' => 'text_textfield',
463 '#default_value' => isset($element['#value']) ? $element['#value'] : '',
464 '#autocomplete_path' => 'nodereference/autocomplete/'. $element['#field_name'],
465 '#element_validate' => array('nodereference_autocomplete_validate'),
466
467 // The following values were set by the content module and need
468 // to be passed down to the nested element.
469 '#field_name' => $element['#field_name'],
470 '#delta' => $element['#delta'],
471 '#columns' => $element['#columns'],
472 '#title' => $element['#title'],
473 '#required' => $element['#required'],
474 '#description' => $element['#description'],
475 );
476 return $element;
477 }
478
479 /**
480 * Validate an select element.
481 *
482 * Remove the wrapper layer and set the right element's value.
483 */
484 function nodereference_select_validate($element, &$form_state) {
485 $field_key = $element['#columns'][0];
486 array_pop($element['#parents']);
487 form_set_value($element, $form_state['values'][$element['#field_name']][$field_key], $form_state);
488 }
489
490 /**
491 * Validate an autocomplete element.
492 *
493 * Remove the wrapper layer and set the right element's value.
494 */
495 function nodereference_autocomplete_validate($element, &$form_state) {
496 $field_name = $element['#field_name'];
497 $field = content_fields($field_name);
498 $field_key = $element['#columns'][0];
499 $delta = $element['#delta'];
500 $value = $element['#value'][$field_key];
501 $nid = NULL;
502 if (!empty($value)) {
503 preg_match('/^(?:\s*|(.*) )?\[\s*nid\s*:\s*(\d+)\s*\]$/', $value, $matches);
504 if (!empty($matches)) {
505 // explicit nid
506 list(, $title, $nid) = $matches;
507 if (!empty($title) && ($n = node_load($nid)) && $title != $n->title) {
508 form_set_error($element[$field_key], t('%name : Title mismatch. Please check your selection.'), array('%name' => t($element[$field_key]['#title'])));
509 }
510 }
511 else {
512 // no explicit nid
513 // TODO :
514 // the best thing would be to present the user with an additional form,
515 // allowing the user to choose between valid candidates with the same title
516 // ATM, we pick the first matching candidate...
517 $nids = _nodereference_potential_references($field, FALSE, $value, TRUE);
518 $nid = (!empty($nids)) ? array_shift(array_keys($nids)) : 0;
519 }
520 }
521 form_set_value($element, $nid, $form_state);
522 return $element;
523 }
524
525 /**
526 * Implementation of hook_allowed_values().
527 */
528 function nodereference_allowed_values($field) {
529 $options = _nodereference_potential_references($field, TRUE);
530 foreach ($options as $key => $value) {
531 $options[$key] = _nodereference_item($field, $value);
532 }
533 if (!$field['required']) {
534 $options = array(0 => '<'. t('none') .'>') + $options;
535 }
536 return $options;
537 }
538
539 /**
540 * Fetch an array of all candidate referenced nodes,
541 * for use in presenting the selection form to the user.
542 */
543 function _nodereference_potential_references($field, $return_full_nodes = FALSE, $string = '', $exact_string = false) {
544 // TODO Once filtering by title is working, get rid of "empty($string)" constraint to use this with autocomplete.
545 if (empty($string) && module_exists('views') && isset($field['advanced_view']) && $field['advanced_view'] != '--' && ($view = views_get_view($field['advanced_view']))) {
546 // advanced field : referenceable nodes defined by a view
547 // let views.module build the query
548
549 $view->init();
550
551 // TODO is this the right way to do this?
552 // make sure the fields get included in the query
553 $view->set_display('page');
554 $view->display['page']->style_plugin = 'list';
555
556 // arguments for the view
557 if (isset($field['advanced_view_args'])) {
558 // TODO: Support Tokens using token.module ?
559 $view_args = array();
560 $view_args = array_map('trim', explode(',', $field['advanced_view_args']));
561 $view->set_arguments($view_args);
562 }
563
564 // TODO Filtering by title is not yet working in Views 2, can't do this yet??
565 //if (isset($string)) {
566 // views_view_add_filter($view, 'node', 'title', $exact_string ? '=' : 'contains', $string, null);
567 //}
568
569 // we do need title field, so add it if not present (unlikely, but...)
570 //$has_title = array_reduce($view->field, create_function('$a, $b', 'return ($b["field"] == "title") || $a;'), false);
571 //if (!$has_title) {
572 // views_view_add_field($view, 'node', 'title', '');
573 //}
574 //views_load_cache();
575 //views_sanitize_view($view);
576
577 // make sure the query is not cached
578 $view->is_cacheable = FALSE;
579
580 $view->execute();
581 $options = array();
582 foreach ($view->result as $row) {
583 foreach ($view->field as $field) {
584 if (!empty($field['handler']) && is_object($field['handler'])) {
585 $options[$row->nid][] = theme('views_view_field', $view, $field, $row);
586 }
587 }
588 }
589 return $options;
590 }
591 else {
592 // standard field : referenceable nodes defined by content types
593 // build the appropriate query
594 $related_types = array();
595 $args = array();
596
597 if (is_array($field['referenceable_types'])) {
598 foreach ($field['referenceable_types'] as $related_type) {
599 if ($related_type) {
600 $related_types[] = " n.type = '%s'";
601 $args[] = $related_type;
602 }
603 }
604 }
605
606 $related_clause = implode(' OR ', $related_types);
607
608 if (!count($related_types)) {
609 return array();
610 }
611
612 if (isset($string)) {
613 $string_clause = $exact_string ? " AND n.title = '%s'" : " AND n.title LIKE '%%%s%'";
614 $related_clause = "(". $related_clause .")". $string_clause;
615 $args[] = $string;
616 }
617
618 $result = db_query(db_rewrite_sql("SELECT n.nid, n.title AS node_title, n.type AS node_type FROM {node} n WHERE ". $related_clause ." ORDER BY n.title, n.type"), $args);
619 }
620
621 $rows = array();
622
623 while ($node = db_fetch_object($result)) {
624 if ($return_full_nodes) {
625 $rows[$node->nid] = $node;
626 }
627 else {
628 $rows[$node->nid] = $node->node_title;
629 }
630 }
631
632 return $rows;
633 }
634
635 /**
636 * Retrieve a pipe delimited string of autocomplete suggestions
637 */
638 function nodereference_autocomplete($field_name, $string = '') {
639 $fields = content_fields();
640 $field = $fields[$field_name];
641 $matches = array();
642
643 foreach (_nodereference_potential_references($field, TRUE, $string) as $row) {
644 $matches[$row->node_title .' [nid:'. $row->nid .']'] = _nodereference_item($field, $row, TRUE);
645 }
646 drupal_json($matches);
647 }
648
649 function _nodereference_item($field, $item, $html = FALSE) {
650 if (module_exists('views') && isset($field['advanced_view']) && $field['advanced_view'] != '--' && ($view = views_get_view($field['advanced_view']))) {
651 $field_names = array();
652 foreach ($view->field as $name => $viewfield) {
653 $field_names[] = $name;
654 }
655 $output = theme('nodereference_item_advanced', $item, $field_names, $view);
656 if (!$html) {
657 // Views theming runs check_plain (htmlentities) on the values.
658 // We reverse that with html_entity_decode.
659 $output = html_entity_decode(strip_tags($output), ENT_QUOTES);
660 }
661 }
662 else {
663 $output = theme('nodereference_item_simple', $item);
664 $output = $html ? check_plain($output) : $output;
665 }
666 return $output;
667 }
668
669 function theme_nodereference_item_advanced($item, $field_names, $view) {
670 $item_fields = array();
671 foreach ($item as $delta => $value) {
672 // remove link tags (ex : for node titles)
673 $value = preg_replace('/<a[^>]*>(.*)<\/a>/iU', '$1', $value);
674 if (!empty($value)) {
675 $item_fields[] = "<span class='view-field view-data-$field_names[$delta]'>$value</span>";;
676 }
677 }
678 $output = implode(' - ', $item_fields);
679 $output = "<span class='view-item view-item-$view->name'>$output</span>";
680 return $output;
681 }
682
683 function theme_nodereference_item_simple($item) {
684 return $item->node_title;
685 }
686
687 /**
688 * Provide a list of users to filter on.
689 */
690 function _nodereference_filter_handler($op, $filterinfo) {
691 $options = array(0 => t('<empty>'));
692 $options = $options + _nodereference_potential_references($filterinfo['extra']['field']);
693 return $options;
694 }
695
696 /**
697 * FAPI theme for an individual elements.
698 *
699 * The textfield or select is already rendered by the
700 * textfield or select themes and the html output
701 * lives in $element['#children']. Override this theme to
702 * make custom changes to the output.
703 *
704 * $element['#field_name'] contains the field name
705 * $element['#delta] is the position of this element in the group
706 */
707 function theme_nodereference_select($element) {
708 return $element['#children'];
709 }
710
711 function theme_nodereference_autocomplete($element) {
712 return $element['#children'];
713 }

  ViewVC Help
Powered by ViewVC 1.1.2