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

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

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
/**
 * @defgroup field_storage Field Storage API
 * @{
 * Implement a storage engine for Field API data.
 *
47 48 49 50 51 52 53
 * The Field Attach API uses the Field Storage API to perform all "database
 * access". Each Field Storage API hook function defines a primitive database
 * operation such as read, write, or delete. The default field storage module,
 * field_sql_storage.module, uses the local SQL database to implement these
 * operations, but alternative field storage backends can choose to represent
 * the data in SQL differently or use a completely different storage mechanism
 * such as a cloud-based database.
54
 *
55 56
 * Each field defines which storage backend it uses. The Drupal system variable
 * 'field_default_storage' identifies the storage backend used by default.
57
 */
58 59

/**
60 61
 * Argument for an update operation.
 *
62
 * This is used in hook_field_storage_write when updating an
63
 * existing entity.
64 65 66 67
 */
define('FIELD_STORAGE_UPDATE', 'update');

/**
68 69
 * Argument for an insert operation.
 *
70
 * This is used in hook_field_storage_write when inserting a new entity.
71 72 73
 */
define('FIELD_STORAGE_INSERT', 'insert');

74 75 76 77 78 79 80
/**
 * @} End of "defgroup field_storage"
 */

/**
 * @defgroup field_attach Field Attach API
 * @{
81
 * Operate on Field API data attached to Drupal entities.
82 83
 *
 * Field Attach API functions load, store, generate Form API
84
 * structures, display, and perform a variety of other functions for
85
 * field data connected to individual entities.
86
 *
87
 * Field Attach API functions generally take $entity_type and $entity
88
 * arguments along with additional function-specific arguments.
89
 * $entity_type is the type of the fieldable entity, such as 'node' or
90 91
 * 'user', and $entity is the entity itself. An individual entity's
 * bundle, if any, is read from the entity's bundle key property
92
 * identified by hook_fieldable_info() for $entity_type.
93 94
 *
 * Fieldable types call Field Attach API functions during their own
95
 * API calls; for example, node_load() calls field_attach_load(). A
96
 * fieldable type is not required to use all of the Field Attach
97 98 99 100
 * API functions.
 *
 * Most Field Attach API functions define a corresponding hook
 * function that allows any module to act on Field Attach operations
101 102
 * for any entity after the operation is complete, and access or
 * modify all the field, form, or display data for that entity and
103
 * operation. For example, field_attach_view() invokes
104
 * hook_field_attach_view_alter(). These all-module hooks are distinct from
105 106 107 108 109
 * 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,
110
 * e.g. hook_field_attach_pre_load(). These hooks run before the
111 112 113
 * 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
114
 * basis. They also allow modules to take over field storage
115 116 117 118 119 120 121 122
 * 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.
123 124 125 126 127 128
 */

/**
 * Invoke a field hook.
 *
 * @param $op
129
 *   Possible operations include:
130 131 132 133 134 135 136 137 138
 *   - form
 *   - validate
 *   - presave
 *   - insert
 *   - update
 *   - delete
 *   - delete revision
 *   - view
 *   - prepare translation
139 140 141
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
142
 *   The fully formed $entity_type entity.
143
 * @param $a
144
 *   - The $form in the 'form' operation.
145
 *   - The value of $view_mode in the 'view' operation.
146
 *   - Otherwise NULL.
147
 * @param $b
148 149
 *   - The $form_state in the 'submit' operation.
 *   - Otherwise NULL.
150 151
 * @param $options
 *   An associative array of additional options, with the following keys:
152 153
 *  - 'field_name': The name of the field whose operation should be
 *    invoked. By default, the operation is invoked on all the fields
154
 *    in the entity's bundle. NOTE: This option is not compatible with
155
 *    the 'deleted' option; the 'field_id' option should be used
156
 *    instead.
157 158
 *  - 'field_id': The id of the field whose operation should be
 *    invoked. By default, the operation is invoked on all the fields
159
 *    in the entity's' bundles.
160 161
 *  - 'default': A boolean value, specifying which implementation of
 *    the operation should be invoked.
162 163 164 165 166 167
 *    - 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.
168 169 170
 *  - 'deleted': If TRUE, the function will operate on deleted fields
 *    as well as non-deleted fields. If unset or FALSE, only
 *    non-deleted fields are operated on.
171 172 173
 *  - 'language': A language code or an array of language codes keyed by field
 *    name. It will be used to narrow down to a single value the available
 *    languages to act on.
174
 */
