field.attach.inc 38.8 KB
Newer Older
1
2
3
<?php
// $Id$

4
5
6
7
8
/**
 * @file
 * Field attach API, allowing objects (nodes, users, ...) to be 'fieldable'.
 */

9
/**
10
 * Exception thrown by field_attach_validate() on field validation errors.
11
12
13
14
15
16
17
18
19
20
21
 */
class FieldValidationException extends FieldException {
  var $errors;

 /**
  * Constructor for FieldValidationException.
  *
  * @param $errors
  *   An array of field validation errors, keyed by field name and
  *   delta that contains two keys:
  *   - 'error': A machine-readable error code string, prefixed by
22
  *     the field module name. A field widget may use this code to decide
23
24
25
26
27
28
29
30
31
32
  *     how to report the error.
  *   - 'message': A human-readable error message such as to be
  *     passed to form_error() for the appropriate form element.
  */
  function __construct($errors) {
    $this->errors = $errors;
    parent::__construct(t('Field validation errors'));
  }
}

33
34
35
36
37
38
39
40
41
/**
 * Exception thrown by field_attach_query() on unsupported query syntax.
 *
 * Some storage modules might not support the full range of the syntax for
 * conditions, and will raise a FieldQueryException when an usupported
 * condition was specified.
 */
class FieldQueryException extends FieldException {}

42
43
44
45
46
47
/**
 * @defgroup field_storage Field Storage API
 * @{
 * Implement a storage engine for Field API data.
 *
 * The Field Attach API uses the Field Storage API to perform all
48
49
 * "database access". Each Field Storage API hook function defines a
 * primitive database operation such as read, write, or delete. The
50
51
52
53
54
55
56
57
58
 * default field storage module, field_sql_storage.module, uses the
 * local SQL database to implement these operations, but alternative
 * field storage engines can choose to represent the data in SQL
 * differently or use a completely different storage mechanism such as
 * a cloud-based database.
 *
 * The Drupal system variable field_storage_module identifies the
 * field storage module to use.
 */
59
60
61

/**
 * Argument for an insert operation.
62
 * This is used in hook_field_storage_write when updating an
63
64
65
66
67
68
69
70
71
72
 * existing object.
 */
define('FIELD_STORAGE_UPDATE', 'update');

/**
 * Argument for an update operation.
 * This is used in hook_field_storage_write when inserting a new object.
 */
define('FIELD_STORAGE_INSERT', 'insert');

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
 * @} End of "defgroup field_storage"
 */

/**
 * @defgroup field_attach Field Attach API
 * @{
 * Operate on Field API data attached to Drupal objects.
 *
 * Field Attach API functions load, store, generate Form API
 * structures, display, and perform a vareity of other functions for
 * field data connected to individual objects.
 *
 * Field Attach API functions generally take $obj_type and $object
 * arguments along with additional function-specific arguments.
 * $obj_type is the type of the fieldable entity, such as 'node' or
89
 * 'user', and $object is the object itself. An individual object's
90
91
92
93
 * bundle, if any, is read from the object's bundle key property
 * identified by hook_fieldable_info() for $obj_type.
 *
 * Fieldable types call Field Attach API functions during their own
94
 * API calls; for example, node_load() calls field_attach_load(). A
95
 * fieldable type is not required to use all of the Field Attach
96
97
98
99
 * API functions.
 *
 * Most Field Attach API functions define a corresponding hook
 * function that allows any module to act on Field Attach operations
100
101
102
 * for any object after the operation is complete, and access or
 * modify all the field, form, or display data for that object and
 * operation. For example, field_attach_view() invokes
103
 * hook_field_attach_view_alter(). These all-module hooks are distinct from
104
105
106
107
108
 * those of the Field Types API, such as hook_field_load(), that are
 * only invoked for the module that defines a specific field type.
 *
 * field_attach_load(), field_attach_insert(), and
 * field_attach_update() also define pre-operation hooks,
109
 * e.g. hook_field_attach_pre_load(). These hooks run before the
110
111
112
 * corresponding Field Storage API and Field Type API operations.
 * They allow modules to define additional storage locations
 * (e.g. denormalizing, mirroring) for field data on a per-field
113
 * basis. They also allow modules to take over field storage
114
115
116
117
118
119
120
121
 * completely by instructing other implementations of the same hook
 * and the Field Storage API itself not to operate on specified
 * fields.
 *
 * The pre-operation hooks do not make the Field Storage API
 * irrelevant. The Field Storage API is essentially the "fallback
 * mechanism" for any fields that aren't being intercepted explicitly
 * by pre-operation hooks.
122
123
124
125
126
127
 */

