Projet

Général

Profil

Paste
Télécharger (19,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date.field.inc @ 1f142f4f

1
<?php
2

    
3
/**
4
 * @file
5
 * Field hooks to implement a date field.
6
 */
7

    
8
/**
9
 * Implements hook_field_formatter_info().
10
 */
11
function date_field_formatter_info() {
12
  $formatters = array(
13
    'date_default' => array(
14
      'label' => t('Date and time'),
15
      'field types' => array('date', 'datestamp', 'datetime'),
16
      'settings' => array(
17
        'format_type' => 'long',
18
        'multiple_number' => '',
19
        'multiple_from' => '',
20
        'multiple_to' => '',
21
        'fromto' => 'both',
22
        'show_remaining_days' => FALSE,
23
      ),
24
    ),
25
    'format_interval' => array(
26
      'label' => t('Time ago'),
27
      'field types' => array('date', 'datestamp', 'datetime'),
28
      'settings' => array(
29
        'interval' => 2,
30
        'interval_display' => 'time ago',
31
      ),
32
    ),
33
    'date_plain' => array(
34
      'label' => t('Plain'),
35
      'field types' => array('date', 'datestamp', 'datetime'),
36
    ),
37
  );
38
  return $formatters;
39
}
40

    
41
/**
42
 * Implements hook_field_formatter_settings_form().
43
 */
44
function date_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
45
  $display = $instance['display'][$view_mode];
46
  $formatter = $display['type'];
47
  module_load_include('inc', 'date', 'date_admin');
48
  switch ($formatter) {
49
    case 'format_interval':
50
      $form = date_interval_formatter_settings_form($field, $instance, $view_mode, $form, $form_state);
51
      break;
52

    
53
    default:
54
      $form = date_default_formatter_settings_form($field, $instance, $view_mode, $form, $form_state);
55
      break;
56
  }
57
  $context = array(
58
    'field' => $field,
59
    'instance' => $instance,
60
    'view_mode' => $view_mode,
61
  );
62
  drupal_alter('date_field_formatter_settings_form', $form, $form_state, $context);
63
  return $form;
64
}
65

    
66
/**
67
 * Implements hook_field_formatter_settings_summary().
68
 */
69
function date_field_formatter_settings_summary($field, $instance, $view_mode) {
70
  $display = $instance['display'][$view_mode];
71
  $formatter = $display['type'];
72
  module_load_include('inc', 'date', 'date_admin');
73
  switch ($formatter) {
74
    case 'format_interval':
75
      $summary = date_interval_formatter_settings_summary($field, $instance, $view_mode);
76
      break;
77

    
78
    default:
79
      $summary = date_default_formatter_settings_summary($field, $instance, $view_mode);
80
      break;
81
  }
82
  $context = array(
83
    'field' => $field,
84
    'instance' => $instance,
85
    'view_mode' => $view_mode,
86
  );
87
  drupal_alter('date_field_formatter_settings_summary', $summary, $context);
88

    
89
  return implode('<br />', $summary);
90
}
91

    
92
/**
93
 * Implements hook_field_formatter_view().
94
 *
95
 * Useful values:
96
 *
97
 *   $entity->date_id
98
 *     If set, this will show only an individual date on a field with
99
 *     multiple dates. The value should be a string that contains
100
 *     the following values, separated with periods:
101
 *     - module name of the module adding the item
102
 *     - node nid
103
 *     - field name
104
 *     - delta value of the field to be displayed
105
 *     - other information the module's custom theme might need
106
 *
107
 *     Used by the calendar module and available for other uses.
108
 *     example: 'date:217:field_date:3:test'
109
 *
110
 *   $entity->date_repeat_show
111
 *     If true, tells the theme to show all the computed values
112
 *     of a repeating date. If not true or not set, only the
113
 *     start date and the repeat rule will be displayed.
114
 */
115
function date_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
116
  $element = array();
117
  $settings = $display['settings'];
118
  $formatter = $display['type'];
119
  $variables = array(
120
    'entity' => $entity,
121
    'entity_type' => $entity_type,
122
    'field' => $field,
123
    'instance' => $instance,
124
    'langcode' => $langcode,
125
    'items' => $items,
126
    'display' => $display,
127
    'dates' => array(),
128
    'attributes' => array(),
129
    'rdf_mapping' => array(),
130
    'add_rdf' => module_exists('rdf'),
131
    'microdata' => array(),
132
    'add_microdata' => module_exists('microdata'),
133
  );