175
function _field_invoke($op, $entity_type, $entity, &$a = NULL, &$b = NULL, $options = array()) {
176 177 178
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
179
    'deleted' => FALSE,
180
    'language' => NULL,
181 182 183
  );
  $options += $default_options;

184
  // Determine the list of instances to iterate on.
185
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
186
  $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
187

188 189
  // Iterate through the instances and collect results.
  $return = array();
190
  foreach ($instances as $instance) {
191
    $field_name = $instance['field_name'];
192 193 194 195
    $field = field_info_field($field_name);
    $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
    if (function_exists($function)) {
      // Determine the list of languages to iterate on.
196 197
      $available_languages = field_available_languages($entity_type, $field);
      $languages = _field_language_suggestion($available_languages, $options['language'], $field_name);
198

199
      foreach ($languages as $langcode) {
200 201 202 203 204 205 206
        $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
        $result = $function($entity_type, $entity, $field, $instance, $langcode, $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);
207
          }
208 209
          else {
            $return[] = $result;
210 211
          }
        }
212 213 214 215 216 217

        // Populate $items back in the field values, but avoid replacing missing
        // fields with an empty array (those are not equivalent on update).
        if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
          $entity->{$field_name}[$langcode] = $items;
        }
218 219 220 221 222 223 224
      }
    }
  }

  return $return;
}

225
/**
226
 * Invoke a field hook across fields on multiple entities.
227 228 229 230
 *
 * @param $op
 *   Possible operations include:
 *   - load
231
 *   - prepare_view
232 233
 *   For all other operations, use _field_invoke() / field_invoke_default()
 *   instead.
234 235 236
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entities
237
 *   An array of entities, keyed by entity id.
238 239 240 241 242
 * @param $a
 *   - The $age parameter in the 'load' operation.
 *   - Otherwise NULL.
 * @param $b
 *   Currently always NULL.
243 244
 * @param $options
 *   An associative array of additional options, with the following keys:
245 246
 *  - 'field_name': The name of the field whose operation should be
 *    invoked. By default, the operation is invoked on all the fields
247
 *    in the entity's bundle. NOTE: This option is not compatible with
248 249 250
 *    the 'deleted' option; the 'field_id' option should be used instead.
 *  - 'field_id': The id of the field whose operation should be
 *    invoked. By default, the operation is invoked on all the fields
251
 *    in the entity's' bundles.
252 253
 *  - 'default': A boolean value, specifying which implementation of
 *    the operation should be invoked.
254 255 256 257 258 259
 *    - 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.
260 261 262
 *  - 'deleted': If TRUE, the function will operate on deleted fields
 *    as well as non-deleted fields. If unset or FALSE, only
 *    non-deleted fields are operated on.
263 264 265 266
 *  - 'language': A language code or an array of language codes keyed by field
 *    name. It will be used to narrow down to a single value the available
 *    languages to act on.
 *
267
 * @return
268
 *   An array of returned values keyed by entity id.
269
 */
270
function _field_invoke_multiple($op, $entity_type, $entities, &$a = NULL, &$b = NULL, $options = array()) {
271 272 273
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
274
    'deleted' => FALSE,
275
    'language' => NULL,
276 277 278
  );
  $options += $default_options;

279 280
  $fields = array();
  $grouped_instances = array();
281
  $grouped_entities = array();
282 283 284
  $grouped_items = array();
  $return = array();

285
  // Go through the entities 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, entities can only
290 291
  // contain data for a single field for each name, even if that field
  // is deleted, so we reference field data via the