/**
 * Invoke a field hook.
 *
 * @param $op
128
 *   Possible operations include:
129
130
131
132
133
134
135
136
137
138
139
 *   - form
 *   - validate
 *   - presave
 *   - insert
 *   - update
 *   - delete
 *   - delete revision
 *   - sanitize
 *   - view
 *   - prepare translation
 * @param $obj_type
140
 *   The type of $object; e.g. 'node' or 'user'.
141
 * @param $object
142
 *   The fully formed $obj_type object.
143
 * @param $a
144
 *   - The $form in the 'form' operation.
145
 *   - The value of $build_mode in the 'view' operation.
146
 *   - Otherwise NULL.
147
 * @param $b
148
149
 *   - The $form_state in the 'submit' operation.
 *   - Otherwise NULL.
150
151
152
153
154
155
156
157
158
159
160
161
162
163
 * @param $options
 *   An associative array of additional options, with the following keys:
 *  - 'field_name'
 *    The name of the field whose operation should be invoked. By default, the
 *    operation is invoked on all the fields in the object's bundle.
 *  - 'default'
 *    A boolean value, specifying which implementation of the operation should
 *    be invoked.
 *    - if FALSE (default), the field types implementation of the operation
 *      will be invoked (hook_field_[op])
 *    - If TRUE, the default field implementation of the field operation
 *      will be invoked (field_default_[op])
 *    Internal use only. Do not explicitely set to TRUE, but use
 *    _field_invoke_default() instead.
164
 */
165
166
167
168
169
170
171
172
function _field_invoke($op, $obj_type, $object, &$a = NULL, &$b = NULL, $options = array()) {
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
  );
  $options += $default_options;

  // Iterate through the object's field instances.
173
  $return = array();
174
175
  list(, , $bundle) = field_attach_extract_ids($obj_type, $object);
  foreach (field_info_instances($bundle) as $instance) {
176
177
    $field_name = $instance['field_name'];

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
    // When in 'single field' mode, only act on the specified field.
    if (empty($options['field_name']) || $options['field_name'] == $field_name) {
      $field = field_info_field($field_name);

      // Extract the field values into a separate variable, easily accessed by
      // hook implementations.
      $items = isset($object->$field_name) ? $object->$field_name : array();

      // Invoke the field hook and collect results.
      $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
      if (drupal_function_exists($function)) {
        $result = $function($obj_type, $object, $field, $instance, $items, $a, $b);
        if (isset($result)) {
          // For hooks with array results, we merge results together.
          // For hooks with scalar results, we collect results in an array.
          if (is_array($result)) {
            $return = array_merge($return, $result);
          }
          else {
            $return[] = $result;
          }
        }
200
      }
201
202
203
204
205

      // Populate field values back in the object, but avoid replacing missing
      // fields with an empty array (those are not equivalent on update).
      if ($items !== array() || property_exists($object, $field_name)) {
        $object->$field_name = $items;
206
207
208
209
210
211
212
      }
    }
  }

  return $return;
}

213
/**
214
 * Invoke a field hook across fields on multiple objects.
215
216
217
218
 *
 * @param $op
 *   Possible operations include:
 *   - load
219
220
 *   For all other operations, use _field_invoke() / field_invoke_default()
 *   instead.
221
222
223
224
225
226
227
228
229
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $objects
 *   An array of objects, keyed by object id.
 * @param $a
 *   - The $age parameter in the 'load' operation.
 *   - Otherwise NULL.
 * @param $b
 *   Currently always NULL.
230
231
232
233
234
235
236
237
238
239
240
241
242
243
 * @param $options
 *   An associative array of additional options, with the following keys:
 *  - 'field_name'
 *    The name of the field whose operation should be invoked. By default, the
 *    operation is invoked on all the fields in the objects' bundles.
 *  - 'default'
 *    A boolean value, specifying which implementation of the operation should
 *    be invoked.
 *    - if FALSE (default), the field types implementation of the operation
 *      will be invoked (hook_field_[op])
 *    - If TRUE, the default field implementation of the field operation
 *      will be invoked (field_default_[op])
 *    Internal use only. Do not explicitely set to TRUE, but use
 *    _field_invoke_multiple_default() instead.
244
245
246
 * @return
 *   An array of returned values keyed by object id.
 */
247
248
249
250
251
252
253
function _field_invoke_multiple($op, $obj_type, $objects, &$a = NULL, &$b = NULL, $options = array()) {
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
  );
  $options += $default_options;

254
255
256
257
258
259
  $fields = array();
  $grouped_instances = array();
  $grouped_objects = array();
  $grouped_items = array();
  $return = array();

260
261
  // Go through the objects and collect the fields on which the hook should be
  // invoked.
262
263
264
265
  foreach ($objects as $object) {
    list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
    foreach (field_info_instances($bundle) as $instance) {
      $field_name = $instance['field_name'];
266
267
268
269
270
271
272
273
274
275
276
277
      // When in 'single field' mode, only act on the specified field.
      if (empty($options['field_name']) || $options['field_name'] == $field_name) {
        // Add the field to the list of fields to invoke the hook on.
        if (!isset($fields[$field_name])) {
          $fields[$field_name] = field_info_field($field_name);
        }
        // Group the corresponding instances and objects.
        $grouped_instances[$field_name][$id] = $instance;
        $grouped_objects[$field_name][$id] = $objects[$id];
        // Extract the field values into a separate variable, easily accessed
        // by hook implementations.
        $grouped_items[$field_name][$id] = isset($object->$field_name) ? $object->$field_name : array();
278
279
      }
    }
280
    // Initialize the return value for each object.
281
282
283
    $return[$id] = array();
  }