134

    
135
  // If the microdata module is enabled, the microdata mapping will have been
136
  // passed in via the entity.
137
  if ($variables['add_microdata'] && isset($entity->microdata[$field['field_name']])) {
138
    $variables['microdata'] = $entity->microdata[$field['field_name']];
139
  }
140

    
141
  // If there is an RDf mapping for this date field, pass it down to the theme.
142
  $rdf_mapping = array();
143
  if (!empty($entity->rdf_mapping) && function_exists('rdf_rdfa_attributes')) {
144
    if (!empty($entity->rdf_mapping[$field['field_name']])) {
145
      $variables['rdf_mapping'] = $rdf_mapping = $entity->rdf_mapping[$field['field_name']];
146
    }
147
  }
148

    
149
  // Give other modules a chance to prepare the entity before formatting it.
150
  drupal_alter('date_formatter_pre_view', $entity, $variables);
151

    
152
  // See if we are only supposed to display a selected
153
  // item from multiple value date fields.
154
  $selected_deltas = array();
155
  if (!empty($entity->date_id)) {
156
    foreach ((array) $entity->date_id as $key => $id) {
157
      list($module, $nid, $field_name, $selected_delta, $other) = explode('.', $id . '.');
158
      if ($field_name == $field['field_name']) {
159
        $selected_deltas[] = $selected_delta;
160
      }
161
    }
162
  }
163

    
164
  switch ($display['type']) {
165
    case 'date_plain':
166
      foreach ($items as $delta => $item) {
167
        if (!empty($entity->date_id) && !in_array($delta, $selected_deltas)) {
168
          continue;
169
        }
170
        else {
171
          if (empty($item['value2']) || $item['value'] == $item['value2']) {
172
            $element[$delta] = array('#markup' => $item['value']);
173
          }
174
          else {
175
            $element[$delta] = array(
176
              '#markup' => t('!start-date to !end-date', array(
177
                '!start-date' => $item['value'],
178
                '!end-date' => $item['value2']
179
              )));
180
          }
181
        }
182
      }
183
      break;
184

    
185
    case 'format_interval':
186
      foreach ($items as $delta => $item) {
187
        if (!empty($entity->date_id) && !in_array($delta, $selected_deltas)) {
188
          continue;
189
        }
190
        else {
191
          $variables['delta'] = $delta;
192
          $variables['item'] = $item;
193
          $variables['dates'] = date_formatter_process($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display);
194
          $variables['attributes'] = !empty($rdf_mapping) ? rdf_rdfa_attributes($rdf_mapping, $item['value']) : array();
195
          $element[$delta] = array('#markup' => theme('date_display_interval', $variables));
196
        }
197
      }
198
      break;
199

    
200
    default:
201
      foreach ($items as $delta => $item) {
202
        if (!empty($entity->date_id) && !in_array($delta, $selected_deltas)) {
203
          continue;
204
        }
205
        else {
206
          $variables['delta'] = $delta;
207
          $variables['item'] = $item;
208
          $variables['dates'] = date_formatter_process($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display);
209
          $variables['attributes'] = !empty($rdf_mapping) ? rdf_rdfa_attributes($rdf_mapping, $item['value']) : array();
210
          $variables['show_remaining_days'] = $display['settings']['show_remaining_days'];
211
          $output = theme('date_display_combination', $variables);
212
          if (!empty($output)) {
213
            $element[$delta] = array('#markup' => $output);
214
          }
215
        }
216
      }
217
      break;
218
  }
219
  return $element;
220
}
221

    
222
/**
223
 * Implements hook_field_is_empty().
224
 */
225
function date_field_is_empty($item, $field) {
226
  // Sometimes a $item is a date object.
227
  // Coming from repeating dates. Why??
228
  if (!is_array($item)) {
229
    return FALSE;
230
  }
231
  if (empty($item['value'])) {
232
    return TRUE;
233
  }
234
  elseif ($field['settings']['todate'] == 'required' && empty($item['value2'])) {
235
    return TRUE;
236
  }
237
  return FALSE;
238
}
239

    
240
/**
241
 * Implements hook_field_info().
242
 */
