Projet

Général

Profil

Paste
Télécharger (27,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date.module @ b720ea3e

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines date/time field types.
6
 */
7

    
8
module_load_include('theme', 'date', 'date');
9
module_load_include('inc', 'date', 'date.field');
10
module_load_include('inc', 'date', 'date_elements');
11

    
12
/**
13
 * Helper function to figure out the bundle name for an entity.
14
 */
15
function date_get_entity_bundle($entity_type, $entity) {
16
  switch ($entity_type) {
17
    case 'field_collection_item':
18
      $bundle = $entity->field_name;
19
      break;
20

    
21
    default:
22
      $bundle = field_extract_bundle($entity_type, $entity);
23
      break;
24
  }
25
  // If there is no bundle name, field_info() uses the entity name as the bundle
26
  // name in its arrays.
27
  if (empty($bundle)) {
28
    $bundle = $entity_type;
29
  }
30
  return $bundle;
31
}
32

    
33
/**
34
 * Gets the default date format for the given field widget.
35
 */
36
function date_default_format($type) {
37
  // Example input formats must show all possible date parts, so add seconds.
38
  $default_format = str_replace('i', 'i:s', variable_get('date_format_short', 'm/d/Y - H:i'));
39
  return $default_format;
40
}
41

    
42
/**
43
 * Wrapper function around each of the widget types for creating a date object.
44
 */
45
function date_input_date($field, $instance, $element, $input) {
46
  // Trim extra spacing off user input of text fields.
47
  if (isset($input['date'])) {
48
    $input['date'] = trim($input['date']);
49
  }
50

    
51
  switch ($instance['widget']['type']) {
52
    case 'date_text':
53
      $function = 'date_text_input_date';
54
      break;
55

    
56
    case 'date_popup':
57
      $function = 'date_popup_input_date';
58
      break;
59

    
60
    default:
61
      $function = 'date_select_input_date';
62
  }
63
  return $function($element, $input);
64
}
65

    
66
/**
67
 * Implements hook_theme().
68
 */
69
function date_theme() {
70
  $path = drupal_get_path('module', 'date');
71
  module_load_include('theme', 'date', 'date');
72

    
73
  $base = array(
74
    'file' => 'date.theme',
75
    'path' => "$path",
76
  );
77
  $themes = array(
78
    'date_combo' => $base + array('render element' => 'element'),
79
    'date_form_element' => $base + array('render element' => 'element'),
80
    'date_text_parts' => $base + array('render element' => 'element'),
81
    'date' => $base + array('render element' => 'element'),
82
    'date_display_single' => $base + array(
83
      'variables' => array(
84
        'date' => NULL,
85
        'timezone' => NULL,
86
        'dates' => NULL,
87
        'attributes' => array(),
88
        'rdf_mapping' => NULL,
89
        'add_rdf' => NULL,
90
        'microdata' => NULL,
91
        'add_microdata' => NULL,
92
      ),
93
    ),
94
    'date_display_range' => $base + array(
95
      'variables' => array(
96
        'date1' => NULL,
97
        'date2' => NULL,
98
        'timezone' => NULL,
99
        'dates' => NULL,
100
        // HTML attributes that will be applied to both the start and end dates
101
        // (unless overridden).
102
        'attributes' => array(),
103
        // HTML attributes that will be applied to the start date only.
104
        'attributes_start' => array(),
105
        // HTML attributes that will be applied to the end date only.
106
        'attributes_end' => array(),
107
        'rdf_mapping' => NULL,
108
        'add_rdf' => NULL,
109
        'microdata' => NULL,
110
        'add_microdata' => NULL,
111
      ),
112
    ),
113
    'date_display_remaining' => $base + array(
114
      'variables' => array(
115
        'remaining_days' => NULL,
116
      ),
117
    ),
118
    'date_display_combination' => $base + array(
119
      'variables' => array(
120
        'entity_type' => NULL,
121
        'entity' => NULL,
122
        'field' => NULL,
123
        'instance' => NULL,
124
        'langcode' => NULL,
125
        'item' => NULL,
126
        'delta' => NULL,
127
        'display' => NULL,
128
        'dates' => NULL,
129
        'attributes' => array(),
130
        'rdf_mapping' => NULL,
131
        'add_rdf' => NULL,
132
        'microdata' => NULL,
133
        'add_microdata' => NULL,
134
      ),
135
    ),
136
    'date_display_interval' => $base + array(
137
      'variables' => array(
138
        'entity_type' => NULL,
139
        'entity' => NULL,
140
        'field' => NULL,
141
        'instance' => NULL,
142
        'langcode' => NULL,
143
        'item' => NULL,
144
        'delta' => NULL,
145
        'display' => NULL,
146
        'dates' => NULL,
147
        'attributes' => array(),
148
        'rdf_mapping' => NULL,
149
        'add_rdf' => NULL,
150
      ),
151
    ),
152
  );
153

    
154
  return $themes;
155
}
156

    
157
/**
158
 * Implements hook_element_info().
159
 *
160
 * date_combo will create a 'start' and optional 'end' date, along with
161
 * an optional 'timezone' column for date-specific timezones. Each
162
 * 'start' and 'end' date will be constructed from date_select or date_text.
163
 */
164
function date_element_info() {
165
  $type = array();
166
  $type['date_combo'] = array(
167
    '#input' => TRUE,
168
    '#delta' => 0,
169
    '#columns' => array('value', 'value2', 'timezone', 'offset', 'offset2'),
170
    '#process' => array('date_combo_element_process'),
171
    '#element_validate' => array('date_combo_validate'),
172
    '#theme_wrappers' => array('date_combo'),
173
  );
174
  if (module_exists('ctools')) {
175
    $type['date_combo']['#pre_render'] = array('ctools_dependent_pre_render');
176
  }
177
  return $type;
178
}
179

    
180
/**
181
 * Helper function for creating formatted date arrays from a formatter.
182
 *
183
 * Use the Date API to get an object representation of a date field.
184
 *
185
 * @param string $formatter
186
 *   The date formatter.
187
 * @param string $entity_type
188
 *   The entity_type for the instance
189
 * @param object $entity
190
 *   The entity object.
191
 * @param array $field
192
 *   The field info array.
193
 * @param array $instance
194
 *   The field instance array.
195
 * @param string $langcode
196
 *   The language code used by this field.
197
 * @param array $item
198
 *   An entity field item, like $entity->myfield[0].
199
 * @param array $display
200
 *   The instance display settings.
201
 *
202
 * @return array
203
 *   An array that holds the Start and End date objects.
204
 *   Each date object looks like:
205
 *     date [value] => array (
206
 *       [db] => array (  // the value stored in the database
207
 *         [object] => the datetime object
208
 *         [datetime] => 2007-02-15 20:00:00
209
 *       )
210
 *       [local] => array (  // the local representation of that value
211
 *         [object] => the datetime object
212
 *         [datetime] => 2007-02-15 14:00:00
213
 *         [timezone] => US/Central
214
 *         [offset] => -21600
215
 *       )
216
 *     )
217
 */
218
function date_formatter_process($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display) {
219
  $dates = array();
220
  $timezone = date_default_timezone();
221
  if (empty($timezone)) {
222
    return $dates;
223
  }
224

    
225
  $granularity = date_granularity($field);
226
  $settings = $display['settings'];
227
  $field_name = $field['field_name'];
228
  $format = date_formatter_format($formatter, $settings, $granularity, $langcode);
229
  if (!isset($field['settings']['tz_handling']) || $field['settings']['tz_handling'] !== 'utc') {
230
    $timezone = isset($item['timezone']) ? $item['timezone'] : '';
231
    $timezone = date_get_timezone($field['settings']['tz_handling'], $timezone);
232
  }
233
  $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
234
  $db_format = date_type_format($field['type']);
235
  $process = date_process_values($field);
236
  foreach ($process as $processed) {
237
    if (empty($item[$processed])) {
238
      $dates[$processed] = NULL;
239
    }
240
    else {
241
      // Create a date object with a GMT timezone from the database value.
242
      $dates[$processed] = array();
243

    
244
      // Check to see if this date was already created by date_field_load().
245
      if (isset($item['db'][$processed])) {
246
        $date = $item['db'][$processed];
247
      }
248
      else {
249
        $date = new DateObject($item[$processed], $timezone_db, $db_format);
250
        $date->limitGranularity($field['settings']['granularity']);
251
      }
252

    
253
      $dates[$processed]['db']['object'] = $date;
254
      $dates[$processed]['db']['datetime'] = date_format($date, DATE_FORMAT_DATETIME);
255

    
256
      date_timezone_set($date, timezone_open($timezone));
257
      $dates[$processed]['local']['object'] = $date;
258
      $dates[$processed]['local']['datetime'] = date_format($date, DATE_FORMAT_DATETIME);
259
      $dates[$processed]['local']['timezone'] = $timezone;
260
      $dates[$processed]['local']['offset'] = date_offset_get($date);
261

    
262
      // Format the date, special casing the 'interval' format which doesn't
263
      // need to be processed.
264
      $dates[$processed]['formatted'] = '';
265
      $dates[$processed]['formatted_iso'] = date_format_date($date, 'custom', 'c');
266
      if (is_object($date)) {
267
        if ($format == 'format_interval') {
268
          $dates[$processed]['interval'] = date_format_interval($date);
269
        }
270
        elseif ($format == 'format_calendar_day') {
271
          $dates[$processed]['calendar_day'] = date_format_calendar_day($date);
272
        }
273
        elseif ($format == 'U' || $format == 'r' || $format == 'c') {
274
          $dates[$processed]['formatted'] = date_format_date($date, 'custom', $format);
275
          $dates[$processed]['formatted_date'] = date_format_date($date, 'custom', $format);
276
          $dates[$processed]['formatted_time'] = '';
277
          $dates[$processed]['formatted_timezone'] = '';
278
        }
279
        elseif (!empty($format)) {
280
          $formats = _get_custom_date_format($date, $format);
281
          $dates[$processed]['formatted'] = $formats['formatted'];
282
          $dates[$processed]['formatted_date'] = $formats['date'];
283
          $dates[$processed]['formatted_time'] = $formats['time'];
284
          $dates[$processed]['formatted_timezone'] = $formats['zone'];
285
        }
286
      }
287
    }
288
  }
289

    
290
  if (empty($dates['value2'])) {
291
    $dates['value2'] = $dates['value'];
292
  }
293

    
294
  // Allow other modules to alter the date values.
295
  $context = array(
296
    'field' => $field,
297
    'instance' => $instance,
298
    'format' => $format,
299
    'entity_type' => $entity_type,
300
    'entity' => $entity,
301
    'langcode' => $langcode,
302
    'item' => $item,
303
    'display' => $display,
304
  );
305
  drupal_alter('date_formatter_dates', $dates, $context);
306

    
307
  $dates['format'] = $format;
308
  return $dates;
309
}
310

    
311
/**
312
 * Get a custom date format.
313
 */
314
function _get_custom_date_format($date, $format) {
315
  $custom = array();
316
  $custom['granularities'] = array(
317
    'date' => array('year', 'month', 'day'),
318
    'time' => array('hour', 'minute', 'second'),
319
    'zone' => array('timezone'),
320
  );
321
  $custom['limits'] = array(
322
    'date' => date_limit_format($format, $custom['granularities']['date']),
323
    'time' => date_limit_format($format, $custom['granularities']['time']),
324
    'zone' => date_limit_format($format, $custom['granularities']['zone']),
325
  );
326

    
327
  return array(
328
    'formatted' => date_format_date($date, 'custom', $format),
329
    'date'      => date_format_date($date, 'custom', $custom['limits']['date']),
330
    'time'      => date_format_date($date, 'custom', $custom['limits']['time']),
331
    'zone'      => date_format_date($date, 'custom', $custom['limits']['zone']),
332
  );
333
}
334

    
335
/**
336
 * Retrieves the granularity for a field.
337
 *
338
 * $field['settings']['granularity'] will contain an array like
339
 * ('hour' => 'hour', 'month' => 0) where the values turned on return their own
340
 * names and the values turned off return a zero need to reconfigure this into
341
 * simple array of the turned on values
342
 *
343
 * @param array $field
344
 *   The field array.
345
 */
346
function date_granularity($field) {
347
  if (!is_array($field) || !is_array($field['settings']['granularity'])) {
348
    $granularity = drupal_map_assoc(array('year', 'month', 'day'));
349
    $field['settings']['granularity'] = $granularity;
350
  }
351
  return array_values(array_filter($field['settings']['granularity']));
352
}
353

    
354
/**
355
 * Helper function to create an array of the date values in a field that need to be processed.
356
 */
357
function date_process_values($field) {
358
  return $field['settings']['todate'] ? array('value', 'value2') : array('value');
359
}
360

    
361
/**
362
 * Implements hook_form_FORM_ID_alter() for field_ui_field_edit_form().
363
 */
364
function date_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
365
  $field = $form['#field'];
366
  $instance = $form['#instance'];
367

    
368
  if (!in_array($field['type'], array('date', 'datetime', 'datestamp'))) {
369
    return;
370
  }
371

    
372
  // Reorganize the instance settings and widget settings sections into a more
373
  // intuitive combined fieldset.
374
  $form['instance']['defaults'] = array(
375
    '#type' => 'fieldset',
376
    '#title' => t('More settings and values'),
377
    '#collapsible' => TRUE,
378
    '#collapsed' => TRUE,
379
  );
380
  $form['instance']['date_format'] = array(
381
    '#type' => 'fieldset',
382
    '#title' => t('Date entry'),
383
    '#collapsible' => TRUE,
384
    '#collapsed' => FALSE,
385
  );
386
  $form['instance']['default_values'] = array(
387
    '#type' => 'fieldset',
388
    '#title' => t('Default values'),
389
    '#collapsible' => TRUE,
390
    '#collapsed' => FALSE,
391
  );
392
  $form['instance']['years_back_and_forward'] = array(
393
    '#type' => 'fieldset',
394
    '#title' => t('Starting and ending year'),
395
    '#collapsible' => TRUE,
396
    '#collapsed' => FALSE,
397
  );
398

    
399
  $form['instance']['#pre_render'][] = 'date_field_ui_field_edit_form_pre_render';
400
}
401

    
402
/**
403
 * Rearrange form elements into fieldsets for presentation only.
404
 */