292 293
  // $entity->$field_name property.
  foreach ($entities as $entity) {
294
    // Determine the list of instances to iterate on.
295
    list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
296
    $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
297 298 299

    foreach ($instances as $instance) {
      $field_id = $instance['field_id'];
300
      $field_name = $instance['field_name'];
301 302 303
      $field = field_info_field_by_id($field_id);
      $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
      if (function_exists($function)) {
304
        // Add the field to the list of fields to invoke the hook on.
305
        if (!isset($fields[$field_id])) {
306
          $fields[$field_id] = $field;
307
        }
308
        // Group the corresponding instances and entities.
309
        $grouped_instances[$field_id][$id] = $instance;
310
        $grouped_entities[$field_id][$id] = $entities[$id];
311 312
        // Extract the field values into a separate variable, easily accessed
        // by hook implementations.
313 314
        // Unless a language suggestion is provided we iterate on all the
        // available languages.
315
        $available_languages = field_available_languages($entity_type, $field);
316 317
        $languages = _field_language_suggestion($available_languages, $options['language'], $field_name);
        foreach ($languages as $langcode) {
318
          $grouped_items[$field_id][$langcode][$id] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
319
        }
320 321
      }
    }
322
    // Initialize the return value for each entity.
323 324 325
    $return[$id] = array();
  }

326
  // For each field, invoke the field hook and collect results.
327 328
  foreach ($fields as $field_id => $field) {
    $field_name = $field['field_name'];
329
    $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
330 331 332 333 334 335 336 337 338 339 340 341 342
    // Iterate over all the field translations.
    foreach ($grouped_items[$field_id] as $langcode => $items) {
      $results = $function($entity_type, $grouped_entities[$field_id], $field, $grouped_instances[$field_id], $langcode, $grouped_items[$field_id][$langcode], $a, $b);
      if (isset($results)) {
        // Collect results by entity.
        // 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;
343 344 345 346 347
          }
        }
      }
    }

348
    // Populate field values back in the entities, but avoid replacing missing
349
    // fields with an empty array (those are not equivalent on update).
350
    foreach ($grouped_entities[$field_id] as $id => $entity) {
351
      foreach ($grouped_items[$field_id] as $langcode => $items) {
352 353
        if ($grouped_items[$field_id][$langcode][$id] !== array() || isset($entity->{$field_name}[$langcode])) {
          $entity->{$field_name}[$langcode] = $grouped_items[$field_id][$langcode][$id];
354
        }
355 356 357 358 359 360 361
      }
    }
  }

  return $return;
}

362 363
/**
 * Invoke field.module's version of a field hook.
364 365 366 367 368
 *
 * This function invokes the field_default_[op]() function.
 * Use _field_invoke() to invoke the field type implementation,
 * hook_field_[op]().
 *
369
 * @see _field_invoke()
370
 */
371
function _field_invoke_default($op, $entity_type, $entity, &$a = NULL, &$b = NULL, $options = array()) {
372
  $options['default'] = TRUE;
373
  return _field_invoke($op, $entity_type, $entity, $a, $b, $options);
374 375
}

376
/**
377
 * Invoke field.module's version of a field hook on multiple entities.
378 379 380 381 382
 *
 * This function invokes the field_default_[op]() function.
 * Use _field_invoke_multiple() to invoke the field type implementation,
 * hook_field_[op]().
 *
383
 * @see _field_invoke_multiple()
384
 */
