date.module 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. <?php
  2. /**
  3. * @file
  4. * Defines date/time field types.
  5. */
  6. module_load_include('theme', 'date', 'date');
  7. module_load_include('inc', 'date', 'date.field');
  8. module_load_include('inc', 'date', 'date_elements');
  9. /**
  10. * Helper function to figure out the bundle name for an entity.
  11. */
  12. function date_get_entity_bundle($entity_type, $entity) {
  13. switch ($entity_type) {
  14. case 'field_collection_item':
  15. $bundle = $entity->field_name;
  16. break;
  17. default:
  18. $bundle = field_extract_bundle($entity_type, $entity);
  19. break;
  20. }
  21. // If there is no bundle name, field_info() uses the entity name as the bundle
  22. // name in its arrays.
  23. if (empty($bundle)) {
  24. $bundle = $entity_type;
  25. }
  26. return $bundle;
  27. }
  28. /**
  29. * Gets the default date format for the given field widget.
  30. */
  31. function date_default_format($type) {
  32. // Example input formats must show all possible date parts, so add seconds.
  33. $default_format = str_replace('i', 'i:s', variable_get('date_format_short', 'm/d/Y - H:i'));
  34. return $default_format;
  35. }
  36. /**
  37. * Wrapper function around each of the widget types for creating a date object.
  38. */
  39. function date_input_date($field, $instance, $element, $input) {
  40. switch ($instance['widget']['type']) {
  41. case 'date_text':
  42. $function = 'date_text_input_date';
  43. break;
  44. case 'date_popup':
  45. $function = 'date_popup_input_date';
  46. break;
  47. default:
  48. $function = 'date_select_input_date';
  49. }
  50. return $function($element, $input);
  51. }
  52. /**
  53. * Implements hook_theme().
  54. */
  55. function date_theme() {
  56. $path = drupal_get_path('module', 'date');
  57. module_load_include('theme', 'date', 'date');
  58. $base = array(
  59. 'file' => 'date.theme',
  60. 'path' => "$path",
  61. );
  62. $themes = array(
  63. 'date_combo' => $base + array('render element' => 'element'),
  64. 'date_text_parts' => $base + array('render element' => 'element'),
  65. 'date' => $base + array('render element' => 'element'),
  66. 'date_display_single' => $base + array(
  67. 'variables' => array(
  68. 'date' => NULL,
  69. 'timezone' => NULL,
  70. 'dates' => NULL,
  71. 'attributes' => array(),
  72. 'rdf_mapping' => NULL,
  73. 'add_rdf' => NULL,
  74. 'microdata' => NULL,
  75. 'add_microdata' => NULL,
  76. ),
  77. ),
  78. 'date_display_range' => $base + array(
  79. 'variables' => array(
  80. 'date1' => NULL,
  81. 'date2' => NULL,
  82. 'timezone' => NULL,
  83. 'dates' => NULL,
  84. // HTML attributes that will be applied to both the start and end dates
  85. // (unless overridden).
  86. 'attributes' => array(),
  87. // HTML attributes that will be applied to the start date only.
  88. 'attributes_start' => array(),
  89. // HTML attributes that will be applied to the end date only.
  90. 'attributes_end' => array(),
  91. 'rdf_mapping' => NULL,
  92. 'add_rdf' => NULL,
  93. 'microdata' => NULL,
  94. 'add_microdata' => NULL,
  95. )),
  96. 'date_display_combination' => $base + array(
  97. 'variables' => array(
  98. 'entity_type' => NULL,
  99. 'entity' => NULL,
  100. 'field' => NULL,
  101. 'instance' => NULL,
  102. 'langcode' => NULL,
  103. 'item' => NULL,
  104. 'delta' => NULL,
  105. 'display' => NULL,
  106. 'dates' => NULL,
  107. 'attributes' => array(),
  108. 'rdf_mapping' => NULL,
  109. 'add_rdf' => NULL,
  110. 'microdata' => NULL,
  111. 'add_microdata' => NULL,
  112. ),
  113. ),
  114. 'date_display_interval' => $base + array(
  115. 'variables' => array(
  116. 'entity_type' => NULL,
  117. 'entity' => NULL,
  118. 'field' => NULL,
  119. 'instance' => NULL,
  120. 'langcode' => NULL,
  121. 'item' => NULL,
  122. 'delta' => NULL,
  123. 'display' => NULL,
  124. 'dates' => NULL,
  125. 'attributes' => array(),
  126. 'rdf_mapping' => NULL,
  127. 'add_rdf' => NULL,
  128. ),
  129. ),
  130. );
  131. return $themes;
  132. }
  133. /**
  134. * Implements hook_element_info().
  135. *
  136. * date_combo will create a 'start' and optional 'end' date, along with
  137. * an optional 'timezone' column for date-specific timezones. Each
  138. * 'start' and 'end' date will be constructed from date_select or date_text.
  139. */
  140. function date_element_info() {
  141. $type = array();
  142. $type['date_combo'] = array(
  143. '#input' => TRUE,
  144. '#delta' => 0,
  145. '#columns' => array('value', 'value2', 'timezone', 'offset', 'offset2'),
  146. '#process' => array('date_combo_element_process'),
  147. '#element_validate' => array('date_combo_validate'),
  148. '#theme_wrappers' => array('date_combo'),
  149. );
  150. if (module_exists('ctools')) {
  151. $type['date_combo']['#pre_render'] = array('ctools_dependent_pre_render');
  152. }
  153. return $type;
  154. }
  155. /**
  156. * Helper function for creating formatted date arrays from a formatter.
  157. *
  158. * Use the Date API to get an object representation of a date field.
  159. *
  160. * @param string $formatter
  161. * The date formatter.
  162. * @param string $entity_type
  163. * The entity_type for the instance
  164. * @param object $entity
  165. * The entity object.
  166. * @param array $field
  167. * The field info array.
  168. * @param array $instance
  169. * The field instance array.
  170. * @param string $langcode
  171. * The language code used by this field.
  172. * @param array $item
  173. * An entity field item, like $entity->myfield[0].
  174. * @param array $display
  175. * The instance display settings.
  176. *
  177. * @return array
  178. * An array that holds the Start and End date objects.
  179. * Each date object looks like:
  180. * date [value] => array (
  181. * [db] => array ( // the value stored in the database
  182. * [object] => the datetime object
  183. * [datetime] => 2007-02-15 20:00:00
  184. * )
  185. * [local] => array ( // the local representation of that value
  186. * [object] => the datetime object
  187. * [datetime] => 2007-02-15 14:00:00
  188. * [timezone] => US/Central
  189. * [offset] => -21600
  190. * )
  191. * )
  192. */
  193. function date_formatter_process($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display) {
  194. $dates = array();
  195. $timezone = date_default_timezone();
  196. if (empty($timezone)) {
  197. return $dates;
  198. }
  199. $granularity = date_granularity($field);
  200. $settings = $display['settings'];
  201. $field_name = $field['field_name'];
  202. $format = date_formatter_format($formatter, $settings, $granularity, $langcode);
  203. $timezone = isset($item['timezone']) ? $item['timezone'] : '';
  204. $timezone = date_get_timezone($field['settings']['tz_handling'], $timezone);
  205. $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
  206. $db_format = date_type_format($field['type']);
  207. $process = date_process_values($field);
  208. foreach ($process as $processed) {
  209. if (empty($item[$processed])) {
  210. $dates[$processed] = NULL;
  211. }
  212. else {
  213. // Create a date object with a GMT timezone from the database value.
  214. $dates[$processed] = array();
  215. // Check to see if this date was already created by date_field_load().
  216. if (isset($item['db'][$processed])) {
  217. $date = $item['db'][$processed];
  218. }
  219. else {
  220. $date = new DateObject($item[$processed], $timezone_db, $db_format);
  221. $date->limitGranularity($field['settings']['granularity']);
  222. }
  223. $dates[$processed]['db']['object'] = $date;
  224. $dates[$processed]['db']['datetime'] = date_format($date, DATE_FORMAT_DATETIME);
  225. date_timezone_set($date, timezone_open($timezone));
  226. $dates[$processed]['local']['object'] = $date;
  227. $dates[$processed]['local']['datetime'] = date_format($date, DATE_FORMAT_DATETIME);
  228. $dates[$processed]['local']['timezone'] = $timezone;
  229. $dates[$processed]['local']['offset'] = date_offset_get($date);
  230. // Format the date, special casing the 'interval' format which doesn't
  231. // need to be processed.
  232. $dates[$processed]['formatted'] = '';
  233. $dates[$processed]['formatted_iso'] = date_format_date($date, 'custom', 'c');
  234. if (is_object($date)) {
  235. if ($format == 'format_interval') {
  236. $dates[$processed]['interval'] = date_format_interval($date);
  237. }
  238. elseif ($format == 'format_calendar_day') {
  239. $dates[$processed]['calendar_day'] = date_format_calendar_day($date);
  240. }
  241. elseif ($format == 'U' || $format == 'r' || $format == 'c') {
  242. $dates[$processed]['formatted'] = date_format_date($date, 'custom', $format);
  243. $dates[$processed]['formatted_date'] = date_format_date($date, 'custom', $format);
  244. $dates[$processed]['formatted_time'] = '';
  245. $dates[$processed]['formatted_timezone'] = '';
  246. }
  247. elseif (!empty($format)) {
  248. $dates[$processed]['formatted'] = date_format_date($date, 'custom', $format);
  249. $dates[$processed]['formatted_date'] = date_format_date($date, 'custom', date_limit_format($format, array('year', 'month', 'day')));
  250. $dates[$processed]['formatted_time'] = date_format_date($date, 'custom', date_limit_format($format, array('hour', 'minute', 'second')));
  251. $dates[$processed]['formatted_timezone'] = date_format_date($date, 'custom', date_limit_format($format, array('timezone')));
  252. }
  253. }
  254. }
  255. }
  256. if (empty($dates['value2'])) {
  257. $dates['value2'] = $dates['value'];
  258. }
  259. // Allow other modules to alter the date values.
  260. $context = array(
  261. 'field' => $field,
  262. 'instance' => $instance,
  263. 'format' => $format,
  264. 'entity_type' => $entity_type,
  265. 'entity' => $entity,
  266. 'langcode' => $langcode,
  267. 'item' => $item,
  268. 'display' => $display,
  269. );
  270. drupal_alter('date_formatter_dates', $dates, $context);
  271. $dates['format'] = $format;
  272. return $dates;
  273. }
  274. /**
  275. * Retrieves the granularity for a field.
  276. *
  277. * $field['settings']['granularity'] will contain an array like
  278. * ('hour' => 'hour', 'month' => 0) where the values turned on return their own
  279. * names and the values turned off return a zero need to reconfigure this into
  280. * simple array of the turned on values
  281. *
  282. * @param array $field
  283. * The field array.
  284. */
  285. function date_granularity($field) {
  286. if (!is_array($field) || !is_array($field['settings']['granularity'])) {
  287. $field['settings']['granularity'] = drupal_map_assoc(array('year', 'month', 'day'));
  288. }
  289. return array_values(array_filter($field['settings']['granularity']));
  290. }
  291. /**
  292. * Helper function to create an array of the date values in a
  293. * field that need to be processed.
  294. */
  295. function date_process_values($field) {
  296. return $field['settings']['todate'] ? array('value', 'value2') : array('value');
  297. }
  298. /**
  299. * Implements hook_form_FORM_ID_alter() for field_ui_field_edit_form().
  300. */
  301. function date_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  302. $field = $form['#field'];
  303. $instance = $form['#instance'];
  304. if (!in_array($field['type'], array('date', 'datetime', 'datestamp'))) {
  305. return;
  306. }
  307. // Reorganize the instance settings and widget settings sections into a more
  308. // intuitive combined fieldset.
  309. $form['instance']['defaults'] = array(
  310. '#type' => 'fieldset',
  311. '#title' => t('More settings and values'),
  312. '#collapsible' => TRUE,
  313. '#collapsed' => TRUE,
  314. );
  315. $form['instance']['date_format'] = array(
  316. '#type' => 'fieldset',
  317. '#title' => t('Date entry'),
  318. '#collapsible' => TRUE,
  319. '#collapsed' => FALSE,
  320. );
  321. $form['instance']['default_values'] = array(
  322. '#type' => 'fieldset',
  323. '#title' => t('Default values'),
  324. '#collapsible' => TRUE,
  325. '#collapsed' => FALSE,
  326. );
  327. $form['instance']['years_back_and_forward'] = array(
  328. '#type' => 'fieldset',
  329. '#title' => t('Starting and ending year'),
  330. '#collapsible' => TRUE,
  331. '#collapsed' => FALSE,
  332. );
  333. $form['instance']['#pre_render'][] = 'date_field_ui_field_edit_form_pre_render';
  334. }
  335. /**
  336. * Rearrange form elements into fieldsets for presentation only.
  337. */
  338. function date_field_ui_field_edit_form_pre_render($form) {
  339. foreach ($form as $name => $element) {
  340. if (is_array($element) && isset($element['#fieldset'])) {
  341. $fieldset = $element['#fieldset'];
  342. $form[$fieldset][$name] = $element;
  343. unset($form[$name]);
  344. }
  345. }
  346. foreach (array('date_format', 'default_values', 'years_back_and_forward') as $name) {
  347. if (element_children($form[$name])) {
  348. // Force the items in the fieldset to be resorted now that the instance
  349. // and widget settings are combined.
  350. $form[$name]['#sorted'] = FALSE;
  351. $form['defaults'][$name] = $form[$name];
  352. }
  353. unset($form[$name]);
  354. }
  355. return $form;
  356. }
  357. /**
  358. * Implements hook_field_widget_error().
  359. */
  360. function date_field_widget_error($element, $error, $form, &$form_state) {
  361. form_error($element[$error['error']], $error['message']);
  362. }
  363. /**
  364. * Retrieve a date format string from formatter settings.
  365. */
  366. function date_formatter_format($formatter, $settings, $granularity = array(), $langcode = NULL) {
  367. $format_type = !empty($settings['format_type']) ? $settings['format_type'] : 'format_interval';
  368. switch ($formatter) {
  369. case 'format_interval':
  370. return 'format_interval';
  371. break;
  372. case 'date_plain':
  373. return 'date_plain';
  374. break;
  375. default:
  376. $format = date_format_type_format($format_type, $langcode);
  377. break;
  378. }
  379. // A selected format might include timezone information.
  380. array_push($granularity, 'timezone');
  381. return date_limit_format($format, $granularity);
  382. }
  383. /**
  384. * Helper function to get the right format for a format type.
  385. * Checks for locale-based format first.
  386. */
  387. function date_format_type_format($format_type, $langcode = NULL) {
  388. $static = &drupal_static(__FUNCTION__);
  389. if (!isset($static[$langcode][$format_type])) {
  390. $format = system_date_format_locale($langcode, $format_type);
  391. // If locale enabled and $format_type inexistent in {date_format_locale}
  392. // we receive (due to inconsistency of core api) an array of all (other)
  393. // formats available for $langcode in locale table.
  394. // However there's no guarantee that the key $format_type exists.
  395. // See http://drupal.org/node/1302358.
  396. if (!is_string($format)) {
  397. // If the configuration page at admin/config/regional/date-time was
  398. // never saved, the default core date format variables
  399. // ('date_format_short', 'date_format_medium', and 'date_format_long')
  400. // will not be stored in the database, so we have to define their
  401. // expected defaults here.
  402. switch ($format_type) {
  403. case 'short':
  404. $default = 'm/d/Y - H:i';
  405. break;
  406. case 'long':
  407. $default = 'l, F j, Y - H:i';
  408. break;
  409. // If it's not one of the core date types and isn't stored in the
  410. // database, we'll fall back on using the same default format as the
  411. // 'medium' type.
  412. case 'medium':
  413. default:
  414. // @todo: If a non-core module provides a date type and does not
  415. // variable_set() a default for it, the default assumed here may
  416. // not be correct (since the default format used by 'medium' may
  417. // not even be one of the allowed formats for the date type in
  418. // question). To fix this properly, we should really call
  419. // system_get_date_formats($format_type) and take the first
  420. // format from that list as the default. However, this function
  421. // is called often (on many different page requests), so calling
  422. // system_get_date_formats() from here would be a performance hit
  423. // since that function writes several records to the database
  424. // during each page request that calls it.
  425. $default = 'D, m/d/Y - H:i';
  426. break;
  427. }
  428. $format = variable_get('date_format_' . $format_type, $default);
  429. }
  430. $static[$langcode][$format_type] = $format;
  431. }
  432. return $static[$langcode][$format_type];
  433. }
  434. /**
  435. * Helper function to adapt entity date fields to formatter settings.
  436. */
  437. function date_prepare_entity($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display) {
  438. // If there are options to limit multiple values,
  439. // alter the entity values to match.
  440. $field_name = $field['field_name'];
  441. $options = $display['settings'];
  442. $max_count = $options['multiple_number'];
  443. // If no results should be shown, empty the values and return.
  444. if (is_numeric($max_count) && $max_count == 0) {
  445. $entity->{$field_name} = array();
  446. return $entity;
  447. }
  448. // Otherwise removed values that should not be displayed.
  449. if (!empty($options['multiple_from']) || !empty($options['multiple_to']) || !empty($max_count)) {
  450. $format = date_type_format($field['type']);
  451. include_once drupal_get_path('module', 'date_api') . '/date_api_sql.inc';
  452. $date_handler = new date_sql_handler($field);
  453. $arg0 = !empty($options['multiple_from']) ? $date_handler->arg_replace($options['multiple_from']) : variable_get('date_min_year', 100) . '-01-01T00:00:00';
  454. $arg1 = !empty($options['multiple_to']) ? $date_handler->arg_replace($options['multiple_to']) : variable_get('date_max_year', 4000) . '-12-31T23:59:59';
  455. if (!empty($arg0) && !empty($arg1)) {
  456. $arg = $arg0 . '--' . $arg1;
  457. }
  458. elseif (!empty($arg0)) {
  459. $arg = $arg0;
  460. }
  461. elseif (!empty($arg1)) {
  462. $arg = $arg1;
  463. }
  464. if (!empty($arg)) {
  465. $range = $date_handler->arg_range($arg);
  466. $start = date_format($range[0], $format);
  467. $end = date_format($range[1], $format);
  468. // Empty out values we don't want to see.
  469. $count = 0;
  470. foreach ($entity->{$field_name}[$langcode] as $delta => $value) {
  471. if (!empty($entity->date_repeat_show_all)) {
  472. break;
  473. }
  474. elseif ((!empty($max_count) && is_numeric($max_count) && $count >= $max_count) ||
  475. (!empty($value['value']) && $value['value'] < $start) ||
  476. (!empty($value['value2']) && $value['value2'] > $end)) {
  477. unset($entity->{$field_name}[$langcode][$delta]);
  478. }
  479. else {
  480. $count++;
  481. }
  482. }
  483. }
  484. }
  485. return $entity;
  486. }
  487. /**
  488. * Callback to alter the property info of date fields.
  489. *
  490. * @see date_field_info()
  491. */
  492. function date_entity_metadata_property_info_alter(&$info, $entity_type, $field, $instance, $field_type) {
  493. $name = $field['field_name'];
  494. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];
  495. if ($field['type'] != 'datestamp' || $field['settings']['timezone_db'] != 'UTC') {
  496. // Add a getter callback to convert the date into the right format.
  497. $property['getter callback'] = 'date_entity_metadata_field_getter';
  498. $property['setter callback'] = 'date_entity_metadata_field_setter';
  499. unset($property['query callback']);
  500. }
  501. if (!empty($field['settings']['todate'])) {
  502. // Define a simple data structure containing both dates.
  503. $property['type'] = ($field['cardinality'] != 1) ? 'list<struct>' : 'struct';
  504. $property['auto creation'] = 'date_entity_metadata_struct_create';
  505. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  506. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  507. $property['property info'] = array(
  508. 'value' => array(
  509. 'type' => 'date',
  510. 'label' => t('Start date'),
  511. 'getter callback' => 'date_entity_metadata_struct_getter',
  512. 'setter callback' => 'date_entity_metadata_struct_setter',
  513. // The getter and setter callbacks for 'value' and 'value2'
  514. // will not provide the field name as $name, we'll add it to $info.
  515. 'field_name' => $field['field_name'],
  516. // Alert Microdata module that this value can be exposed in microdata.
  517. 'microdata' => TRUE,
  518. ),
  519. 'value2' => array(
  520. 'type' => 'date',
  521. 'label' => t('End date'),
  522. 'getter callback' => 'date_entity_metadata_struct_getter',
  523. 'setter callback' => 'date_entity_metadata_struct_setter',
  524. // The getter and setter callbacks for 'value' and 'value2'
  525. // will not provide the field name as $name, we'll add it to $info.
  526. 'field_name' => $field['field_name'],
  527. // Alert Microdata module that this value can be exposed in microdata.
  528. 'microdata' => TRUE,
  529. ),
  530. 'duration' => array(
  531. 'type' => 'duration',
  532. 'label' => t('Duration'),
  533. 'desription' => t('The duration of the time period given by the dates.'),
  534. 'getter callback' => 'date_entity_metadata_duration_getter',
  535. // No setter callback for duration.
  536. // The getter callback for duration will not provide the field name
  537. // as $name, we'll add it to $info.
  538. 'field_name' => $field['field_name'],
  539. ),
  540. );
  541. unset($property['query callback']);
  542. }
  543. else {
  544. // If this doesn't have a todate, it is handled as a date rather than a
  545. // struct. Enable microdata on the field itself rather than the properties.
  546. $property['microdata'] = TRUE;
  547. }
  548. }
  549. /**
  550. * Getter callback to return date values as datestamp in UTC from the field.
  551. */
  552. function date_entity_metadata_field_getter($entity, array $options, $name, $entity_type, &$context) {
  553. $return = entity_metadata_field_verbatim_get($entity, $options, $name, $entity_type, $context);
  554. $items = ($context['field']['cardinality'] == 1) ? array($return) : $return;
  555. foreach ($items as $key => $item) {
  556. $items[$key] = date_entity_metadata_struct_getter($item, $options, 'value', 'struct', $context);
  557. }
  558. return ($context['field']['cardinality'] == 1) ? $items[0] : $items;
  559. }
  560. /**
  561. * Getter callback to return date values as datestamp in UTC.
  562. */
  563. function date_entity_metadata_struct_getter($item, array $options, $name, $type, $info) {
  564. $value = trim($item[$name]);
  565. if (empty($value)) {
  566. return NULL;
  567. }
  568. $timezone_db = !empty($item['timezone_db']) ? $item['timezone_db'] : 'UTC';
  569. $date = new DateObject($value, $timezone_db);
  570. return !empty($date) ? date_format_date($date, 'custom', 'U') : NULL;
  571. }
  572. /**
  573. * Getter callback to return the duration of the time period given by the dates.
  574. */
  575. function date_entity_metadata_duration_getter($item, array $options, $name, $type, $info) {
  576. $value = date_entity_metadata_struct_getter($item, $options, 'value', 'struct', $info);
  577. $value2 = date_entity_metadata_struct_getter($item, $options, 'value2', 'struct', $info);
  578. if ($value && $value2) {
  579. return $value2 - $value;
  580. }
  581. }
  582. /**
  583. * Callback for setting field property values.
  584. *
  585. * Based on entity_metadata_field_property_set(), the original property setter,
  586. * adapted to transform non-timestamp date values to timestamps.
  587. */
  588. function date_entity_metadata_field_setter(&$entity, $name, $value, $langcode, $entity_type, $info) {
  589. $field = field_info_field($name);
  590. if (!isset($langcode)) {
  591. // Try to figure out the default language used by the entity.
  592. // @todo: Update once http://drupal.org/node/1260640 has been fixed.
  593. $langcode = isset($entity->language) ? $entity->language : LANGUAGE_NONE;
  594. }
  595. $values = $field['cardinality'] == 1 ? array($value) : (array) $value;
  596. $items = array();
  597. foreach ($values as $delta => $value) {
  598. // Make use of the struct setter to convert the date back to a timestamp.
  599. $info['field_name'] = $name;
  600. date_entity_metadata_struct_setter($items[$delta], 'value', $value, $langcode, 'struct', $info);
  601. }
  602. $entity->{$name}[$langcode] = $items;
  603. // Empty the static field language cache, so the field system picks up any
  604. // possible new languages.
  605. drupal_static_reset('field_language');
  606. }
  607. /**
  608. * Auto creation callback for fields which contain two date values in one
  609. */
  610. function date_entity_metadata_struct_create($name, $property_info) {
  611. return array(
  612. 'date_type' => $property_info['field']['columns'][$name]['type'],
  613. 'timezone_db' => $property_info['field']['settings']['timezone_db'],
  614. );
  615. }
  616. /**
  617. * Callback for setting an individual field value if a to-date may be there too.
  618. * Based on entity_property_verbatim_set().
  619. *
  620. * The passed in unix timestamp (UTC) is converted to the right value and
  621. * format dependent on the field.
  622. *
  623. * $name is either 'value' or 'value2'.
  624. */
  625. function date_entity_metadata_struct_setter(&$item, $name, $value, $langcode, $type, $info) {
  626. if (!isset($value)) {
  627. $item[$name] = NULL;
  628. }
  629. else {
  630. $field = field_info_field($info['field_name']);
  631. $format = date_type_format($field['type']);
  632. $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
  633. $date = new DateObject($value, 'UTC');
  634. if ($timezone_db != 'UTC') {
  635. date_timezone_set($date, timezone_open($timezone_db));
  636. }
  637. $item[$name] = $date->format($format);
  638. }
  639. }
  640. /**
  641. * Duplicate functionality of what is now date_all_day_field() in
  642. * the Date All Day module. Copy left here to avoid breaking other
  643. * modules that use this function.
  644. *
  645. * DEPRECATED!, will be removed at some time in the future.
  646. */
  647. function date_field_all_day($field, $instance, $date1, $date2 = NULL) {
  648. if (empty($date1) || !is_object($date1)) {
  649. return FALSE;
  650. }
  651. elseif (!date_has_time($field['settings']['granularity'])) {
  652. return TRUE;
  653. }
  654. if (empty($date2)) {
  655. $date2 = $date1;
  656. }
  657. $granularity = date_granularity_precision($field['settings']['granularity']);
  658. $increment = isset($instance['widget']['settings']['increment']) ? $instance['widget']['settings']['increment'] : 1;
  659. return date_is_all_day(date_format($date1, DATE_FORMAT_DATETIME), date_format($date2, DATE_FORMAT_DATETIME), $granularity, $increment);
  660. }
  661. /**
  662. * Generates a Date API SQL handler for the given date field.
  663. *
  664. * The handler will be set up to make the correct timezone adjustments
  665. * for the field settings.
  666. *
  667. * @param array $field
  668. * The $field array.
  669. * @param string $compare_tz
  670. * The timezone used for comparison values in the SQL.
  671. *
  672. * DEPRECATED!, will be removed at some time in the future.
  673. */
  674. function date_field_get_sql_handler($field, $compare_tz = NULL) {
  675. module_load_include('inc', 'date_api', 'date_api_sql');
  676. $db_info = date_api_database_info($field);
  677. // Create a DateAPI SQL handler class for this field type.
  678. $handler = new date_sql_handler($field['type']);
  679. // If this date field stores a timezone in the DB, tell the handler about it.
  680. if ($field['settings']['tz_handling'] == 'date') {
  681. $handler->db_timezone_field = $db_info['columns']['timezone']['column'];
  682. }
  683. else {
  684. $handler->db_timezone = date_get_timezone_db($field['settings']['tz_handling']);
  685. }
  686. if (empty($compare_tz)) {
  687. $compare_tz = date_get_timezone($field['settings']['tz_handling']);
  688. }
  689. $handler->local_timezone = $compare_tz;
  690. // Now that the handler is properly initialized, force the DB
  691. // to use UTC so no timezone conversions get added to things like
  692. // NOW() or FROM_UNIXTIME().
  693. $handler->set_db_timezone();
  694. return $handler;
  695. }
  696. /**
  697. * Implements hook_field_widget_properties_alter().
  698. *
  699. * Alters the widget properties of a field instance before it gets displayed.
  700. * Used here to flag new entities so we can later tell if they need default values.
  701. */
  702. function date_field_widget_properties_alter(&$widget, $context) {
  703. if (in_array($widget['type'], array('date_select', 'date_text', 'date_popup'))) {
  704. $entity_type = $context['entity_type'];
  705. $entity = $context['entity'];
  706. $info = entity_get_info($entity_type);
  707. $id = $info['entity keys']['id'];
  708. $widget['is_new']= FALSE;
  709. if (empty($entity->$id)) {
  710. $widget['is_new'] = TRUE;
  711. }
  712. }
  713. }