405
function date_field_ui_field_edit_form_pre_render($form) {
406
  foreach ($form as $name => $element) {
407
    if (is_array($element) && isset($element['#fieldset'])) {
408
      $fieldset = $element['#fieldset'];
409
      $form[$fieldset][$name] = $element;
410
      unset($form[$name]);
411
    }
412
  }
413
  foreach (array('date_format', 'default_values', 'years_back_and_forward') as $name) {
414
    if (element_children($form[$name])) {
415
      // Force the items in the fieldset to be resorted now that the instance
416
      // and widget settings are combined.
417
      $form[$name]['#sorted'] = FALSE;
418
      $form['defaults'][$name] = $form[$name];
419
    }
420
    unset($form[$name]);
421
  }
422
  return $form;
423
}
424

    
425
/**
426
 * Implements hook_field_widget_error().
427
 */
428
function date_field_widget_error($element, $error, $form, &$form_state) {
429
  form_error($element[$error['error']], $error['message']);
430
}
431

    
432
/**
433
 * Retrieve a date format string from formatter settings.
434
 */
435
function date_formatter_format($formatter, $settings, $granularity = array(), $langcode = NULL) {
436
  $format_type = !empty($settings['format_type']) ? $settings['format_type'] : 'format_interval';
437

    
438
  switch ($formatter) {
439
    case 'format_interval':
440
      return 'format_interval';
441

    
442
    case 'date_plain':
443
      return 'date_plain';
444

    
445
    default:
446
      $format = date_format_type_format($format_type, $langcode);
447
      break;
448
  }
449

    
450
  // A selected format might include timezone information.
451
  array_push($granularity, 'timezone');
452
  return date_limit_format($format, $granularity);
453
}
454

    
455
/**
456
 * Helper function to get the right format for a format type.
457
 *
458
 * Checks for locale-based format first.
459
 */