243
function date_field_info() {
244
  $granularity = array('year', 'month', 'day', 'hour', 'minute');
245
  $settings = array(
246
    'settings' => array(
247
      'todate' => '',
248
      'granularity' => drupal_map_assoc($granularity),
249
      'tz_handling' => 'site',
250
      'timezone_db' => 'UTC',
251
    ),
252
    'instance_settings' => array(
253
      'default_value' => 'now',
254
      'default_value_code' => '',
255
      'default_value2' => 'same',
256
      'default_value_code2' => '',
257
    ),
258
    // Integrate with the Entity Metadata module.
259
    'property_type' => 'date',
260
    'property_callbacks' => array('date_entity_metadata_property_info_alter'),
261
  );
262
  return array(
263
    'datetime' => array(
264
      'label' => t('Date'),
265
      'description' => t('Store a date in the database as a datetime field, recommended for complete dates and times that may need timezone conversion.'),
266
      'default_widget' => 'date_select',
267
      'default_formatter' => 'date_default',
268
      'default_token_formatter' => 'date_plain',
269
    ) + $settings,
270
    'date' => array(
271
      'label' => t('Date (ISO format)'),
272
      'description' => t('Store a date in the database as an ISO date, recommended for historical or partial dates.'),
273
      'default_widget' => 'date_select',
274
      'default_formatter' => 'date_default',
275
      'default_token_formatter' => 'date_plain',
276
    ) + $settings,
277
    'datestamp' => array(
278
      'label' => t('Date (Unix timestamp)'),
279
      'description' => t('Store a date in the database as a timestamp, deprecated format to support legacy data.'),
280
      'default_widget' => 'date_select',
281
      'default_formatter' => 'date_default',
282
      'default_token_formatter' => 'date_plain',
283
    ) + $settings,
284
  );
285
}
286

    
287
/**
288
 * Implements hook_field_widget_info().
289
 */
290
function date_field_widget_info() {
291
  $settings = array(
292
    'settings' => array(
293
      'input_format' => date_default_format('date_select'),
294
      'input_format_custom' => '',
295
      'increment' => 15,
296
      'text_parts' => array(),
297
      'year_range' => '-3:+3',
298
      'label_position' => 'above',
299
    ),
300
    'behaviors' => array(
301
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
302
      'default value' => FIELD_BEHAVIOR_NONE,
303
    ),
304
  );
305

    
306
  $info = array(
307
    'date_select' => array(
308
      'label' => t('Select list'),
309
      'field types' => array('date', 'datestamp', 'datetime'),
310
    ) + $settings,
311
    'date_text' => array(
312
      'label' => t('Text field'),
313
      'field types' => array('date', 'datestamp', 'datetime'),
314
    ) + $settings,
315
  );
316

    
317
  if (module_exists('date_popup')) {
318
    $info['date_popup'] = array(
319
      'label' => t('Pop-up calendar'),
320
      'field types' => array('date', 'datestamp', 'datetime'),
321
    ) + $settings;
322
  }
323

    
324
  // The date text widget should use an increment of 1.
325
  $info['date_text']['increment'] = 1;
326

    
327
  return $info;
328
}
329

    
330
/**
331
 * Implements hook_field_load().
332
 */
333
function date_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
334
  $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
335
  $db_format = date_type_format($field['type']);
336
  $process = date_process_values($field);
337
  foreach ($entities as $id => $entity) {
338
    foreach ($items[$id] as $delta => &$item) {
339
      // If the file does not exist, mark the entire item as empty.
340
      if (is_array($item)) {
341
        $timezone = isset($item['timezone']) ? $item['timezone'] : '';
342
        $item['timezone'] = date_get_timezone($field['settings']['tz_handling'], $timezone);
343
        $item['timezone_db'] = $timezone_db;
344
        $item['date_type'] = $field['type'];
345
        if (!empty($field['settings']['cache_enabled']) && ($delta < $field['settings']['cache_count'] || $field['settings']['cache_count'] == 0)) {
346
          foreach ($process as $processed) {
347
            if (!empty($item[$processed])) {
348
              $date = new DateObject($item[$processed], $item['timezone_db'], $db_format);
349
              $date->limitGranularity($field['settings']['granularity']);
350
              $item['db'][$processed] = $date;
351
            }
352
          }
353
          if (!empty($item['db']['value']) && empty($item['db']['value2'])) {
354
            $item['db']['value2'] = $item['db']['value'];
355
          }
356
        }
357
      }
358
    }
359
  }