385
function _field_invoke_multiple_default($op, $entity_type, $entities, &$a = NULL, &$b = NULL, $options = array()) {
386
  $options['default'] = TRUE;
387
  return _field_invoke_multiple($op, $entity_type, $entities, $a, $b, $options);
388 389
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/**
 * Helper for _field_invoke(): retrieves a list of instances to operate on.
 *
 * @param $entity_type
 *   The entity type.
 * @param $bundle
 *   The bundle name.
 * @param $options
 *   An associative array of options, as provided to _field_invoke(). Only the
 *   following keys are considered :
 *   - deleted
 *   - field_name
 *   - field_id
 *   See _field_invoke() for details.
 *
 * @return
 *   The array of selected instance definitions.
 */
function _field_invoke_get_instances($entity_type, $bundle, $options) {
  if ($options['deleted']) {
    // Deleted fields are not included in field_info_instances(), and need to
    // be fetched from the database with field_read_instances().
    $params = array('entity_type' => $entity_type, 'bundle' => $bundle);
    if (isset($options['field_id'])) {
      // Single-field mode by field id: field_read_instances() does the filtering.
      // Single-field mode by field name is not compatible with the 'deleted'
      // option.
      $params['field_id'] = $options['field_id'];
    }
    $instances = field_read_instances($params, array('include_deleted' => TRUE));
  }
  elseif (isset($options['field_name'])) {
    // Single-field mode by field name: field_info_instance() does the
    // filtering.
    $instances = array(field_info_instance($entity_type, $options['field_name'], $bundle));
  }
  else {
    $instances = field_info_instances($entity_type, $bundle);
    if (isset($options['field_id'])) {
      // Single-field mode by field id: we need to loop on each instance to
      // find the right one.
      foreach ($instances as $instance) {
        if ($instance['field_id'] == $options['field_id']) {
          $instances = array($instance);
          break;
        }
      }
    }
  }

  return $instances;
}

443
/**
444
 * Add form elements for all fields for an entity to a form structure.
445
 *
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
 * Sample structure for $form:
 * @code
 *   // One sub-array per field appearing in the form, keyed by field name.
 *   // The structure of the array differs slightly depending on whether the
 *   // widget is 'single-value' (provides the input for one field value,
 *   // most common case), and will therefore be repeated as many times as
 *   // needed, or 'multiple-values' (one single widget allows the input of
 *   // several values, e.g checkboxes, select box...).
 *   // The sub-array is nested into a $langcode key where $langcode has the
 *   // same value of the $langcode parameter above.
 *   // The '#language' key holds the same value of $langcode and it is used
 *   // to access the field sub-array when $langcode is unknown.
 *   'field_foo' => array(
 *     '#tree' => TRUE,
 *     '#field_name' => the name of the field,
 *     '#language' => $langcode,
 *     $langcode => array(
 *       '#field_name' => the name of the field,
 *       '#tree' => TRUE,
 *       '#required' => whether or not the field is required,
 *       '#title' => the label of the field instance,
 *       '#description' => the description text for the field instance,
 *
 *       // Only for 'single' widgets:
 *       '#theme' => 'field_multiple_value_form',
 *       '#cardinality' => the field cardinality,
 *       // One sub-array per copy of the widget, keyed by delta.
 *       0 => array(
 *         '#title' => the title to be displayed by the widget,
 *         '#default_value' => the field value for delta 0,
 *         '#required' => whether the widget should be marked required,
 *         '#delta' => 0,
 *         '#field_name' => the name of the field,
 *         '#bundle' => the name of the bundle,
 *         '#columns' => the array of field columns,
 *         // The remaining elements in the sub-array depend on the widget.
 *         '#type' => the type of the widget,
 *         ...
 *       ),
 *       1 => array(
 *         ...
 *       ),
 *
 *       // Only for multiple widgets:
 *       '#bundle' => $instance['bundle'],
 *       '#columns'  => array_keys($field['columns']),
 *       // The remaining elements in the sub-array depend on the widget.
 *       '#type' => the type of the widget,
 *       ...
 *     ),
 *     ...
 *   ),
 * )
 * @endcode
 *
 * Sample structure for $form_state['field']:
 * @code
 * array(
 *   // One sub-array per field appearing in the form, keyed by field name.
 *   'field_foo' => array(
 *     $langcode => array(
 *       'field' => the field definition array,
 *       'instance' => the field instance definition array,
 *       'array_parents' => an array of keys indicating the path to the field
 *         element within the full $form structure. This entry is populated at
 *         form build time.
 *       'errors' => the array ok field validation errors reported on the
 *         field. This entry is populated at form validation time.
 *     ),
 *   ),
 * ),
 * @endcode
 *
519 520 521
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
522
 *   The entity for which to load form elements, used to initialize
523 524 525 526 527
 *   default form values.
 * @param $form
 *   The form structure to fill in.
 * @param $form_state
 *   An associative array containing the current state of the form.
528 529 530
 * @param $langcode
 *   The language the field values are going to be entered, if no language
 *   is provided the default site language will be used.
531 532
 * @return
 *   The form elements are added by reference at the top level of the $form
533 534
 *   parameter. Processing information is added by reference in
 *   $form_state['field'].
535
 */
536
function field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode = NULL) {
537
  // If no language is provided use the default site language.
538
  $options = array('language' => field_valid_language($langcode));
539
  $form += (array) _field_invoke_default('form', $entity_type, $entity, $form, $form_state, $options);
540

541
  // Add custom weight handling.
542
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
543
  $form['#attached']['css'][] = drupal_get_path('module', 'field') . '/theme/field.css';
544
  $form['#pre_render'][] = '_field_extra_weights_pre_render';
545
  $form['#extra_fields'] = field_extra_fields($entity_type, $bundle);
546

547
  // Let other modules make changes to the form.
548
  // Avoid module_invoke_all() to let parameters be taken by reference.
549 550
  foreach (module_implements('field_attach_form') as $module) {
    $function = $module . '_field_attach_form';
551
    $function($entity_type, $entity, $form, $form_state, $langcode);
552 553 554 555 556
  }
}