460
function date_format_type_format($format_type, $langcode = NULL) {
461
  $static = &drupal_static(__FUNCTION__);
462
  if (!isset($static[$langcode][$format_type])) {
463
    $format = system_date_format_locale($langcode, $format_type);
464

    
465
    // If locale enabled and $format_type inexistent in {date_format_locale}
466
    // we receive (due to inconsistency of core api) an array of all (other)
467
    // formats available for $langcode in locale table.
468
    // However there's no guarantee that the key $format_type exists.
469
    // See http://drupal.org/node/1302358.
470
    if (!is_string($format)) {
471
      // If the configuration page at admin/config/regional/date-time was
472
      // never saved, the default core date format variables
473
      // ('date_format_short', 'date_format_medium', and 'date_format_long')
474
      // will not be stored in the database, so we have to define their
475
      // expected defaults here.
476
      switch ($format_type) {
477
        case 'short':
478
          $default = 'm/d/Y - H:i';
479
          break;
480

    
481
        case 'long':
482
          $default = 'l, F j, Y - H:i';
483
          break;
484

    
485
        // If it's not one of the core date types and isn't stored in the
486
        // database, we'll fall back on using the same default format as the
487
        // 'medium' type.
488
        case 'medium':
489
        default:
490
          // @todo: If a non-core module provides a date type and does not
491
          // variable_set() a default for it, the default assumed here may
492
          // not be correct (since the default format used by 'medium' may
493
          // not even be one of the allowed formats for the date type in
494
          // question). To fix this properly, we should really call
495
          // system_get_date_formats($format_type) and take the first
496
          // format from that list as the default. However, this function
497
          // is called often (on many different page requests), so calling
498
          // system_get_date_formats() from here would be a performance hit
499
          // since that function writes several records to the database
500
          // during each page request that calls it.
501
          $default = 'D, m/d/Y - H:i';
502
          break;
503

    
504
      }
505
      $format = variable_get('date_format_' . $format_type, $default);
506
    }
507
    $static[$langcode][$format_type] = $format;
508
  }
509
  return $static[$langcode][$format_type];
510
}
511

    
512
/**
513
 * Helper function to adapt entity date fields to formatter settings.
514
 */