360
}
361

    
362
/**
363
 * Implements hook_field_validate().
364
 */
365
function date_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
366
  $field_name = $field['field_name'];
367
  $flexible = 0;
368

    
369
  // Don't try to validate if there were any errors before this point
370
  // since the element won't have been munged back into a date.
371
  if (!form_get_errors()) {
372
    foreach ($items as $delta => $item) {
373
      if (is_array($item) && isset($item['value'])) {
374
        $process = date_process_values($field, $instance);
375
        $date1 = new DateObject($item['value'], $item['timezone'], date_type_format($field['type']));
376
        if (count($process) == 1 || (empty($item['value2']) && $item['value2'] !== 0)) {
377
          $date2 = clone($date1);
378
        }
379
        else {
380
          $date2 = new DateObject($item['value2'], $item['timezone'], date_type_format($field['type']));
381
        }
382
        $valid1 = $date1->validGranularity($field['settings']['granularity'], $flexible);
383
        $valid2 = $date2->validGranularity($field['settings']['granularity'], $flexible);
384

    
385
        foreach ($process as $processed) {
386
          if ($processed == 'value' && $field['settings']['todate'] && !$valid1 && $valid2) {
387
            $errors[$field['field_name']][$langcode][$delta][] = array(
388
              'error' => 'value',
389
              'message' => t("A 'Start date' date is required for field %field #%delta.", array('%delta' => $field['cardinality'] ? intval($delta + 1) : '', '%field' => $instance['label'])),
390
            );
391
          }
392
          if ($processed == 'value2' && $field['settings']['todate'] == 'required' && ($instance['required'] && $valid1 && !$valid2)) {
393
            $errors[$field['field_name']][$langcode][$delta][] = array(
394
              'error' => 'value2',
395
              'message' => t("An 'End date' is required for field %field #%delta.", array('%delta' => $field['cardinality'] ? intval($delta + 1) : '', '%field' => $instance['label'])),
396
            );
397
          }
398
        }
399
      }
400
    }
401
  }
402
}
403

    
404
/**
405
 * Implements hook_field_insert().
406
 */
407
function date_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
408
  $field_name = $field['field_name'];
409

    
410
  if (empty($items)) {
411
    return;
412
  }
413
  // Add some information needed to interpret token values.
414
  $values = $items;
415
  foreach ($values as $delta => $item) {
416
    $timezone = isset($item['timezone']) ? $item['timezone'] : '';
417
    if (is_array($item)) {
418
      $items[$delta]['timezone'] = date_get_timezone($field['settings']['tz_handling'], $timezone);
419
      $items[$delta]['timezone_db'] = date_get_timezone_db($field['settings']['tz_handling']);
420
      $items[$delta]['date_type'] = $field['type'];
421
    }
422
  }
423
  $entity->{$field['field_name']}[$langcode] = $items;
424
}
425

    
426
/**
427
 * Implements hook_field_insert().
428
 */
429
function date_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
430
  $context = array(
431
    'entity_type' => $entity_type,
432
    'entity' => $entity,
433
    'field' => $field,
434
    'instance' => $instance,
435
    'langcode' => $langcode,
436
  );
437
  drupal_alter('date_field_insert', $items, $context);
438
}
439

    
440
/**
441
 * Implements hook_field_update().
442
 */
443
function date_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
444
  $context = array(
445
    'entity_type' => $entity_type,
446
    'entity' => $entity,
447
    'field' => $field,
448
    'instance' => $instance,
449
    'langcode' => $langcode,
450
  );
451
  drupal_alter('date_field_update', $items, $context);
452
}
453

    
454
/**
455
 * Implements hook_field_instance_settings_form().
456
 *
457
 * Wrapper functions for date administration, included only when processing
458
 * field settings.
459
 */
