Simpletest Coverage - modules/field/field.attach.inc

1 <?php
2 // $Id: field.attach.inc,v 1.36 2009/08/13 00:17:47 webchick Exp $
3
4 /**
5 * @file
6 * Field attach API, allowing objects (nodes, users, ...) to be 'fieldable'.
7 */
8
9 /**
10 * Exception thrown by field_attach_validate() on field validation errors.
11 */
12 class FieldValidationException extends FieldException {
13 var $errors;
14
15 /**
16 * Constructor for FieldValidationException.
17 *
18 * @param $errors
19 * An array of field validation errors, keyed by field name and
20 * delta that contains two keys:
21 * - 'error': A machine-readable error code string, prefixed by
22 * the field module name. A field widget may use this code to decide
23 * how to report the error.
24 * - 'message': A human-readable error message such as to be
25 * passed to form_error() for the appropriate form element.
26 */
27 function __construct($errors) {
28 $this->errors = $errors;
29 parent::__construct(t('Field validation errors'));
30 }
31 }
32
33 /**
34 * Exception thrown by field_attach_query() on unsupported query syntax.
35 *
36 * Some storage modules might not support the full range of the syntax for
37 * conditions, and will raise a FieldQueryException when an usupported
38 * condition was specified.
39 */
40 class FieldQueryException extends FieldException {}
41
42 /**
43 * @defgroup field_storage Field Storage API
44 * @{
45 * Implement a storage engine for Field API data.
46 *
47 * The Field Attach API uses the Field Storage API to perform all
48 * "database access". Each Field Storage API hook function defines a
49 * primitive database operation such as read, write, or delete. The
50 * default field storage module, field_sql_storage.module, uses the
51 * local SQL database to implement these operations, but alternative
52 * field storage engines can choose to represent the data in SQL
53 * differently or use a completely different storage mechanism such as
54 * a cloud-based database.
55 *
56 * The Drupal system variable field_storage_module identifies the
57 * field storage module to use.
58 */
59
60 /**
61 * Argument for an update operation.
62 *
63 * This is used in hook_field_storage_write when updating an
64 * existing object.
65 */
66 define('FIELD_STORAGE_UPDATE', 'update');
67
68 /**
69 * Argument for an insert operation.
70 *
71 * This is used in hook_field_storage_write when inserting a new object.
72 */
73 define('FIELD_STORAGE_INSERT', 'insert');
74
75 /**
76 * @} End of "defgroup field_storage"
77 */
78
79 /**
80 * @defgroup field_attach Field Attach API
81 * @{
82 * Operate on Field API data attached to Drupal objects.
83 *
84 * Field Attach API functions load, store, generate Form API
85 * structures, display, and perform a vareity of other functions for
86 * field data connected to individual objects.
87 *
88 * Field Attach API functions generally take $obj_type and $object
89 * arguments along with additional function-specific arguments.
90 * $obj_type is the type of the fieldable entity, such as 'node' or
91 * 'user', and $object is the object itself. An individual object's
92 * bundle, if any, is read from the object's bundle key property
93 * identified by hook_fieldable_info() for $obj_type.
94 *
95 * Fieldable types call Field Attach API functions during their own
96 * API calls; for example, node_load() calls field_attach_load(). A
97 * fieldable type is not required to use all of the Field Attach
98 * API functions.
99 *
100 * Most Field Attach API functions define a corresponding hook
101 * function that allows any module to act on Field Attach operations
102 * for any object after the operation is complete, and access or
103 * modify all the field, form, or display data for that object and
104 * operation. For example, field_attach_view() invokes
105 * hook_field_attach_view_alter(). These all-module hooks are distinct from
106 * those of the Field Types API, such as hook_field_load(), that are
107 * only invoked for the module that defines a specific field type.
108 *
109 * field_attach_load(), field_attach_insert(), and
110 * field_attach_update() also define pre-operation hooks,
111 * e.g. hook_field_attach_pre_load(). These hooks run before the
112 * corresponding Field Storage API and Field Type API operations.
113 * They allow modules to define additional storage locations
114 * (e.g. denormalizing, mirroring) for field data on a per-field
115 * basis. They also allow modules to take over field storage
116 * completely by instructing other implementations of the same hook
117 * and the Field Storage API itself not to operate on specified
118 * fields.
119 *
120 * The pre-operation hooks do not make the Field Storage API
121 * irrelevant. The Field Storage API is essentially the "fallback
122 * mechanism" for any fields that aren't being intercepted explicitly
123 * by pre-operation hooks.
124 */
125
126 /**
127 * Invoke a field hook.
128 *
129 * @param $op
130 * Possible operations include:
131 * - form
132 * - validate
133 * - presave
134 * - insert
135 * - update
136 * - delete
137 * - delete revision
138 * - sanitize
139 * - view
140 * - prepare translation
141 * @param $obj_type
142 * The type of $object; e.g. 'node' or 'user'.
143 * @param $object
144 * The fully formed $obj_type object.
145 * @param $a
146 * - The $form in the 'form' operation.
147 * - The value of $build_mode in the 'view' operation.
148 * - Otherwise NULL.
149 * @param $b
150 * - The $form_state in the 'submit' operation.
151 * - Otherwise NULL.
152 * @param $options
153 * An associative array of additional options, with the following keys:
154 * - 'field_name': The name of the field whose operation should be
155 * invoked. By default, the operation is invoked on all the fields
156 * in the object's bundle. NOTE: This option is not compatible with
157 * the 'deleted' option; the 'field_id' option should be used
158 * instead.
159 * - 'field_id': The id of the field whose operation should be
160 * invoked. By default, the operation is invoked on all the fields
161 * in the objects' bundles.
162 * - 'default': A boolean value, specifying which implementation of
163 * the operation should be invoked.
164 * - if FALSE (default), the field types implementation of the operation
165 * will be invoked (hook_field_[op])
166 * - If TRUE, the default field implementation of the field operation
167 * will be invoked (field_default_[op])
168 * Internal use only. Do not explicitely set to TRUE, but use
169 * _field_invoke_default() instead.
170 * - 'deleted': If TRUE, the function will operate on deleted fields
171 * as well as non-deleted fields. If unset or FALSE, only
172 * non-deleted fields are operated on.
173 */
174 function _field_invoke($op, $obj_type, $object, &$a = NULL, &$b = NULL, $options = array()) {
175 // Merge default options.
176 $default_options = array(
177 'default' => FALSE,
178 'deleted' => FALSE,
179 );
180 $options += $default_options;
181
182 // Iterate through the object's field instances.
183 $return = array();
184 list(, , $bundle) = field_attach_extract_ids($obj_type, $object);
185
186 if ($options['deleted']) {
187 $instances = field_read_instances(array('bundle' => $bundle), array('include_deleted' => $options['deleted']));
188 }
189 else {
190 $instances = field_info_instances($bundle);
191 }
192
193 foreach ($instances as $instance) {
194 $field_name = $instance['field_name'];
195
196 // When in 'single field' mode, only act on the specified field.
197 if ((!isset($options['field_id']) || $options['field_id'] == $instance['field_id']) && (!isset($options['field_name']) || $options['field_name'] == $field_name)) {
198 $field = field_info_field($field_name);
199
200 // Extract the field values into a separate variable, easily accessed by
201 // hook implementations.
202 $items = isset($object->$field_name) ? $object->$field_name : array();
203
204 // Invoke the field hook and collect results.
205 $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
206 if (drupal_function_exists($function)) {
207 $result = $function($obj_type, $object, $field, $instance, $items, $a, $b);
208 if (isset($result)) {
209 // For hooks with array results, we merge results together.
210 // For hooks with scalar results, we collect results in an array.
211 if (is_array($result)) {
212 $return = array_merge($return, $result);
213 }
214 else {
215 $return[] = $result;
216 }
217 }
218 }
219
220 // Populate field values back in the object, but avoid replacing missing
221 // fields with an empty array (those are not equivalent on update).
222 if ($items !== array() || property_exists($object, $field_name)) {
223 $object->$field_name = $items;
224 }
225 }
226 }
227
228 return $return;
229 }
230
231 /**
232 * Invoke a field hook across fields on multiple objects.
233 *
234 * @param $op
235 * Possible operations include:
236 * - load
237 * For all other operations, use _field_invoke() / field_invoke_default()
238 * instead.
239 * @param $obj_type
240 * The type of $object; e.g. 'node' or 'user'.
241 * @param $objects
242 * An array of objects, keyed by object id.
243 * @param $a
244 * - The $age parameter in the 'load' operation.
245 * - Otherwise NULL.
246 * @param $b
247 * Currently always NULL.
248 * @param $options
249 * An associative array of additional options, with the following keys:
250 * - 'field_name': The name of the field whose operation should be
251 * invoked. By default, the operation is invoked on all the fields
252 * in the object's bundle. NOTE: This option is not compatible with
253 * the 'deleted' option; the 'field_id' option should be used instead.
254 * - 'field_id': The id of the field whose operation should be
255 * invoked. By default, the operation is invoked on all the fields
256 * in the objects' bundles.
257 * - 'default': A boolean value, specifying which implementation of
258 * the operation should be invoked.
259 * - if FALSE (default), the field types implementation of the operation
260 * will be invoked (hook_field_[op])
261 * - If TRUE, the default field implementation of the field operation
262 * will be invoked (field_default_[op])
263 * Internal use only. Do not explicitely set to TRUE, but use
264 * _field_invoke_multiple_default() instead.
265 * - 'deleted': If TRUE, the function will operate on deleted fields
266 * as well as non-deleted fields. If unset or FALSE, only
267 * non-deleted fields are operated on.
268 * @return
269 * An array of returned values keyed by object id.
270 */
271 function _field_invoke_multiple($op, $obj_type, $objects, &$a = NULL, &$b = NULL, $options = array()) {
272 // Merge default options.
273 $default_options = array(
274 'default' => FALSE,
275 'deleted' => FALSE,
276 );
277 $options += $default_options;
278
279 $fields = array();
280 $grouped_instances = array();
281 $grouped_objects = array();
282 $grouped_items = array();
283 $return = array();
284
285 // Go through the objects and collect the fields on which the hook should be
286 // invoked.
287 //
288 // We group fields by id, not by name, because this function can operate on
289 // deleted fields which may have non-unique names. However, objects can only
290 // contain data for a single field for each name, even if that field
291 // is deleted, so we reference field data via the
292 // $object->$field_name property.
293 foreach ($objects as $object) {
294 list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
295
296 if ($options['deleted']) {
297 $instances = field_read_field(array('bundle' => $bundle, array('include_deleted' => $options['deleted'])));
298 }
299 else {
300 $instances = field_info_instances($bundle);
301 }
302
303 foreach ($instances as $instance) {
304 $field_id = $instance['field_id'];
305 $field_name = $instance['field_name'];
306 // When in 'single field' mode, only act on the specified field.
307 if ((empty($options['field_id']) || $options['field_id'] == $field_id) && (empty($options['field_name']) || $options['field_name'] == $field_name)) {
308 // Add the field to the list of fields to invoke the hook on.
309 if (!isset($fields[$field_id])) {
310 $fields[$field_id] = field_info_field_by_id($field_id);
311 }
312 // Group the corresponding instances and objects.
313 $grouped_instances[$field_id][$id] = $instance;
314 $grouped_objects[$field_id][$id] = $objects[$id];
315 // Extract the field values into a separate variable, easily accessed
316 // by hook implementations.
317 $grouped_items[$field_id][$id] = isset($object->$field_name) ? $object->$field_name : array();
318 }
319 }
320 // Initialize the return value for each object.
321 $return[$id] = array();
322 }
323
324 // For each field, invoke the field hook and collect results.
325 foreach ($fields as $field_id => $field) {
326 $field_name = $field['field_name'];
327 $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
328 if (drupal_function_exists($function)) {
329 $results = $function($obj_type, $grouped_objects[$field_id], $field, $grouped_instances[$field_id], $grouped_items[$field_id], $options, $a, $b);
330 if (isset($results)) {
331 // Collect results by object.
332 // For hooks with array results, we merge results together.
333 // For hooks with scalar results, we collect results in an array.
334 foreach ($results as $id => $result) {
335 if (is_array($result)) {
336 $return[$id] = array_merge($return[$id], $result);
337 }
338 else {
339 $return[$id][] = $result;
340 }
341 }
342 }
343 }
344
345 // Populate field values back in the objects, but avoid replacing missing
346 // fields with an empty array (those are not equivalent on update).
347 foreach ($grouped_objects[$field_id] as $id => $object) {
348 if ($grouped_items[$field_id][$id] !== array() || property_exists($object, $field_name)) {
349 $object->$field_name = $grouped_items[$field_id][$id];
350 }
351 }
352 }
353
354 return $return;
355 }
356
357 /**
358 * Invoke field.module's version of a field hook.
359 *
360 * This function invokes the field_default_[op]() function.
361 * Use _field_invoke() to invoke the field type implementation,
362 * hook_field_[op]().
363 *
364 * @see _field_invoke().
365 */
366 function _field_invoke_default($op, $obj_type, $object, &$a = NULL, &$b = NULL, $options = array()) {
367 $options['default'] = TRUE;
368 return _field_invoke($op, $obj_type, $object, $a, $b, $options);
369 }
370
371 /**
372 * Invoke field.module's version of a field hook on multiple objects.
373 *
374 * This function invokes the field_default_[op]() function.
375 * Use _field_invoke_multiple() to invoke the field type implementation,
376 * hook_field_[op]().
377 *
378 * @see _field_invoke_multiple().
379 */
380 function _field_invoke_multiple_default($op, $obj_type, $objects, &$a = NULL, &$b = NULL, $options = array()) {
381 $options['default'] = TRUE;
382 return _field_invoke_multiple($op, $obj_type, $objects, $a, $b, $options);
383 }
384
385 /**
386 * Add form elements for all fields for an object to a form structure.
387 *
388 * @param $obj_type
389 * The type of $object; e.g. 'node' or 'user'.
390 * @param $object
391 * The object for which to load form elements, used to initialize
392 * default form values.
393 * @param $form
394 * The form structure to fill in.
395 * @param $form_state
396 * An associative array containing the current state of the form.
397 * @return
398 * The form elements are added by reference at the top level of the $form
399 * parameter. Sample structure:
400 * @code
401 * array(
402 * '#fields' => array(
403 * // One sub-array per field appearing in the form, keyed by field name.
404 * 'field_foo' => array (
405 * 'field' => the field definition structure,
406 * 'instance' => the field instance definition structure,
407 * 'form_path' => an array of keys indicating the path to the field
408 * element within the full $form structure, used by the 'add more
409 * values' AHAH button. Any 3rd party module using form_alter() to
410 * modify the structure of the form should update this entry as well.
411 * ),
412 * ),
413 *
414 * // One sub-array per field appearing in the form, keyed by field name.
415 * // The structure of the array differs slightly depending on whether the
416 * // widget is 'single-value' (provides the input for one field value,
417 * // most common case), and will therefore be repeated as many times as
418 * // needed, or 'multiple-values' (one single widget allows the input of
419 * // several values, e.g checkboxes, select box...).
420 * 'field_foo' => array(
421 * '#field_name' => the name of the field,
422 * '#tree' => TRUE,
423 * '#required' => whether or not the field is required,
424 * '#title' => the label of the field instance,
425 * '#description' => the description text for the field instance,
426 *
427 * // Only for 'single' widgets:
428 * '#theme' => 'field_multiple_value_form',
429 * '#multiple' => the field cardinality,
430 * // One sub-array per copy of the widget, keyed by delta.
431 * 0 => array(
432 * '#title' => the title to be displayed by the widget,
433 * '#default_value' => the field value for delta 0,
434 * '#required' => whether the widget should be marked required,
435 * '#delta' => 0,
436 * '#field_name' => the name of the field,
437 * '#bundle' => the name of the bundle,
438 * '#columns' => the array of field columns,
439 * // The remaining elements in the sub-array depend on the widget.
440 * '#type' => the type of the widget,
441 * ...
442 * ),
443 * 1 => array(
444 * ...
445 * ),
446 *
447 * // Only for multiple widgets:
448 * '#bundle' => $instance['bundle'],
449 * '#columns' => array_keys($field['columns']),
450 * // The remaining elements in the sub-array depend on the widget.
451 * '#type' => the type of the widget,
452 * ...
453 * ),
454 * )
455 * @endcode
456 */
457 function field_attach_form($obj_type, $object, &$form, &$form_state) {
458 $form += (array) _field_invoke_default('form', $obj_type, $object, $form, $form_state);
459
460 // Let other modules make changes to the form.
461 foreach (module_implements('field_attach_form') as $module) {
462 $function = $module . '_field_attach_form';
463 $function($obj_type, $object, $form, $form_state);
464 }
465 }
466
467 /**
468 * Load all fields for the most current version of each of a set of
469 * objects of a single object type.
470 *
471 * @param $obj_type
472 * The type of $object; e.g. 'node' or 'user'.
473 * @param $objects
474 * An array of objects for which to load fields, keyed by object id.
475 * Each object needs to have its 'bundle', 'id' and (if applicable)
476 * 'revision' keys filled.
477 * @param $age
478 * FIELD_LOAD_CURRENT to load the most recent revision for all
479 * fields, or FIELD_LOAD_REVISION to load the version indicated by
480 * each object. Defaults to FIELD_LOAD_CURRENT; use
481 * field_attach_load_revision() instead of passing FIELD_LOAD_REVISION.
482 * @param $options
483 * An associative array of additional options, with the following keys:
484 * - 'field_id': The field id that should be loaded, instead of
485 * loading all fields, for each object. Note that returned objects
486 * may contain data for other fields, for example if they are read
487 * from a cache.
488 * - 'deleted': If TRUE, the function will operate on deleted fields
489 * as well as non-deleted fields. If unset or FALSE, only
490 * non-deleted fields are operated on.
491 * @returns
492 * Loaded field values are added to $objects. Fields with no values should be
493 * set as an empty array.
494 */
495 function field_attach_load($obj_type, $objects, $age = FIELD_LOAD_CURRENT, $options = array()) {
496 $load_current = $age == FIELD_LOAD_CURRENT;
497
498 // Merge default options.
499 $default_options = array(
500 'deleted' => FALSE,
501 );
502 $options += $default_options;
503
504 $info = field_info_fieldable_types($obj_type);
505 // Only the most current revision of non-deleted fields for
506 // cacheable fieldable types can be cached.
507 $cache_read = $load_current && $info['cacheable'] && empty($options['deleted']);
508 // In addition, do not write to the cache when loading a single field.
509 $cache_write = $cache_read && !isset($options['field_id']);
510
511 if (empty($objects)) {
512 return;
513 }
514
515 // Assume all objects will need to be queried. Objects found in the cache
516 // will be removed from the list.
517 $queried_objects = $objects;
518
519 // Fetch available objects from cache, if applicable.
520 if ($cache_read) {
521 // Build the list of cache entries to retrieve.
522 $cids = array();
523 foreach ($objects as $id => $object) {
524 $cids[] = "field:$obj_type:$id";
525 }
526 $cache = cache_get_multiple($cids, 'cache_field');
527 // Put the cached field values back into the objects and remove them from
528 // the list of objects to query.
529 foreach ($objects as $id => $object) {
530 $cid = "field:$obj_type:$id";
531 if (isset($cache[$cid])) {
532 unset($queried_objects[$id]);
533 foreach ($cache[$cid]->data as $field_name => $values) {
534 $object->$field_name = $values;
535 }
536 }
537 }
538 }
539
540 // Fetch other objects from their storage location.
541 if ($queried_objects) {
542 // The invoke order is:
543 // - hook_field_attach_pre_load()
544 // - storage engine's hook_field_storage_load()
545 // - field-type module's hook_field_load()
546 // - hook_field_attach_load()
547
548 // Invoke hook_field_attach_pre_load(): let any module load field
549 // data before the storage engine, accumulating along the way.
550 $skip_fields = array();
551 foreach (module_implements('field_attach_pre_load') as $module) {
552 $function = $module . '_field_attach_pre_load';
553 $function($obj_type, $queried_objects, $age, $skip_fields, $options);
554 }
555
556 // Invoke the storage engine's hook_field_storage_load(): the field storage
557 // engine loads the rest.
558 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_load', $obj_type, $queried_objects, $age, $skip_fields, $options);
559
560 // Invoke field-type module's hook_field_load().
561 _field_invoke_multiple('load', $obj_type, $queried_objects, $age, $options);
562
563 // Invoke hook_field_attach_load(): let other modules act on loading the
564 // object.
565 foreach (module_implements('field_attach_load') as $module) {
566 $function = $module . '_field_attach_load';
567 $function($obj_type, $queried_objects, $age, $options);
568 }
569
570 // Build cache data.
571 if ($cache_write) {
572 foreach ($queried_objects as $id => $object) {
573 $data = array();
574 list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
575 $instances = field_info_instances($bundle);
576 foreach ($instances as $instance) {
577 $data[$instance['field_name']] = $queried_objects[$id]->{$instance['field_name']};
578 }
579 $cid = "field:$obj_type:$id";
580 cache_set($cid, $data, 'cache_field');
581 }
582 }
583 }
584 }
585
586 /**
587 * Load all fields for a previous version of each of a set of
588 * objects of a single object type.
589 *
590 * Loading different versions of the same objects is not supported,
591 * and should be done by separate calls to the function.
592 *
593 * @param $obj_type
594 * The type of $object; e.g. 'node' or 'user'.
595 * @param $objects
596 * An array of objects for which to load fields, keyed by object id.
597 * Each object needs to have its 'bundle', 'id' and (if applicable)
598 * 'revision' keys filled.
599 * @param $options
600 * An associative array of additional options, with the following keys:
601 * - 'field_name': The field name that should be loaded, instead of
602 * loading all fields, for each object. Note that returned objects
603 * may contain data for other fields, for example if they are read
604 * from a cache.
605 * @returns
606 * On return, the objects in $objects are modified by having the
607 * appropriate set of fields added.
608 */
609 function field_attach_load_revision($obj_type, $objects, $options = array()) {
610 return field_attach_load($obj_type, $objects, FIELD_LOAD_REVISION, $options);
611 }
612
613 /**
614 * Perform field validation against the field data in an object.
615 *
616 * This function does not perform field widget validation on form
617 * submissions. It is intended to be called during API save
618 * operations. Use field_attach_form_validate() to validate form
619 * submissions.
620 *
621 * @param $obj_type
622 * The type of $object; e.g. 'node' or 'user'.
623 * @param $object
624 * The object with fields to validate.
625 * @return
626 * Throws a FieldValidationException if validation errors are found.
627 */
628 function field_attach_validate($obj_type, $object) {
629 $errors = array();
630 _field_invoke('validate', $obj_type, $object, $errors);
631
632 // Let other modules validate the object.
633 foreach (module_implements('field_attach_validate') as $module) {
634 $function = $module . '_field_attach_validate';
635 $function($obj_type, $object, $errors);
636 }
637
638 if ($errors) {
639 throw new FieldValidationException($errors);
640 }
641 }
642
643 /**
644 * Perform field validation against form-submitted field values.
645 *
646 * There are two levels of validation for fields in forms: widget
647 * validation, and field validation.
648 * - Widget validation steps are specific to a given widget's own form
649 * structure and UI metaphors. They are executed through FAPI's
650 * #element_validate property during normal form validation.
651 * - Field validation steps are common to a given field type, independently of
652 * the specific widget being used in a given form. They are defined in the
653 * field type's implementation of hook_field_validate().
654 *
655 * This function performs field validation in the context of a form
656 * submission. It converts field validation errors into form errors
657 * on the correct form elements. Fieldable object types should call
658 * this function during their own form validation function.
659 *
660 * @param $obj_type
661 * The type of $object; e.g. 'node' or 'user'.
662 * @param $object
663 * The object being submitted. The 'bundle', 'id' and (if applicable)
664 * 'revision' keys should be present. The actual field values will be read
665 * from $form_state['values'].
666 * @param $form
667 * The form structure.
668 * @param $form_state
669 * An associative array containing the current state of the form.
670 */
671 function field_attach_form_validate($obj_type, $object, $form, &$form_state) {
672 // Extract field values from submitted values.
673 _field_invoke_default('extract_form_values', $obj_type, $object, $form, $form_state);
674
675 // Perform field_level validation.
676 try {
677 field_attach_validate($obj_type, $object);
678 }
679 catch (FieldValidationException $e) {
680 // Pass field-level validation errors back to widgets for accurate error
681 // flagging.
682 _field_invoke_default('form_errors', $obj_type, $object, $form, $e->errors);
683 }
684 }
685
686 /**
687 * Perform necessary operations on field data submitted by a form.
688 *
689 * Currently, this accounts for drag-and-drop reordering of
690 * field values, and filtering of empty values.
691 *
692 * @param $obj_type
693 * The type of $object; e.g. 'node' or 'user'.
694 * @param $object
695 * The object being submitted. The 'bundle', 'id' and (if applicable)
696 * 'revision' keys should be present. The actual field values will be read
697 * from $form_state['values'].
698 * @param $form
699 * The form structure to fill in.
700 * @param $form_state
701 * An associative array containing the current state of the form.
702 */
703 function field_attach_submit($obj_type, $object, $form, &$form_state) {
704 // Extract field values from submitted values.
705 _field_invoke_default('extract_form_values', $obj_type, $object, $form, $form_state);
706
707 _field_invoke_default('submit', $obj_type, $object, $form, $form_state);
708
709 // Let other modules act on submitting the object.
710 foreach (module_implements('field_attach_submit') as $module) {
711 $function = $module . '_field_attach_submit';
712 $function($obj_type, $object, $form, $form_state);
713 }
714 }
715
716 /**
717 * Perform necessary operations just before fields data get saved.
718 *
719 * We take no specific action here, we just give other
720 * modules the opportunity to act.
721 *
722 * @param $obj_type
723 * The type of $object; e.g. 'node' or 'user'.
724 * @param $object
725 * The object with fields to process.
726 */
727 function field_attach_presave($obj_type, $object) {
728 _field_invoke('presave', $obj_type, $object);
729
730 // Let other modules act on presaving the object.
731 foreach (module_implements('field_attach_presave') as $module) {
732 $function = $module . '_field_attach_presave';
733 $function($obj_type, $object);
734 }
735 }
736
737 /**
738 * Save field data for a new object.
739 *
740 * The passed in object must already contain its id and (if applicable)
741 * revision id attributes.
742 * Default values (if any) will be saved for fields not present in the
743 * $object.
744 *
745 * @param $obj_type
746 * The type of $object; e.g. 'node' or 'user'.
747 * @param $object
748 * The object with fields to save.
749 * @return
750 * Default values (if any) will be added to the $object parameter for fields
751 * it leaves unspecified.
752 */
753 function field_attach_insert($obj_type, $object) {
754 _field_invoke_default('insert', $obj_type, $object);
755 _field_invoke('insert', $obj_type, $object);
756
757 // Let other modules act on inserting the object, accumulating saved
758 // fields along the way.
759 $skip_fields = array();
760 foreach (module_implements('field_attach_pre_insert') as $module) {
761 $function = $module . '_field_attach_pre_insert';
762 $function($obj_type, $object, $skip_fields);
763 }
764
765 // Field storage module saves any remaining unsaved fields.
766 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_write', $obj_type, $object, FIELD_STORAGE_INSERT, $skip_fields);
767
768 list($id, $vid, $bundle, $cacheable) = field_attach_extract_ids($obj_type, $object);
769 if ($cacheable) {
770 cache_clear_all("field:$obj_type:$id", 'cache_field');
771 }
772 }
773
774 /**
775 * Save field data for an existing object.
776 *
777 * @param $obj_type
778 * The type of $object; e.g. 'node' or 'user'.
779 * @param $object
780 * The object with fields to save.
781 */
782 function field_attach_update($obj_type, $object) {
783 _field_invoke('update', $obj_type, $object);
784
785 // Let other modules act on updating the object, accumulating saved
786 // fields along the way.
787 $skip_fields = array();
788 foreach (module_implements('field_attach_pre_update') as $module) {
789 $function = $module . '_field_attach_pre_update';
790 $function($obj_type, $object, $skip_fields);
791 }
792
793 // Field storage module saves any remaining unsaved fields.
794 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_write', $obj_type, $object, FIELD_STORAGE_UPDATE, $skip_fields);
795
796 list($id, $vid, $bundle, $cacheable) = field_attach_extract_ids($obj_type, $object);
797 if ($cacheable) {
798 cache_clear_all("field:$obj_type:$id", 'cache_field');
799 }
800 }
801
802 /**
803 * Delete field data for an existing object. This deletes all
804 * revisions of field data for the object.
805 *
806 * @param $obj_type
807 * The type of $object; e.g. 'node' or 'user'.
808 * @param $object
809 * The object whose field data to delete.
810 */
811 function field_attach_delete($obj_type, $object) {
812 _field_invoke('delete', $obj_type, $object);
813 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_delete', $obj_type, $object);
814
815 // Let other modules act on deleting the object.
816 foreach (module_implements('field_attach_delete') as $module) {
817 $function = $module . '_field_attach_delete';
818 $function($obj_type, $object);
819 }
820
821 list($id, $vid, $bundle, $cacheable) = field_attach_extract_ids($obj_type, $object);
822 if ($cacheable) {
823 cache_clear_all("field:$obj_type:$id", 'cache_field');
824 }
825 }
826
827 /**
828 * Delete field data for a single revision of an existing object. The
829 * passed object must have a revision id attribute.
830 *
831 * @param $obj_type
832 * The type of $object; e.g. 'node' or 'user'.
833 * @param $object
834 * The object with fields to save.
835 */
836 function field_attach_delete_revision($obj_type, $object) {
837 _field_invoke('delete_revision', $obj_type, $object);
838 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_delete_revision', $obj_type, $object);
839
840 // Let other modules act on deleting the revision.
841 foreach (module_implements('field_attach_delete_revision') as $module) {
842 $function = $module . '_field_attach_delete_revision';
843 $function($obj_type, $object);
844 }
845 }
846
847 /**
848 * Retrieve objects matching a given set of conditions.
849 *
850 * Note that the query 'conditions' only apply to the stored values.
851 * In a regular field_attach_load() call, field values additionally go through
852 * hook_field_load() and hook_field_attach_load() invocations, which can add
853 * to or affect the raw stored values. The results of field_attach_query()
854 * might therefore differ from what could be expected by looking at a regular,
855 * fully loaded object.
856 *
857 * @param $field_id
858 * The id of the field to query.
859 * @param $conditions
860 * An array of query conditions. Each condition is a numerically indexed
861 * array, in the form: array(column, value, operator).
862 * Not all storage engines are required to support queries on all column, or
863 * with all operators below. A FieldQueryException will be raised if an
864 * unsupported condition is specified.
865 * Supported columns:
866 * - any of the columns for $field_name's field type: condition on field
867 * value,
868 * - 'type': condition on object type (e.g. 'node', 'user'...),
869 * - 'bundle': condition on object bundle (e.g. node type),
870 * - 'entity_id': condition on object id (e.g node nid, user uid...),
871 * - 'deleted': condition on whether the field's data is
872 * marked deleted for the object (defaults to FALSE if not specified)
873 * The field_attach_query_revisions() function additionally supports:
874 * - 'revision_id': condition on object revision id (e.g node vid).
875 * Supported operators:
876 * - '=', '!=', '>', '>=', '<', '<=', 'STARTS_WITH', 'ENDS_WITH',
877 * 'CONTAINS': these operators expect the value as a literal of the same
878 * type as the column,
879 * - 'IN', 'NOT IN': this operator expects the value as an array of
880 * literals of the same type as the column.
881 * - 'BETWEEN': this operator expects the value as an array of two literals
882 * of the same type as the column.
883 * The operator can be ommitted, and will default to 'IN' if the value is
884 * an array, or to '=' otherwise.
885 * Example values for $conditions:
886 * @code
887 * array(
888 * array('type', 'node'),
889 * );
890 * array(
891 * array('bundle', array('article', 'page')),
892 * array('value', 12, '>'),
893 * );
894 * @endcode
895 * @param $count
896 * The number of results that is requested. This is only a
897 * hint to the storage engine(s); callers should be prepared to
898 * handle fewer or more results. Specify FIELD_QUERY_NO_LIMIT to retrieve
899 * all available objects. This parameter has no default value so
900 * callers must make an explicit choice to potentially retrieve an
901 * enormous result set.
902 * @param &$cursor
903 * An opaque cursor that allows a caller to iterate through multiple
904 * result sets. On the first call, pass 0; the correct value to pass
905 * on the next call will be written into $cursor on return. When
906 * there is no more query data available, $cursor will be filled in
907 * with FIELD_QUERY_COMPLETE. If $cursor is passed as NULL,
908 * the first result set is returned and no next cursor is returned.
909 * @param $age
910 * Internal use only. Use field_attach_query_revisions() instead of passing
911 * FIELD_LOAD_REVISION.
912 * - FIELD_LOAD_CURRENT (default): query the most recent revisions for all
913 * objects. The results will be keyed by object type and object id.
914 * - FIELD_LOAD_REVISION: query all revisions. The results will be keyed by
915 * object type and object revision id.
916 * @return
917 * An array keyed by object type (e.g. 'node', 'user'...), then by object id
918 * or revision id (depending of the value of the $age parameter).
919 * The values are pseudo-objects with the bundle, id, and revision
920 * id fields filled in.
921 *
922 * Throws a FieldQueryException if the field's storage doesn't support the
923 * specified conditions.
924 */
925 function field_attach_query($field_id, $conditions, $count, &$cursor = NULL, $age = FIELD_LOAD_CURRENT) {
926 if (!isset($cursor)) {
927 $cursor = 0;
928 }
929
930 // Give a chance to 3rd party modules that bypass the storage engine to
931 // handle the query.
932 $skip_field = FALSE;
933 foreach (module_implements('field_attach_pre_query') as $module) {
934 $function = $module . '_field_attach_pre_query';
935 $results = $function($field_id, $conditions, $count, $cursor, $age, $skip_field);
936 // Stop as soon as a module claims it handled the query.
937 if ($skip_field) {
938 break;
939 }
940 }
941 // If the request hasn't been handled, let the storage engine handle it.
942 if (!$skip_field) {
943 $function = variable_get('field_storage_module', 'field_sql_storage') . '_field_storage_query';
944 $results = $function($field_id, $conditions, $count, $cursor, $age);
945 }
946
947 return $results;
948 }
949
950 /**
951 * Retrieve object revisions matching a given set of conditions.
952 *
953 * See field_attach_query() for more informations.
954 *
955 * @param $field_id
956 * The id of the field to query.
957 * @param $conditions
958 * See field_attach_query().
959 * @param $count
960 * The number of results that is requested. This is only a
961 * hint to the storage engine(s); callers should be prepared to
962 * handle fewer or more results. Specify FIELD_QUERY_NO_LIMIT to retrieve
963 * all available objects. This parameter has no default value so
964 * callers must make an explicit choice to potentially retrieve an
965 * enormous result set.
966 * @param &$cursor
967 * An opaque cursor that allows a caller to iterate through multiple
968 * result sets. On the first call, pass 0; the correct value to pass
969 * on the next call will be written into $cursor on return.
970 * @return
971 * See field_attach_query().
972 */
973 function field_attach_query_revisions($field_id, $conditions, $count, &$cursor = NULL) {
974 return field_attach_query($field_id, $conditions, $count, $cursor, FIELD_LOAD_REVISION);
975 }
976
977 /**
978 * Generate and return a structured content array tree suitable for
979 * drupal_render() for all of the fields on an object. The format of
980 * each field's rendered content depends on the display formatter and
981 * its settings.
982 *
983 * @param $obj_type
984 * The type of $object; e.g. 'node' or 'user'.
985 * @param $object
986 * The object with fields to render.
987 * @param $build_mode
988 * Build mode, e.g. 'full', 'teaser'...
989 * @return
990 * A structured content array tree for drupal_render().
991 * Sample structure:
992 * @code
993 * array(
994 * 'field_foo' => array(
995 * // The structure of the array differs slightly depending on whether
996 * // the formatter is 'single-value' (displays one single field value,
997 * // most common case) or 'multiple-values' (displays all the field's
998 * // values, e.g. points on a graph or a map).
999 * '#theme' => 'field',
1000 * '#title' => the label of the field instance,
1001 * '#label_display' => the label display mode,
1002 * '#object' => the fieldable object being displayed,
1003 * '#object_type' => the type of the object being displayed,
1004 * '#build_mode' => the build mode,
1005 * '#field_name' => the name of the field,
1006 * '#single' => boolean indicating whether the formatter is single or
1007 * multiple,
1008 * 'items' => array(
1009 * // One sub-array per field value, keyed by delta.
1010 * 0 => array(
1011 * '#item' => the field value for delta 0,
1012 *
1013 * // Only for 'single-value' formatters:
1014 * '#theme' => the formatter's theme function,
1015 * '#formatter' => name of the formatter,
1016 * '#settings' => array of formatter settings,
1017 * '#object' => the fieldable object being displayed,
1018 * '#object_type' => the type of the object being displayed,
1019 * '#field_name' => the name of the field,
1020 * '#bundle' => the object's bundle,
1021 * '#delta' => 0,
1022 * ),
1023 * 1 => array(
1024 * ...
1025 * ),
1026 *
1027 * // Only for 'multiple-values' formatters:
1028 * '#theme' => the formatter's theme function,
1029 * '#formatter' => name of the formatter,
1030 * '#settings' => array of formatter settings,
1031 * '#object' => the fieldable object being displayed,
1032 * '#object_type' => the type of the object being displayed,
1033 * '#field_name' => the name of the field,
1034 * '#bundle' => the object's bundle,
1035 * ),
1036 * ),
1037 * );
1038 * @endcode
1039 */
1040 function field_attach_view($obj_type, $object, $build_mode = 'full') {
1041 // Let field modules sanitize their data for output.
1042 _field_invoke('sanitize', $obj_type, $object);
1043
1044 $output = _field_invoke_default('view', $obj_type, $object, $build_mode);
1045
1046 // Let other modules make changes after rendering the view.
1047 drupal_alter('field_attach_view', $output, $obj_type, $object, $build_mode);
1048
1049 return $output;
1050
1051 }
1052
1053 /**
1054 * Implement hook_node_prepare_translation.
1055 *
1056 * TODO D7: We do not yet know if this really belongs in Field API.
1057 */
1058 function field_attach_prepare_translation($node) {
1059 // Prevent against invalid 'nodes' built by broken 3rd party code.
1060 if (isset($node->type)) {
1061 $type = content_types($node->type);
1062 // Save cycles if the type has no fields.
1063 if (!empty($type['instances'])) {
1064 $default_additions = _field_invoke_default('prepare_translation', $node);
1065 $additions = _field_invoke('prepare_translation', $node);
1066 // Merge module additions after the default ones to enable overriding
1067 // of field values.
1068 $node = (object) array_merge((array) $node, $default_additions, $additions);
1069 }
1070 }
1071 }
1072
1073 /**
1074 * Notify field.module that a new bundle was created.
1075 *
1076 * The default SQL-based storage doesn't need to do anytrhing about it, but
1077 * others might.
1078 *
1079 * @param $bundle
1080 * The name of the newly created bundle.
1081 */
1082 function field_attach_create_bundle($bundle) {
1083 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_create_bundle', $bundle);
1084
1085 // Clear the cache.
1086 field_cache_clear();
1087
1088 foreach (module_implements('field_attach_create_bundle') as $module) {
1089 $function = $module . '_field_attach_create_bundle';
1090 $function($bundle);
1091 }
1092 }
1093
1094 /**
1095 * Notify field.module that a bundle was renamed.
1096 *
1097 * @param $bundle_old
1098 * The previous name of the bundle.
1099 * @param $bundle_new
1100 * The new name of the bundle.
1101 */
1102 function field_attach_rename_bundle($bundle_old, $bundle_new) {
1103 module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_rename_bundle', $bundle_old, $bundle_new);
1104 db_update('field_config_instance')
1105 ->fields(array('bundle' => $bundle_new))
1106 ->condition('bundle', $bundle_old)
1107 ->execute();
1108
1109 // Clear the cache.
1110 field_cache_clear();
1111
1112 foreach (module_implements('field_attach_rename_bundle') as $module) {
1113 $function = $module . '_field_attach_rename_bundle';
1114 $function($bundle_old, $bundle_new);
1115 }
1116 }
1117
1118 /**
1119 * Notify field.module the a bundle was deleted.
1120 *
1121 * This deletes the data for the field instances as well as the field instances
1122 * themselves. This function actually just marks the data and field instances
1123 * and deleted, leaving the garbage collection for a separate process, because
1124 * it is not always possible to delete this much data in a single page request
1125 * (particularly since for some field types, the deletion is more than just a
1126 * simple DELETE query).
1127 *
1128 * @param $bundle
1129 * The bundle to delete.
1130 */
1131 function field_attach_delete_bundle($bundle) {
1132 // Delete the instances themseves
1133 $instances = field_info_instances($bundle);
1134 foreach ($instances as $instance) {
1135 field_delete_instance($instance['field_name'], $bundle);
1136 }
1137
1138 // Let other modules act on deleting the bundle.
1139 foreach (module_implements('field_attach_delete_bundle') as $module) {
1140 $function = $module . '_field_attach_delete_bundle';
1141 $function($bundle, $instances);
1142 }
1143 }
1144
1145 /**
1146 * Helper function to extract id, vid, and bundle name from an object.
1147 *
1148 * @param $obj_type
1149 * The type of $object; e.g. 'node' or 'user'.
1150 * @param $object
1151 * The object from which to extract values.
1152 * @return
1153 * A numerically indexed array (not a hash table) containing these
1154 * elements:
1155 *
1156 * 0: primary id of the object
1157 * 1: revision id of the object, or NULL if $obj_type is not versioned
1158 * 2: bundle name of the object
1159 * 3: whether $obj_type's fields should be cached (TRUE/FALSE)
1160 */
1161 function field_attach_extract_ids($obj_type, $object) {
1162 // TODO D7 : prevent against broken 3rd party $node without 'type'.
1163 $info = field_info_fieldable_types($obj_type);
1164 // Objects being created might not have id/vid yet.
1165 $id = isset($object->{$info['object keys']['id']}) ? $object->{$info['object keys']['id']} : NULL;
1166 $vid = ($info['object keys']['revision'] && isset($object->{$info['object keys']['revision']})) ? $object->{$info['object keys']['revision']} : NULL;
1167 // If no bundle key provided, then we assume a single bundle, named after the
1168 // type of the object.
1169 $bundle = $info['object keys']['bundle'] ? $object->{$info['object keys']['bundle']} : $obj_type;
1170 $cacheable = $info['cacheable'];
1171 return array($id, $vid, $bundle, $cacheable);
1172 }
1173
1174 /**
1175 * Helper function to extract id, vid, and bundle name from an object.
1176 *
1177 * @param $obj_type
1178 * The type of $object; e.g. 'node' or 'user'.
1179 * @param $bundle
1180 * The bundle object (or string if bundles for this object type do not exist
1181 * as standalone objects).
1182 * @return
1183 * The bundle name.
1184 */
1185 function field_attach_extract_bundle($obj_type, $bundle) {
1186 if (is_string($bundle)) {
1187 return $bundle;
1188 }
1189
1190 $info = field_info_fieldable_types($obj_type);
1191 if (is_object($bundle) && isset($info['bundle keys']['bundle']) && isset($bundle->{$info['bundle keys']['bundle']})) {
1192 return $bundle->{$info['bundle keys']['bundle']};
1193 }
1194 }
1195
1196 /**
1197 * Helper function to assemble an object structure with initial ids.
1198 *
1199 * This function can be seen as reciprocal to field_attach_extract_ids().
1200 *
1201 * @param $obj_type
1202 * The type of $object; e.g. 'node' or 'user'.
1203 * @param $ids
1204 * A numerically indexed array, as returned by field_attach_extract_ids(),
1205 * containing these elements:
1206 * 0: primary id of the object
1207 * 1: revision id of the object, or NULL if $obj_type is not versioned
1208 * 2: bundle name of the object
1209 * @return
1210 * An $object structure, initialized with the ids provided.
1211 */
1212 function field_attach_create_stub_object($obj_type, $ids) {
1213 $object = new stdClass();
1214 $info = field_info_fieldable_types($obj_type);
1215 $object->{$info['object keys']['id']} = $ids[0];
1216 if (isset($info['object keys']['revision']) && !is_null($ids[1])) {
1217 $object->{$info['object keys']['revision']} = $ids[1];
1218 }
1219 if ($info['object keys']['bundle']) {
1220 $object->{$info['object keys']['bundle']} = $ids[2];
1221 }
1222 return $object;
1223 }
1224
1225 /**
1226 * @} End of "defgroup field_attach"
1227 */
1228

Legend

Missed
lines code that were not excersized during program execution.
Covered
lines code were excersized during program execution.
Comment/non executable
Comment or non-executable line of code.
Dead
lines of code that according to xdebug could not be executed. This is counted as coverage code because in almost all cases it is code that runnable.