515
function date_prepare_entity($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display) {
516
  // If there are options to limit multiple values,
517
  // alter the entity values to match.
518
  $field_name = $field['field_name'];
519
  $options = $display['settings'];
520
  $max_count = $options['multiple_number'];
521

    
522
  // If no results should be shown, empty the values and return.
523
  if (is_numeric($max_count) && $max_count == 0) {
524
    $entity->{$field_name} = array();
525
    return $entity;
526
  }
527

    
528
  // Otherwise removed values that should not be displayed.
529
  if (!empty($options['multiple_from']) || !empty($options['multiple_to']) || !empty($max_count)) {
530
    $format = date_type_format($field['type']);
531
    include_once drupal_get_path('module', 'date_api') . '/date_api_sql.inc';
532
    $date_handler = new date_sql_handler($field);
533
    $arg0 = !empty($options['multiple_from']) ? $date_handler->arg_replace($options['multiple_from']) : variable_get('date_min_year', 100) . '-01-01T00:00:00';
534
    $arg1 = !empty($options['multiple_to']) ? $date_handler->arg_replace($options['multiple_to']) : variable_get('date_max_year', 4000) . '-12-31T23:59:59';
535
    if (!empty($arg0) && !empty($arg1)) {
536
      $arg = $arg0 . '--' . $arg1;
537
    }
538
    elseif (!empty($arg0)) {
539
      $arg = $arg0;
540
    }
541
    elseif (!empty($arg1)) {
542
      $arg = $arg1;
543
    }
544
    if (!empty($arg)) {
545
      $range = $date_handler->arg_range($arg);
546
      $start = date_format($range[0], $format);
547
      $end = date_format($range[1], $format);
548
      // Empty out values we don't want to see.
549
      $count = 0;
550
      foreach ($entity->{$field_name}[$langcode] as $delta => $value) {
551
        if (!empty($entity->date_repeat_show_all)) {
552
          break;
553
        }
554
        elseif ((!empty($max_count) && is_numeric($max_count) && $count >= $max_count) ||
555
          (!empty($value['value'])  && $value['value'] < $start) ||
556
          (!empty($value['value2']) && $value['value2'] > $end)) {
557
          unset($entity->{$field_name}[$langcode][$delta]);
558
        }
559
        else {
560
          $count++;
561
        }
562
      }
563
    }
564
  }
565

    
566
  return $entity;
567
}
568

    
569
/**
570
 * Callback to alter the property info of date fields.
571
 *
572
 * @see date_field_info()
573
 */