/**
 * Load all fields for the most current version of each of a set of
557
 * entities of a single entity type.
558
 *
559 560 561
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entities
562 563
 *   An array of entities for which to load fields, keyed by entity id.
 *   Each entity needs to have its 'bundle', 'id' and (if applicable)
564
 *   'revision' keys filled.
565 566 567
 * @param $age
 *   FIELD_LOAD_CURRENT to load the most recent revision for all
 *   fields, or FIELD_LOAD_REVISION to load the version indicated by
568
 *   each entity. Defaults to FIELD_LOAD_CURRENT; use
569
 *   field_attach_load_revision() instead of passing FIELD_LOAD_REVISION.
570 571
 * @param $options
 *   An associative array of additional options, with the following keys:
572
 *  - 'field_id': The field id that should be loaded, instead of
573
 *    loading all fields, for each entity. Note that returned entities
574
 *    may contain data for other fields, for example if they are read
575
 *    from a cache.
576 577
 *  - 'deleted': If TRUE, the function will operate on deleted fields
 *    as well as non-deleted fields. If unset or FALSE, only
578
 *    non-deleted fields are operated on.
579
 * @return
580
 *   Loaded field values are added to $entities.
581
 */
582
function field_attach_load($entity_type, $entities, $age = FIELD_LOAD_CURRENT, $options = array()) {
583
  $load_current = $age == FIELD_LOAD_CURRENT;
584

585 586 587 588 589 590
  // Merge default options.
  $default_options = array(
    'deleted' => FALSE,
  );
  $options += $default_options;

591
  $info = entity_get_info($entity_type);
592 593 594
  // Only the most current revision of non-deleted fields for cacheable entity
  // types can be cached.
  $cache_read = $load_current && $info['field cache'] && empty($options['deleted']);
595
  // In addition, do not write to the cache when loading a single field.
596
  $cache_write = $cache_read && !isset($options['field_id']);
597

598
  if (empty($entities)) {
599 600 601
    return;
  }

602
  // Assume all entities will need to be queried. Entities found in the cache
603
  // will be removed from the list.
604
  $queried_entities = $entities;
605

606
  // Fetch available entities from cache, if applicable.
607
  if ($cache_read) {
608 609
    // Build the list of cache entries to retrieve.
    $cids = array();
610 611
    foreach ($entities as $id => $entity) {
      $cids[] = "field:$entity_type:$id";
612 613
    }
    $cache = cache_get_multiple($cids, 'cache_field');
614 615
    // Put the cached field values back into the entities and remove them from
    // the list of entities to query.
616 617
    foreach ($entities as $id => $entity) {
      $cid = "field:$entity_type:$id";
618
      if (isset($cache[$cid])) {
619
        unset($queried_entities[$id]);
620
        foreach ($cache[$cid]->data as $field_name => $values) {
621
          $entity->$field_name = $values;
622 623
        }
      }
624
    }
625 626
  }

627 628
  // Fetch other entities from their storage location.
  if ($queried_entities) {
629
    // The invoke order is:
630
    // - hook_field_storage_pre_load()
631
    // - storage backend's hook_field_storage_load()
632
    // - field-type module's hook_field_load()
633 634
    // - hook_field_attach_load()

635
    // Invoke hook_field_storage_pre_load(): let any module load field
636 637
    // data before the storage engine, accumulating along the way.
    $skip_fields = array();
638 639
    foreach (module_implements('field_storage_pre_load') as $module) {
      $function = $module . '_field_storage_pre_load';
640
      $function($entity_type, $queried_entities, $age, $skip_fields, $options);
641 642
    }

643 644
    $instances = array();

645
    // Collect the storage backends used by the remaining fields in the entities.
646
    $storages = array();
647 648
    foreach ($queried_entities as $entity) {
      list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
649
      $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
650 651

      foreach ($instances as $instance) {
652 653 654 655 656 657 658 659 660 661
        $field_name = $instance['field_name'];
        $field_id = $instance['field_id'];
        // Make sure all fields are present at least as empty arrays.
        if (!isset($queried_entities[$id]->{$field_name})) {
          $queried_entities[$id]->{$field_name} = array();
        }
        // Collect the storage backend if the field has not been loaded yet.
        if (!isset($skip_fields[$field_id])) {
          $field = field_info_field_by_id($field_id);
          $storages[$field['storage']['type']][$field_id][] = $load_current ? $id : $vid;
662 663 664 665 666 667 668
        }
      }
    }

    // Invoke hook_field_storage_load() on the relevant storage backends.
    foreach ($storages as $storage => $fields) {
      $storage_info = field_info_storage_types($storage);
669
      module_invoke($storage_info['module'], 'field_storage_load', $entity_type, $queried_entities, $age, $fields, $options);
670
    }
671

672
    // Invoke field-type module's hook_field_load().
673
    _field_invoke_multiple('load', $entity_type, $queried_entities, $age, $options);
674 675

    // Invoke hook_field_attach_load(): let other modules act on loading the
676 677
    // entitiy.
    module_invoke_all('field_attach_load', $entity_type, $queried_entities, $age, $options);
678

679
    // Build cache data.
680
    if ($cache_write) {
681
      foreach ($queried_entities as $id => $entity) {
682
        $data = array();
683 684
        list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
        $instances = field_info_instances($entity_type, $bundle);
685
        foreach ($instances as $instance) {
686
          $data[$instance['field_name']] = $queried_entities[$id]->{$instance['field_name']};
687
        }
688
        $cid = "field:$entity_type:$id";
689 690 691 692 693 694 695 696
        cache_set($cid, $data, 'cache_field');
      }
    }
  }
}