284
  // For each field, invoke the field hook and collect results.
285
  foreach ($fields as $field_name => $field) {
286
287
288
289
290
291
292
293
294
295
296
297
298
    $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
    if (drupal_function_exists($function)) {
      $results = $function($obj_type, $grouped_objects[$field_name], $field, $grouped_instances[$field_name], $grouped_items[$field_name], $a, $b);
      if (isset($results)) {
        // Collect results by object.
        // For hooks with array results, we merge results together.
        // For hooks with scalar results, we collect results in an array.
        foreach ($results as $id => $result) {
          if (is_array($result)) {
            $return[$id] = array_merge($return[$id], $result);
          }
          else {
            $return[$id][] = $result;
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
          }
        }
      }
    }

    // Populate field values back in the objects, but avoid replacing missing
    // fields with an empty array (those are not equivalent on update).
    foreach ($grouped_objects[$field_name] as $id => $object) {
      if ($grouped_items[$field_name][$id] !== array() || property_exists($object, $field_name)) {
        $object->$field_name = $grouped_items[$field_name][$id];
      }
    }
  }

  return $return;
}

316
317
/**
 * Invoke field.module's version of a field hook.
318
319
320
321
322
323
 *
 * This function invokes the field_default_[op]() function.
 * Use _field_invoke() to invoke the field type implementation,
 * hook_field_[op]().
 *
 * @see _field_invoke().
324
 */
325
326
327
function _field_invoke_default($op, $obj_type, $object, &$a = NULL, &$b = NULL, $options = array()) {
  $options['default'] = TRUE;
  return _field_invoke($op, $obj_type, $object, $a, $b, $options);
328
329
}

330
331
/**
 * Invoke field.module's version of a field hook on multiple objects.
332
333
334
335
336
337
 *
 * This function invokes the field_default_[op]() function.
 * Use _field_invoke_multiple() to invoke the field type implementation,
 * hook_field_[op]().
 *
 * @see _field_invoke_multiple().
338
 */
339
340
341
function _field_invoke_multiple_default($op, $obj_type, $objects, &$a = NULL, &$b = NULL, $options = array()) {
  $options['default'] = TRUE;
  return _field_invoke_multiple($op, $obj_type, $objects, $a, $b, $options);
342
343
}

344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
 * Add form elements for all fields for an object to a form structure.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object for which to load form elements, used to initialize
 *   default form values.
 * @param $form
 *   The form structure to fill in.
 * @param $form_state
 *   An associative array containing the current state of the form.
 *
 * TODO : document the resulting $form structure, like we do for
 * field_attach_view().
 */
360
function field_attach_form($obj_type, $object, &$form, &$form_state) {
361
362
363
364
365
366
367
368
369
370
371
372
373
374
  $form += (array) _field_invoke_default('form', $obj_type, $object, $form, $form_state);

  // Let other modules make changes to the form.
  foreach (module_implements('field_attach_form') as $module) {
    $function = $module . '_field_attach_form';
    $function($obj_type, $object, $form, $form_state);
  }
}

/**
 * Load all fields for the most current version of each of a set of
 * objects of a single object type.
 *
 * @param $obj_type
375
 *   The type of $object; e.g. 'node' or 'user'.
376
 * @param $objects
377
 *   An array of objects for which to load fields, keyed by object id.
378
379
 *   Each object needs to have its 'bundle', 'id' and (if applicable)
 *   'revision' keys filled.
380
381
382
 * @param $age
 *   FIELD_LOAD_CURRENT to load the most recent revision for all
 *   fields, or FIELD_LOAD_REVISION to load the version indicated by
383
 *   each object. Defaults to FIELD_LOAD_CURRENT; use
384
 *   field_attach_load_revision() instead of passing FIELD_LOAD_REVISION.
385
386
387
388
389
390
 * @param $options
 *   An associative array of additional options, with the following keys:
 *   - 'field_name'
 *     The field name that should be loaded, instead of loading all fields, for
 *     each object. Note that returned objects may contain data for other
 *     fields, for example if they are read from a cache.
391
 * @returns
392
393
 *   Loaded field values are added to $objects. Fields with no values should be
 *   set as an empty array.
394
 */