574
function date_entity_metadata_property_info_alter(&$info, $entity_type, $field, $instance, $field_type) {
575
  $name = $field['field_name'];
576
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];
577

    
578
  if ($field['type'] != 'datestamp' || $field['settings']['timezone_db'] != 'UTC') {
579
    // Add a getter callback to convert the date into the right format.
580
    $property['getter callback'] = 'date_entity_metadata_field_getter';
581
    $property['setter callback'] = 'date_entity_metadata_field_setter';
582
    unset($property['query callback']);
583
  }
584
  if (!empty($field['settings']['todate'])) {
585
    // Define a simple data structure containing both dates.
586
    $property['type'] = ($field['cardinality'] != 1) ? 'list<struct>' : 'struct';
587
    $property['auto creation'] = 'date_entity_metadata_struct_create';
588
    $property['getter callback'] = 'entity_metadata_field_verbatim_get';
589
    $property['setter callback'] = 'entity_metadata_field_verbatim_set';
590
    $property['property info'] = array(
591
      'value' => array(
592
        'type' => 'date',
593
        'label' => t('Start date'),
594
        'getter callback' => 'date_entity_metadata_struct_getter',
595
        'setter callback' => 'date_entity_metadata_struct_setter',
596
        // The getter and setter callbacks for 'value' and 'value2'
597
        // will not provide the field name as $name, we'll add it to $info.
598
        'field_name' => $field['field_name'],
599
        // Alert Microdata module that this value can be exposed in microdata.
600
        'microdata' => TRUE,
601
      ),
602
      'value2' => array(
603
        'type' => 'date',
604
        'label' => t('End date'),
605
        'getter callback' => 'date_entity_metadata_struct_getter',
606
        'setter callback' => 'date_entity_metadata_struct_setter',
607
        // The getter and setter callbacks for 'value' and 'value2'
608
        // will not provide the field name as $name, we'll add it to $info.
609
        'field_name' => $field['field_name'],
610
        // Alert Microdata module that this value can be exposed in microdata.
611
        'microdata' => TRUE,
612
      ),
613
      'duration' => array(
614
        'type' => 'duration',
615
        'label' => t('Duration'),
616
        'desription' => t('The duration of the time period given by the dates.'),
617
        'getter callback' => 'date_entity_metadata_duration_getter',
618
        // No setter callback for duration.
619
        // The getter callback for duration will not provide the field name
620
        // as $name, we'll add it to $info.
621
        'field_name' => $field['field_name'],
622
      ),
623
    );
624
    unset($property['query callback']);
625
  }