/**
 * Load all fields for a previous version of each of a set of
697
 * entities of a single entity type.
698
 *
699
 * Loading different versions of the same entities is not supported,
700 701
 * and should be done by separate calls to the function.
 *
702 703 704
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entities
705 706
 *   An array of entities for which to load fields, keyed by entity id.
 *   Each entity needs to have its 'bundle', 'id' and (if applicable)
707
 *   'revision' keys filled.
708 709
 * @param $options
 *   An associative array of additional options, with the following keys:
710
 *   - 'field_name':  The field name that should be loaded, instead of
711
 *     loading all fields, for each entity. Note that returned entities
712
 *     may contain data for other fields, for example if they are read
713
 *     from a cache.
714
 * @return
715
 *   On return, the entities in $entities are modified by having the
716 717
 *   appropriate set of fields added.
 */
718 719
function field_attach_load_revision($entity_type, $entities, $options = array()) {
  return field_attach_load($entity_type, $entities, FIELD_LOAD_REVISION, $options);
720 721 722
}

/**
723
 * Perform field validation against the field data in an entity.
724
 *
725 726 727 728
 * 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.
729
 *
730 731 732
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
733
 *   The entity with fields to validate.
734 735 736 737
 * @throws FieldValidationException
 *   If validation errors are found, a FieldValidationException is thrown. The
 *   'errors' property contains the array of errors, keyed by field name,
 *   language and delta.
738
 */