395
function field_attach_load($obj_type, $objects, $age = FIELD_LOAD_CURRENT, $options = array()) {
396
  $load_current = $age == FIELD_LOAD_CURRENT;
397

398
  $info = field_info_fieldable_types($obj_type);
399
400
401
402
  // Only the most current revision of cacheable fieldable types can be cached.
  $cache_read = $load_current && $info['cacheable'];
  // In addition, do not write to the cache when loading a single field.
  $cache_write = $cache_read && !isset($options['field_name']);
403

404
405
406
407
408
409
410
  if (empty($objects)) {
    return;
  }

  // Assume all objects will need to be queried. Objects found in the cache
  // will be removed from the list.
  $queried_objects = $objects;
411

412
  // Fetch available objects from cache, if applicable.
413
  if ($cache_read) {
414
415
416
417
418
419
420
421
    // Build the list of cache entries to retrieve.
    $cids = array();
    foreach ($objects as $id => $object) {
      $cids[] = "field:$obj_type:$id";
    }
    $cache = cache_get_multiple($cids, 'cache_field');
    // Put the cached field values back into the objects and remove them from
    // the list of objects to query.
422
423
    foreach ($objects as $id => $object) {
      $cid = "field:$obj_type:$id";
424
425
426
427
      if (isset($cache[$cid])) {
        unset($queried_objects[$id]);
        foreach ($cache[$cid]->data as $field_name => $values) {
          $object->$field_name = $values;
428
429
        }
      }
430
    }
431
432
  }

433
  // Fetch other objects from their storage location.
434
  if ($queried_objects) {
435
    // The invoke order is:
436
437
    // - hook_field_attach_pre_load()
    // - storage engine's hook_field_storage_load()
438
    // - field-type module's hook_field_load()
439
440
    // - hook_field_attach_load()

441
    // Invoke hook_field_attach_pre_load(): let any module load field
442
443
444
445
    // data before the storage engine, accumulating along the way.
    $skip_fields = array();
    foreach (module_implements('field_attach_pre_load') as $module) {
      $function = $module . '_field_attach_pre_load';
446
      $function($obj_type, $queried_objects, $age, $skip_fields, $options);
447
448
449
450
    }

    // Invoke the storage engine's hook_field_storage_load(): the field storage
    // engine loads the rest.
451
    module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_load', $obj_type, $queried_objects, $age, $skip_fields, $options);
452

453
    // Invoke field-type module's hook_field_load().
454
    _field_invoke_multiple('load', $obj_type, $queried_objects, $age, $options);
455
456
457
458
459

    // Invoke hook_field_attach_load(): let other modules act on loading the
    // object.
    foreach (module_implements('field_attach_load') as $module) {
      $function = $module . '_field_attach_load';
460
      $function($obj_type, $queried_objects, $age, $options);
461
    }
462

463
    // Build cache data.
464
    if ($cache_write) {
465
466
467
468
469
470
      foreach ($queried_objects as $id => $object) {
        $data = array();
        list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
        $instances = field_info_instances($bundle);
        foreach ($instances as $instance) {
          $data[$instance['field_name']] = $queried_objects[$id]->{$instance['field_name']};
471
        }
472
        $cid = "field:$obj_type:$id";
473
474
475
476
477
478
479
480
481
482
        cache_set($cid, $data, 'cache_field');
      }
    }
  }
}

/**
 * Load all fields for a previous version of each of a set of
 * objects of a single object type.
 *
483
484
485
 * Loading different versions of the same objects is not supported,
 * and should be done by separate calls to the function.
 *
486
 * @param $obj_type
487
 *   The type of $object; e.g. 'node' or 'user'.
488
 * @param $objects
489
 *   An array of objects for which to load fields, keyed by object id.
490
491
 *   Each object needs to have its 'bundle', 'id' and (if applicable)
 *   'revision' keys filled.
492
493
494
495
496
497
 * @param $options
 *   An associative array of additional options, with the following keys:
 *   - 'field_name'
 *     The field name that should be loaded, instead of loading all fields, for
 *     each object. Note that returned objects may contain data for other
 *     fields, for example if they are read from a cache.
498
499
500
501
 * @returns
 *   On return, the objects in $objects are modified by having the
 *   appropriate set of fields added.
 */
502
503
function field_attach_load_revision($obj_type, $objects, $options = array()) {
  return field_attach_load($obj_type, $objects, FIELD_LOAD_REVISION, $options);
504
505
506
507
508
}

/**
 * Perform field validation against the field data in an object.
 *
509
510
511
512
 * This function does not perform field widget validation on form
 * submissions. It is intended to be called during API save
 * operations. Use field_attach_form_validate() to validate form
 * submissions.
513
514
515
516
517
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object with fields to validate.
518
519
 * @return
 *   Throws a FieldValidationException if validation errors are found.
520
 */
521
function field_attach_validate($obj_type, $object) {
522
523
  $errors = array();
  _field_invoke('validate', $obj_type, $object, $errors);
524
525
526
527

  // Let other modules validate the object.
  foreach (module_implements('field_attach_validate') as $module) {
    $function = $module . '_field_attach_validate';
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    $function($obj_type, $object, $errors);
  }

  if ($errors) {
    throw new FieldValidationException($errors);
  }
}