626
  else {
627
    // If this doesn't have a todate, it is handled as a date rather than a
628
    // struct. Enable microdata on the field itself rather than the properties.
629
    $property['microdata'] = TRUE;
630
  }
631
}
632

    
633
/**
634
 * Getter callback to return date values as datestamp in UTC from the field.
635
 */
636
function date_entity_metadata_field_getter($entity, array $options, $name, $entity_type, &$context) {
637
  $return = entity_metadata_field_verbatim_get($entity, $options, $name, $entity_type, $context);
638
  $items = ($context['field']['cardinality'] == 1) ? array($return) : $return;
639
  foreach ($items as $key => $item) {
640
    $items[$key] = date_entity_metadata_struct_getter($item, $options, 'value', 'struct', $context);
641
  }
642
  return ($context['field']['cardinality'] == 1) ? $items[0] : $items;
643
}
644

    
645
/**
646
 * Getter callback to return date values as datestamp in UTC.
647
 */
648
function date_entity_metadata_struct_getter($item, array $options, $name, $type, $info) {
649
  $value = trim($item[$name]);
650
  if (empty($value)) {
651
    return NULL;
652
  }
653

    
654
  $timezone_db = !empty($item['timezone_db']) ? $item['timezone_db'] : 'UTC';
655
  $date = new DateObject($value, $timezone_db);
656
  return !empty($date) ? date_format_date($date, 'custom', 'U') : NULL;
657
}
658

    
659
/**
660
 * Getter callback to return the duration of the time period given by the dates.
661
 */
