date.module 29 KB

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