/**
 * Perform field validation against form-submitted field values.
 *
 * There are two levels of validation for fields in forms: widget
 * validation, and field validation.
 * - Widget validation steps are specific to a given widget's own form
 * structure and UI metaphors. They are executed through FAPI's
 * #element_validate property during normal form validation.
 * - Field validation steps are common to a given field type, independently of
 * the specific widget being used in a given form. They are defined in the
 * field type's implementation of hook_field_validate().
 *
 * This function performs field validation in the context of a form
 * submission. It converts field validation errors into form errors
 * on the correct form elements. Fieldable object types should call
 * this function during their own form validation function.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
556
557
 *   The object being submitted. The 'bundle', 'id' and (if applicable)
 *   'revision' keys should be present. The actual field values will be read
558
559
560
561
562
563
 *   from $form_state['values'].
 * @param $form
 *   The form structure.
 * @param $form_state
 *   An associative array containing the current state of the form.
 */
564
function field_attach_form_validate($obj_type, $object, $form, &$form_state) {
565
566
567
568
569
570
571
572
573
574
575
  // Extract field values from submitted values.
  _field_invoke_default('extract_form_values', $obj_type, $object, $form, $form_state);

  // Perform field_level validation.
  try {
    field_attach_validate($obj_type, $object);
  }
  catch (FieldValidationException $e) {
    // Pass field-level validation errors back to widgets for accurate error
    // flagging.
    _field_invoke_default('form_errors', $obj_type, $object, $form, $e->errors);
576
577
578
579
580
581
582
583
584
585
586
587
  }
}

/**
 * Perform necessary operations on field data submitted by a form.
 *
 * Currently, this accounts for drag-and-drop reordering of
 * field values, and filtering of empty values.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
588
589
 *   The object being submitted. The 'bundle', 'id' and (if applicable)
 *   'revision' keys should be present. The actual field values will be read
590
591
592
593
594
595
 *   from $form_state['values'].
 * @param $form
 *   The form structure to fill in.
 * @param $form_state
 *   An associative array containing the current state of the form.
 */
596
function field_attach_submit($obj_type, $object, $form, &$form_state) {
597
598
599
  // Extract field values from submitted values.
  _field_invoke_default('extract_form_values', $obj_type, $object, $form, $form_state);

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
  _field_invoke_default('submit', $obj_type, $object, $form, $form_state);

  // Let other modules act on submitting the object.
  foreach (module_implements('field_attach_submit') as $module) {
    $function = $module . '_field_attach_submit';
    $function($obj_type, $object, $form, $form_state);
  }
}

/**
 * Perform necessary operations just before fields data get saved.
 *
 * We take no specific action here, we just give other
 * modules the opportunity to act.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object with fields to process.
 */
620
function field_attach_presave($obj_type, $object) {
621
622
623
624
625
626
627
628
629
630
  _field_invoke('presave', $obj_type, $object);

  // Let other modules act on presaving the object.
  foreach (module_implements('field_attach_presave') as $module) {
    $function = $module . '_field_attach_presave';
    $function($obj_type, $object);
  }
}

/**
631
632
633
634
635
636
 * Save field data for a new object.
 *
 * The passed in object must already contain its id and (if applicable)
 * revision id attributes.
 * Default values (if any) will be saved for fields not present in the
 * $object.
637
638
639
640
641
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object with fields to save.
642
643
644
 * @return
 *   Default values (if any) will be added to the $object parameter for fields
 *   it leaves unspecified.
645
 */
646
function field_attach_insert($obj_type, $object) {
647
  _field_invoke_default('insert', $obj_type, $object);
648
649
650
651
  _field_invoke('insert', $obj_type, $object);

  // Let other modules act on inserting the object, accumulating saved
  // fields along the way.
652
  $skip_fields = array();
653
654
  foreach (module_implements('field_attach_pre_insert') as $module) {
    $function = $module . '_field_attach_pre_insert';
655
    $function($obj_type, $object, $skip_fields);
656
657
  }

658
  // Field storage module saves any remaining unsaved fields.
659
  module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_write', $obj_type, $object, FIELD_STORAGE_INSERT, $skip_fields);
660
661
662

  list($id, $vid, $bundle, $cacheable) = field_attach_extract_ids($obj_type, $object);
  if ($cacheable) {
663
    cache_clear_all("field:$obj_type:$id", 'cache_field');
664
665
666
667
668
669
670
671
672
673
674
  }
}

/**
 * Save field data for an existing object.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object with fields to save.
 */