662
function date_entity_metadata_duration_getter($item, array $options, $name, $type, $info) {
663
  $value = date_entity_metadata_struct_getter($item, $options, 'value', 'struct', $info);
664
  $value2 = date_entity_metadata_struct_getter($item, $options, 'value2', 'struct', $info);
665
  if ($value && $value2) {
666
    return $value2 - $value;
667
  }
668
}
669

    
670
/**
671
 * Callback for setting field property values.
672
 *
673
 * Based on entity_metadata_field_property_set(), the original property setter,
674
 * adapted to transform non-timestamp date values to timestamps.
675
 */
676
function date_entity_metadata_field_setter(&$entity, $name, $value, $langcode, $entity_type, $info) {
677
  $field = field_info_field($name);
678
  if (!isset($langcode)) {
679
    // Try to figure out the default language used by the entity.
680
    // @todo: Update once http://drupal.org/node/1260640 has been fixed.
681
    $langcode = isset($entity->language) ? $entity->language : LANGUAGE_NONE;
682
  }
683
  $values = $field['cardinality'] == 1 ? array($value) : (array) $value;
684

    
685
  $items = array();
686
  foreach ($values as $delta => $value) {
687
    // Make use of the struct setter to convert the date back to a timestamp.
688
    $info['field_name'] = $name;
689
    date_entity_metadata_struct_setter($items[$delta], 'value', $value, $langcode, 'struct', $info);
690
  }
691
  $entity->{$name}[$langcode] = $items;
692
  // Empty the static field language cache, so the field system picks up any
693
  // possible new languages.
694
  drupal_static_reset('field_language');
695
}
696

    
697
/**
698
 * Auto creation callback for fields which contain two date values in one.
699
 */
700
function date_entity_metadata_struct_create($name, $property_info) {
701
  return array(
702
    'date_type' => $property_info['field']['columns'][$name]['type'],
703
    'timezone_db' => $property_info['field']['settings']['timezone_db'],
704
  );
705
}
706

    
707
/**
708
 * Callback for setting an individual field value if a to-date may be there too.
709
 *
710
 * Based on entity_property_verbatim_set().
711
 *
712
 * The passed in unix timestamp (UTC) is converted to the right value and format dependent on the field.
713
 *
714
 * $name is either 'value' or 'value2'.
715
 */