739
function field_attach_validate($entity_type, $entity) {
740
  $errors = array();
741
  // Check generic, field-type-agnostic errors first.
742
  _field_invoke_default('validate', $entity_type, $entity, $errors);
743
  // Check field-type specific errors.
744
  _field_invoke('validate', $entity_type, $entity, $errors);
745

746
  // Let other modules validate the entity.
747
  // Avoid module_invoke_all() to let $errors be taken by reference.
748 749
  foreach (module_implements('field_attach_validate') as $module) {
    $function = $module . '_field_attach_validate';
750
    $function($entity_type, $entity, $errors);
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  }

  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
772
 * on the correct form elements. Fieldable entity types should call
773 774
 * this function during their own form validation function.
 *
775 776 777
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
778
 *   The entity being submitted. The 'bundle', 'id' and (if applicable)
779
 *   'revision' keys should be present. The actual field values will be read
780 781 782 783 784 785
 *   from $form_state['values'].
 * @param $form
 *   The form structure.
 * @param $form_state
 *   An associative array containing the current state of the form.
 */
786
function field_attach_form_validate($entity_type, $entity, $form, &$form_state) {
787
  // Extract field values from submitted values.
788
  _field_invoke_default('extract_form_values', $entity_type, $entity, $form, $form_state);
789 790 791

  // Perform field_level validation.
  try {
792
    field_attach_validate($entity_type, $entity);
793 794 795 796
  }
  catch (FieldValidationException $e) {
    // Pass field-level validation errors back to widgets for accurate error
    // flagging.
797 798 799 800 801
    foreach ($e->errors as $field_name => $field_errors) {
      foreach ($field_errors as $langcode => $language_errors) {
        $form_state['field'][$field_name][$langcode]['errors'] = $language_errors;
      }
    }
802
    _field_invoke_default('form_errors', $entity_type, $entity, $form, $form_state);
803 804 805 806 807 808 809 810 811
  }
}

/**
 * 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.
 *
812 813 814
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
815
 *   The entity being submitted. The 'bundle', 'id' and (if applicable)
816
 *   'revision' keys should be present. The actual field values will be read
817 818 819 820 821 822
 *   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.
 */
823
function field_attach_submit($entity_type, $entity, $form, &$form_state) {
824
  // Extract field values from submitted values.
825
  _field_invoke_default('extract_form_values', $entity_type, $entity, $form, $form_state);
826

827
  _field_invoke_default('submit', $entity_type, $entity, $form, $form_state);
828

829
  // Let other modules act on submitting the entity.
830
  // Avoid module_invoke_all() to let $form_state be taken by reference.
831 832
  foreach (module_implements('field_attach_submit') as $module) {
    $function = $module . '_field_attach_submit';
833
    $function($entity_type, $entity, $form, $form_state);
834 835 836 837 838 839 840 841 842
  }
}

/**
 * Perform necessary operations just before fields data get saved.
 *
 * We take no specific action here, we just give other
 * modules the opportunity to act.
 *
843 844 845
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
846
 *   The entity with fields to process.
847
 */
848 849
function field_attach_presave($entity_type, $entity) {
  _field_invoke('presave', $entity_type, $entity);
850

851
  // Let other modules act on presaving the entity.
852
  module_invoke_all('field_attach_presave', $entity_type, $entity);
853 854 855
}

/**
856
 * Save field data for a new entity.
857
 *
858
 * The passed in entity must already contain its id and (if applicable)
859 860
 * revision id attributes.
 * Default values (if any) will be saved for fields not present in the
861
 * $entity.
862
 *
863 864 865
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
866
 *   The entity with fields to save.
867
 * @return
868
 *   Default values (if any) will be added to the $entity parameter for fields
869
 *   it leaves unspecified.
870
 */
871 872 873
function field_attach_insert($entity_type, $entity) {
  _field_invoke_default('insert', $entity_type, $entity);
  _field_invoke('insert', $entity_type, $entity);
874

875
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
876

877 878
  // Let any module insert field data before the storage engine, accumulating
  // saved fields along the way.
879
  $skip_fields = array();
880 881
  foreach (module_implements('field_storage_pre_insert') as $module) {
    $function = $module . '_field_storage_pre_insert';
882
    $function($entity_type, $entity, $skip_fields);
883 884
  }

885
  // Collect the storage backends used by the remaining fields in the entities.
886
  $storages = array();
887
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
888 889 890
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['id'];
    $field_name = $field['field_name'];
891
    if (!empty($entity->$field_name)) {
892 893 894 895 896 897 898 899 900 901
      // Collect the storage backend if the field has not been written yet.
      if (!isset($skip_fields[$field_id])) {
        $storages[$field['storage']['type']][$field_id] = $field_id;
      }
    }
  }

  // Field storage backends save any remaining unsaved fields.
  foreach ($storages as $storage => $fields) {
    $storage_info = field_info_storage_types($storage);
902
    module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $entity, FIELD_STORAGE_INSERT, $fields);
903
  }
904

905
  // Let other modules act on inserting the entity.
906
  module_invoke_all('field_attach_insert', $entity_type, $entity);
907

908
  $entity_info = entity_get_info($entity_type);
909 910 911
}