675
function field_attach_update($obj_type, $object) {
676
677
678
679
  _field_invoke('update', $obj_type, $object);

  // Let other modules act on updating the object, accumulating saved
  // fields along the way.
680
  $skip_fields = array();
681
682
  foreach (module_implements('field_attach_pre_update') as $module) {
    $function = $module . '_field_attach_pre_update';
683
    $function($obj_type, $object, $skip_fields);
684
685
  }

686
  // Field storage module saves any remaining unsaved fields.
687
  module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_write', $obj_type, $object, FIELD_STORAGE_UPDATE, $skip_fields);
688
689
690

  list($id, $vid, $bundle, $cacheable) = field_attach_extract_ids($obj_type, $object);
  if ($cacheable) {
691
    cache_clear_all("field:$obj_type:$id", 'cache_field');
692
693
694
695
  }
}

/**
696
 * Delete field data for an existing object. This deletes all
697
698
699
700
701
702
703
 * revisions of field data for the object.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object whose field data to delete.
 */
704
function field_attach_delete($obj_type, $object) {
705
706
707
708
709
710
711
712
713
714
715
  _field_invoke('delete', $obj_type, $object);
  module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_delete', $obj_type, $object);

  // Let other modules act on deleting the object.
  foreach (module_implements('field_attach_delete') as $module) {
    $function = $module . '_field_attach_delete';
    $function($obj_type, $object);
  }

  list($id, $vid, $bundle, $cacheable) = field_attach_extract_ids($obj_type, $object);
  if ($cacheable) {
716
    cache_clear_all("field:$obj_type:$id", 'cache_field');
717
718
719
720
  }
}

/**
721
 * Delete field data for a single revision of an existing object. The
722
723
724
725
726
727
728
 * passed object must have a revision id attribute.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object with fields to save.
 */
729
function field_attach_delete_revision($obj_type, $object) {
730
  _field_invoke('delete_revision', $obj_type, $object);
731
732
733
734
735
736
737
738
739
  module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_delete_revision', $obj_type, $object);

  // Let other modules act on deleting the revision.
  foreach (module_implements('field_attach_delete_revision') as $module) {
    $function = $module . '_field_attach_delete_revision';
    $function($obj_type, $object);
  }
}

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/**
 * Retrieve objects matching a given set of conditions.
 *
 * Note that the query 'conditions' only apply to the stored values.
 * In a regular field_attach_load() call, field values additionally go through
 * hook_field_load() and hook_field_attach_load() invocations, which can add
 * to or affect the raw stored values. The results of field_attach_query()
 * might therefore differ from what could be expected by looking at a regular,
 * fully loaded object.
 *
 * @param $field_name
 *   The name of the field to query.
 * @param $conditions
 *   An array of query conditions. Each condition is a numerically indexed
 *   array, in the form: array(column, value, operator).
 *   Not all storage engines are required to support queries on all column, or
 *   with all operators below. A FieldQueryException will be raised if an
 *   unsupported condition is specified.
 *   Supported columns:
 *     - any of the columns for $field_name's field type: condition on field
 *       value,
 *     - 'type': condition on object type (e.g. 'node', 'user'...),
 *     - 'bundle': condition on object bundle (e.g. node type),
 *     - 'entity_id': condition on object id (e.g node nid, user uid...),
 *     The field_attach_query_revisions() function additionally supports:
 *     - 'revision_id': condition on object revision id (e.g node vid).
 *   Supported operators:
 *     - '=', '!=', '>', '>=', '<', '<=', 'STARTS_WITH', 'ENDS_WITH',
 *       'CONTAINS': these operators expect the value as a literal of the same
 *       type as the column,
770
771
 *     - 'IN', 'NOT IN': this operator expects the value as an array of
 *       literals of the same type as the column.
772
773
774
775
776
777
778
779
780
781
782
783
784
785
 *     - 'BETWEEN': this operator expects the value as an array of two literals
 *       of the same type as the column.
 *     The operator can be ommitted, and will default to 'IN' if the value is
 *     an array, or to '=' otherwise.
 *   Example values for $conditions:
 *   @code
 *   array(
 *     array('type', 'node'),
 *   );
 *   array(
 *     array('bundle', array('article', 'page')),
 *     array('value', 12, '>'),
 *   );
 *   @endcode
786
787
788
789
790
791
792
793
794
795
 * @param $count
 *   The number of results that is requested. This is only a
 *   hint to the storage engine(s); callers should be prepared to
 *   handle fewer or more results. Specify FIELD_QUERY_NO_LIMIT to retrieve
 *   all available objects. This parameter has no default value so
 *   callers must make an explicit choice to potentially retrieve an
 *   enormous result set.
 * @param &$cursor
 *   An opaque cursor that allows a caller to iterate through multiple
 *   result sets. On the first call, pass 0; the correct value to pass
796
797
798
 *   on the next call will be written into $cursor on return. When
 *   there is no more query data available, $cursor will be filled in
 *   with FIELD_QUERY_COMPLETE. If $cursor is passed as NULL,
799
 *   the first result set is returned and no next cursor is returned.
800
801
802
803
804
805
806
807
808
 * @param $age
 *   Internal use only. Use field_attach_query_revisions() instead of passing
 *   FIELD_LOAD_REVISION.
 *   - FIELD_LOAD_CURRENT (default): query the most recent revisions for all
 *     objects. The results will be keyed by object type and object id.
 *   - FIELD_LOAD_REVISION: query all revisions. The results will be keyed by
 *     object type and object revision id.
 * @return
 *   An array keyed by object type (e.g. 'node', 'user'...), then by object id
809
810
811
812
 *   or revision id (depending of the value of the $age parameter).
 *   The values are pseudo-objects with the bundle, id, and revision
 *   id fields filled in.
 *
813
814
815
 *   Throws a FieldQueryException if the field's storage doesn't support the
 *   specified conditions.
 */