716
function date_entity_metadata_struct_setter(&$item, $name, $value, $langcode, $type, $info) {
717
  if (!isset($value)) {
718
    $item[$name] = NULL;
719
  }
720
  else {
721
    $field = field_info_field($info['field_name']);
722
    $format = date_type_format($field['type']);
723
    $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
724

    
725
    $date = new DateObject($value, 'UTC');
726
    if ($timezone_db != 'UTC') {
727
      date_timezone_set($date, timezone_open($timezone_db));
728
    }
729
    $item[$name] = $date->format($format);
730
  }
731
}
732

    
733
/**
734
 * Duplicate functionality of what is now date_all_day_field() in the Date All Day module.
735
 *
736
 * Copy left here to avoid breaking other modules that use this function.
737
 *
738
 * DEPRECATED!, will be removed at some time in the future.
739
 */
740
function date_field_all_day($field, $instance, $date1, $date2 = NULL) {
741
  if (empty($date1) || !is_object($date1)) {
742
    return FALSE;
743
  }
744
  elseif (!date_has_time($field['settings']['granularity'])) {
745
    return TRUE;
746
  }
747
  if (empty($date2)) {
748
    $date2 = $date1;
749
  }
750

    
751
  $granularity = date_granularity_precision($field['settings']['granularity']);
752
  $increment = isset($instance['widget']['settings']['increment']) ? $instance['widget']['settings']['increment'] : 1;
753
  return date_is_all_day(date_format($date1, DATE_FORMAT_DATETIME), date_format($date2, DATE_FORMAT_DATETIME), $granularity, $increment);
754
}
755

    
756
/**
757
 * Generates a Date API SQL handler for the given date field.
758
 *
759
 * The handler will be set up to make the correct timezone adjustments
760
 * for the field settings.
761
 *
762
 * @param array $field
763
 *   The $field array.
764
 * @param string $compare_tz
765
 *   The timezone used for comparison values in the SQL.
766
 *
767
 * DEPRECATED!, will be removed at some time in the future.
768
 */
769
function date_field_get_sql_handler($field, $compare_tz = NULL) {
770
  module_load_include('inc', 'date_api', 'date_api_sql');
771

    
772
  $db_info = date_api_database_info($field);
773

    
774
  // Create a DateAPI SQL handler class for this field type.
775
  $handler = new date_sql_handler($field['type']);
776

    
777
  // If this date field stores a timezone in the DB, tell the handler about it.
778
  if ($field['settings']['tz_handling'] == 'date') {
779
    $handler->db_timezone_field = $db_info['columns']['timezone']['column'];
780
  }
781
  else {
782
    $handler->db_timezone = date_get_timezone_db($field['settings']['tz_handling']);
783
  }
784

    
785
  if (empty($compare_tz)) {
786
    $compare_tz = date_get_timezone($field['settings']['tz_handling']);
787
  }
788
  $handler->local_timezone = $compare_tz;
789

    
790
  // Now that the handler is properly initialized, force the DB
791
  // to use UTC so no timezone conversions get added to things like
792
  // NOW() or FROM_UNIXTIME().
793
  $handler->set_db_timezone();
794

    
795
  return $handler;
796
}
797

    
798
/**
799
 * Implements hook_field_widget_properties_alter().
800
 *
801
 * Alters the widget properties of a field instance before it gets displayed.
802
 * Used here to flag new entities so we can later tell if they need default values.
803
 */
804
function date_field_widget_properties_alter(&$widget, $context) {
805
  if (in_array($widget['type'], array('date_select', 'date_text', 'date_popup'))) {
806
    $entity_type = $context['entity_type'];
807
    $entity = $context['entity'];
808
    $info = entity_get_info($entity_type);
809
    $id = $info['entity keys']['id'];
810
    $widget['is_new'] = FALSE;
811
    if (empty($entity->$id)) {
812
      $widget['is_new'] = TRUE;
813
    }
814
  }
815
}