/**
912
 * Save field data for an existing entity.
913
 *
914 915 916
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
917
 *   The entity with fields to save.
918
 */
919 920
function field_attach_update($entity_type, $entity) {
  _field_invoke('update', $entity_type, $entity);
921

922
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
923

924 925
  // Let any module update field data before the storage engine, accumulating
  // saved fields along the way.
926
  $skip_fields = array();
927 928
  foreach (module_implements('field_storage_pre_update') as $module) {
    $function = $module . '_field_storage_pre_update';
929
    $function($entity_type, $entity, $skip_fields);
930 931
  }

932
  // Collect the storage backends used by the remaining fields in the entities.
933
  $storages = array();
934
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
935 936 937
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['id'];
    $field_name = $field['field_name'];
938
    // Leave the field untouched if $entity comes with no $field_name property,
939 940 941
    // but empty the field if it comes as a NULL value or an empty array.
    // Function property_exists() is slower, so we catch the more frequent
    // cases where it's an empty array with the faster isset().
942
    if (isset($entity->$field_name) || property_exists($entity, $field_name)) {
943 944 945 946 947 948 949 950 951 952
      // Collect the storage backend if the field has not been written yet.
      if (!isset($skip_fields[$field_id])) {
        $storages[$field['storage']['type']][$field_id] = $field_id;
      }
    }
  }

  // Field storage backends save any remaining unsaved fields.
  foreach ($storages as $storage => $fields) {
    $storage_info = field_info_storage_types($storage);
953
    module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $entity, FIELD_STORAGE_UPDATE, $fields);
954
  }
955

956
  // Let other modules act on updating the entity.
957
  module_invoke_all('field_attach_update', $entity_type, $entity);
958

959 960
  $entity_info = entity_get_info($entity_type);
  if ($entity_info['field cache']) {
961
    cache_clear_all("field:$entity_type:$id", 'cache_field');
962 963 964 965
  }
}

/**
966 967
 * Delete field data for an existing entity. This deletes all
 * revisions of field data for the entity.
968
 *
969 970 971
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
972
 *   The entity whose field data to delete.
973
 */
974 975
function field_attach_delete($entity_type, $entity) {
  _field_invoke('delete', $entity_type, $entity);
976

977
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
978

979
  // Collect the storage backends used by the fields in the entities.
980
  $storages = array();
981
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
982 983 984 985 986 987 988 989
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['id'];
    $storages[$field['storage']['type']][$field_id] = $field_id;
  }

  // Field storage backends delete their data.
  foreach ($storages as $storage => $fields) {
    $storage_info = field_info_storage_types($storage);
990
    module_invoke($storage_info['module'], 'field_storage_delete', $entity_type, $entity, $fields);
991
  }
992

993
  // Let other modules act on deleting the entity.
994
  module_invoke_all('field_attach_delete', $entity_type, $entity);
995

996 997
  $entity_info = entity_get_info($entity_type);
  if ($entity_info['field cache']) {
998
    cache_clear_all("field:$entity_type:$id", 'cache_field');
999 1000 1001 1002
  }
}

/**
1003 1004
 * Delete field data for a single revision of an existing entity. The
 * passed entity must have a revision id attribute.
1005
 *
1006 1007 1008
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param $entity
1009
 *   The entity with fields to save.
1010
 */
1011 1012
function field_attach_delete_revision($entity_type, $entity) {
  _field_invoke('delete_revision', $entity_type, $entity);
1013

1014
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
1015

1016
  // Collect the storage backends used by the fields in the entities.
1017
  $storages = array();
1018
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
1019 1020 1021 1022 1023 1024 1025 1026
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['id'];
    $storages[$field['storage']['type']][$field_id] = $field_id;
  }

  // Field storage backends delete their data.
  foreach ($storages as $storage => $fields) {
    $storage_info = field_info_storage_types($storage);
1027
    module_invoke($storage_info['module'], 'field_storage_delete_revision', $entity_type, $entity, $fields);
1028
  }
1029 1030

  // Let other modules act on deleting the revision.
1031
  module_invoke_all('field_attach_delete_revision', $entity_type, $entity);
1032 1033
}

1034
/**
1035
 * Retrieve entities matching a given set of conditions.
1036 1037 1038 1039 1040 1041
 *
 * 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,