816
817
818
819
820
function field_attach_query($field_name, $conditions, $count, &$cursor = NULL, $age = FIELD_LOAD_CURRENT) {
  if (!isset($cursor)) {
    $cursor = 0;
  }

821
822
823
824
825
  // Give a chance to 3rd party modules that bypass the storage engine to
  // handle the query.
  $skip_field = FALSE;
  foreach (module_implements('field_attach_pre_query') as $module) {
    $function = $module . '_field_attach_pre_query';
826
    $results = $function($field_name, $conditions, $count, $cursor, $age, $skip_field);
827
828
829
830
831
832
833
    // Stop as soon as a module claims it handled the query.
    if ($skip_field) {
      break;
    }
  }
  // If the request hasn't been handled, let the storage engine handle it.
  if (!$skip_field) {
834
835
    $function = variable_get('field_storage_module', 'field_sql_storage') . '_field_storage_query';
    $results = $function($field_name, $conditions, $count, $cursor, $age);
836
837
838
839
840
841
842
843
844
845
846
847
848
849
  }

  return $results;
}

/**
 * Retrieve object revisions matching a given set of conditions.
 *
 * See field_attach_query() for more informations.
 *
 * @param $field_name
 *   The name of the field to query.
 * @param $conditions
 *   See field_attach_query().
850
851
852
853
854
855
856
857
858
859
860
 * @param $count
 *   The number of results that is requested. This is only a
 *   hint to the storage engine(s); callers should be prepared to
 *   handle fewer or more results. Specify FIELD_QUERY_NO_LIMIT to retrieve
 *   all available objects. This parameter has no default value so
 *   callers must make an explicit choice to potentially retrieve an
 *   enormous result set.
 * @param &$cursor
 *   An opaque cursor that allows a caller to iterate through multiple
 *   result sets. On the first call, pass 0; the correct value to pass
 *   on the next call will be written into $cursor on return.
861
862
863
 * @return
 *   See field_attach_query().
 */
864
865
function field_attach_query_revisions($field_name, $conditions, $count, &$cursor = NULL) {
  return field_attach_query($field_name, $conditions, $count, $cursor, FIELD_LOAD_REVISION);
866
867
}

868
869
/**
 * Generate and return a structured content array tree suitable for
870
 * drupal_render() for all of the fields on an object. The format of
871
872
873
874
875
876
877
 * each field's rendered content depends on the display formatter and
 * its settings.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object with fields to render.
878
879
 * @param $build_mode
 *   Build mode, e.g. 'full', 'teaser'...
880
881
882
 * @return
 *   A structured content array tree for drupal_render().
 */
883
function field_attach_view($obj_type, $object, $build_mode = 'full') {
884
885
886
  // Let field modules sanitize their data for output.
  _field_invoke('sanitize', $obj_type, $object);

887
  $output = _field_invoke_default('view', $obj_type, $object, $build_mode);
888
889

  // Let other modules make changes after rendering the view.
890
  drupal_alter('field_attach_view', $output, $obj_type, $object, $build_mode);
891
892
893
894
895
896

  return $output;

}

/**
897
 * Implement hook_node_prepare_translation.
898
899
900
 *
 * TODO D7: We do not yet know if this really belongs in Field API.
 */
901
function field_attach_prepare_translation($node) {
902
903
904
905
906
  // Prevent against invalid 'nodes' built by broken 3rd party code.
  if (isset($node->type)) {
    $type = content_types($node->type);
    // Save cycles if the type has no fields.
    if (!empty($type['instances'])) {
907
908
      $default_additions = _field_invoke_default('prepare_translation', $node);
      $additions = _field_invoke('prepare_translation', $node);
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
      // Merge module additions after the default ones to enable overriding
      // of field values.
      $node = (object) array_merge((array) $node, $default_additions, $additions);
    }
  }
}

/**
 * Notify field.module that a new bundle was created.
 *
 * The default SQL-based storage doesn't need to do anytrhing about it, but
 * others might.
 *
 * @param $bundle
 *   The name of the newly created bundle.
 */
925
function field_attach_create_bundle($bundle) {
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
  module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_create_bundle', $bundle);

  // Clear the cache.
  field_cache_clear();

  foreach (module_implements('field_attach_create_bundle') as $module) {
    $function = $module . '_field_attach_create_bundle';
    $function($bundle);
  }
}