460
function date_field_instance_settings_form($field, $instance) {
461
  module_load_include('inc', 'date', 'date_admin');
462
  return _date_field_instance_settings_form($field, $instance);
463
}
464

    
465
/**
466
 * Implements hook_field_widget_settings_form().
467
 */
468
function date_field_widget_settings_form($field, $instance) {
469
  module_load_include('inc', 'date', 'date_admin');
470
  return _date_field_widget_settings_form($field, $instance);
471
}
472

    
473
/**
474
 * Implements hook_field_settings_form().
475
 */
476
function date_field_settings_form($field, $instance, $has_data) {
477
  module_load_include('inc', 'date', 'date_admin');
478
  return _date_field_settings_form($field, $instance, $has_data);
479
}
480

    
481
/**
482
 * Implements hook_content_migrate_field_alter().
483
 *
484
 * Use this to tweak the conversion of field settings from the D6 style to the
485
 * D7 style for specific situations not handled by basic conversion, as when
486
 * field types or settings are changed.
487
 *
488
 * $field_value['widget_type'] is available to see what widget type was
489
 * originally used.
490
 */
491
function date_content_migrate_field_alter(&$field_value, $instance_value) {
492
  switch ($field_value['module']) {
493
    case 'date':
494
      // Those settings do not exist anymore, or have been moved to the instance
495
      // level.
496
      unset($field_value['settings']['default_format']);
497
      unset($field_value['settings']['repeat_collapsed']);
498
      break;
499
  }
500
}
501

    
502
/**
503
 * Implements hook_content_migrate_instance_alter().
504
 *
505
 * Use this to tweak the conversion of instance or widget settings from the D6
506
 * style to the D7 style for specific situations not handled by basic
507
 * conversion, as when formatter or widget names or settings are changed.
508
 */
509
function date_content_migrate_instance_alter(&$instance_value, $field_value) {
510
  switch ($instance_value['widget']['module']) {
511
    case 'date':
512

    
513
      // Some settings have been moved from field to instance.
514
      $instance_value['widget']['settings']['repeat_collapsed'] = $field_value['settings']['repeat_collapsed'];
515

    
516
      // Some settings were moved from widget settings to instance settings.
517
      $instance_value['settings']['default_value'] = $instance_value['default_value'];
518
      unset($instance_value['default_value']);
519
      $instance_value['settings']['default_value_code'] = $instance_value['widget']['settings']['default_value_code'];
520
      unset($instance_value['widget']['settings']['default_value_code']);
521
      $instance_value['settings']['default_value2'] = $instance_value['widget']['settings']['default_value2'];
522
      unset($instance_value['widget']['settings']['default_value2']);
523
      $instance_value['settings']['default_value_code2'] = $instance_value['widget']['settings']['default_value_code2'];
524
      unset($instance_value['widget']['settings']['default_value_code2']);
525

    
526
      // We need to retrieve formatter settings from the variables and store
527
      // them in the instance.
528
      foreach ($instance_value['display'] as $context => &$display) {
529
        if ($display['type'] != 'format_interval') {
530
          $old_settings = date_old_formatter_get_settings($instance_value['field_name'], $instance_value['bundle'], $context);
531
          $display['settings'] = array_merge($display['settings'], $old_settings);
532
          // If the formatter was the 'default', then use the old
533
          // 'default_format' field property.
534
          $format = ($display['type'] == 'default') ? $field_value['settings']['default_format'] : $display['type'];
535
          $display['settings']['format_type'] = $format;
536
          $display['type'] = 'date_default';
537
        }
538
      }
539

    
540
      break;
541
  }
542
}
543

    
544
/**
545
 * Constructs an array of old formatter settings.
546
 */
547
function date_old_formatter_get_settings($field_name, $type_name, $context) {
548
  $options = array();
549
  $value = 'date:' . $type_name . ':' . $context . ':' . $field_name;
550
  $options['show_repeat_rule'] = variable_get($value . '_show_repeat_rule', 'show');
551
  $options['multiple_number'] = variable_get($value . '_multiple_number', '');
552
  $options['multiple_from'] = variable_get($value . '_multiple_from', '');
553
  $options['multiple_to'] = variable_get($value . '_multiple_to', '');
554
  $options['fromto'] = variable_get($value . '_fromto', 'both');
555
  return $options;
556
}