/**
 * Notify field.module that a bundle was renamed.
 *
 * @param $bundle_old
 *   The previous name of the bundle.
 * @param $bundle_new
 *   The new name of the bundle.
 */
945
function field_attach_rename_bundle($bundle_old, $bundle_new) {
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
  module_invoke(variable_get('field_storage_module', 'field_sql_storage'), 'field_storage_rename_bundle', $bundle_old, $bundle_new);
  db_update('field_config_instance')
    ->fields(array('bundle' => $bundle_new))
    ->condition('bundle', $bundle_old)
    ->execute();

  // Clear the cache.
  field_cache_clear();

  foreach (module_implements('field_attach_rename_bundle') as $module) {
    $function = $module . '_field_attach_rename_bundle';
    $function($bundle_old, $bundle_new);
  }
}

/**
 * Notify field.module the a bundle was deleted.
 *
 * This deletes the data for the field instances as well as the field instances
965
 * themselves. This function actually just marks the data and field instances
966
967
968
969
970
971
972
973
 * and deleted, leaving the garbage collection for a separate process, because
 * it is not always possible to delete this much data in a single page request
 * (particularly since for some field types, the deletion is more than just a
 * simple DELETE query).
 *
 * @param $bundle
 *   The bundle to delete.
 */
974
function field_attach_delete_bundle($bundle) {
975
976
977
978
979
  // Delete the instances themseves
  $instances = field_info_instances($bundle);
  foreach ($instances as $instance) {
    field_delete_instance($instance['field_name'], $bundle);
  }
980

981
  // Let other modules act on deleting the bundle.
982
983
984
985
  foreach (module_implements('field_attach_delete_bundle') as $module) {
    $function = $module . '_field_attach_delete_bundle';
    $function($bundle, $instances);
  }
986
987
988
989
}

/**
 * Helper function to extract id, vid, and bundle name from an object.
990
 *
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $object
 *   The object from which to extract values.
 * @return
 *   A numerically indexed array (not a hash table) containing these
 *   elements:
 *
 *   0: primary id of the object
 *   1: revision id of the object, or NULL if $obj_type is not versioned
 *   2: bundle name of the object
 *   3: whether $obj_type's fields should be cached (TRUE/FALSE)
 */
1004
function field_attach_extract_ids($obj_type, $object) {
1005
  // TODO D7 : prevent against broken 3rd party $node without 'type'.
1006
  $info = field_info_fieldable_types($obj_type);
1007
  // Objects being created might not have id/vid yet.
1008
1009
  $id = isset($object->{$info['object keys']['id']}) ? $object->{$info['object keys']['id']} : NULL;
  $vid = ($info['object keys']['revision'] && isset($object->{$info['object keys']['revision']})) ? $object->{$info['object keys']['revision']} : NULL;
1010
1011
  // If no bundle key provided, then we assume a single bundle, named after the
  // type of the object.
1012
  $bundle = $info['object keys']['bundle'] ? $object->{$info['object keys']['bundle']} : $obj_type;
1013
  $cacheable = $info['cacheable'];
1014
1015
1016
  return array($id, $vid, $bundle, $cacheable);
}

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
/**
 * Helper function to extract id, vid, and bundle name from an object.
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $bundle
 *   The bundle object (or string if bundles for this object type do not exist
 *   as standalone objects).
 * @return
 *   The bundle name.
 */
function field_attach_extract_bundle($obj_type, $bundle) {
  if (is_string($bundle)) {
    return $bundle;
  }

  $info = field_info_fieldable_types($obj_type);
  if (is_object($bundle) && isset($info['bundle keys']['bundle']) && isset($bundle->{$info['bundle keys']['bundle']})) {
    return $bundle->{$info['bundle keys']['bundle']};
  }
}

1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
/**
 * Helper function to assemble an object structure with initial ids.
 *
 * This function can be seen as reciprocal to field_attach_extract_ids().
 *
 * @param $obj_type
 *   The type of $object; e.g. 'node' or 'user'.
 * @param $ids
 *   A numerically indexed array, as returned by field_attach_extract_ids(),
 *   containing these elements:
 *   0: primary id of the object
 *   1: revision id of the object, or NULL if $obj_type is not versioned
 *   2: bundle name of the object
 * @return
 *   An $object structure, initialized with the ids provided.
 */
function field_attach_create_stub_object($obj_type, $ids) {
  $object = new stdClass();
  $info = field_info_fieldable_types($obj_type);
1058
1059
1060
  $object->{$info['object keys']['id']} = $ids[0];
  if (isset($info['object keys']['revision']) && !is_null($ids[1])) {
    $object->{$info['object keys']['revision']} = $ids[1];
1061
  }
1062
1063
  if ($info['object keys']['bundle']) {
    $object->{$info['object keys']['bundle']} = $ids[2];
1064
1065
1066
1067
  }
  return $object;
}

1068
/**
1069
 * @} End of "defgroup field_attach"
1070
 */