diff --git a/core/includes/common.inc b/core/includes/common.inc index 47e9f95..cec08ae 100644 --- a/core/includes/common.inc +++ b/core/includes/common.inc @@ -7,6 +7,7 @@ use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Database\Database; use Drupal\Core\Template\Attribute; +use Drupal\Core\Datetime\DrupalDateTime; /** * @file @@ -1997,26 +1998,12 @@ function format_date($timestamp, $type = 'medium', $format = '', $timezone = NUL break; } - // Create a DateTime object from the timestamp. - $date_time = date_create('@' . $timestamp); - // Set the time zone for the DateTime object. - date_timezone_set($date_time, $timezones[$timezone]); - - // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'. - // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the - // input string. - // Paired backslashes are isolated to prevent errors in read-ahead evaluation. - // The read-ahead expression ensures that A matches, but not \A. - $format = preg_replace(array('/\\\\\\\\/', '/(? $langcode); + return $date_time->format($format, $settings); } /** @@ -2037,6 +2024,65 @@ function date_iso8601($date) { } /** + * Handle a string like -3:+3 or 2001:2010 to describe a dynamic range + * of minimum and maximum years to use in a date selector. + * + * Center the range around the current year, if any, but expand it far + * enough so it will pick up the year value in the field in case + * the value in the field is outside the initial range. + * + * @param string $string + * A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'. + * @param object $date + * (optional) A date object to test as a default value. Defaults to NULL. + * + * @return array + * A numerically indexed array, containing the minimum and maximum + * year described by this pattern. + */ +function date_range_years($string, $date = NULL) { + + // We use the full path to the date class to avoid the need to + // include this file when not being used. + $this_year = date_format(new \Drupal\Core\Datetime\DrupalDateTime(), 'Y'); + list($min_year, $max_year) = explode(':', $string); + + // Valid patterns would be -5:+5, 0:+1, 2008:2010. + $plus_pattern = '@[\+|\-][0-9]{1,4}@'; + $year_pattern = '@^[0-9]{4}@'; + if (!preg_match($year_pattern, $min_year, $matches)) { + if (preg_match($plus_pattern, $min_year, $matches)) { + $min_year = $this_year + $matches[0]; + } + else { + $min_year = $this_year; + } + } + if (!preg_match($year_pattern, $max_year, $matches)) { + if (preg_match($plus_pattern, $max_year, $matches)) { + $max_year = $this_year + $matches[0]; + } + else { + $max_year = $this_year; + } + } + // We expect the $min year to be less than the $max year. + // Some custom values for -99:+99 might not obey that. + if ($min_year > $max_year) { + $temp = $max_year; + $max_year = $min_year; + $min_year = $temp; + } + // If there is a current value, stretch the range to include it. + $value_year = $date instanceOf \Drupal\Core\Datetime\DrupalDateTime ? $date->format('Y') : ''; + if (!empty($value_year)) { + $min_year = min($value_year, $min_year); + $max_year = max($value_year, $max_year); + } + return array($min_year, $max_year); +} + +/** * Translates a formatted date string. * * Callback for preg_replace_callback() within format_date(). @@ -5004,7 +5050,8 @@ function drupal_page_set_cache($body) { $cache->data['headers'][$header_names[$name_lower]] = $value; if ($name_lower == 'expires') { // Use the actual timestamp from an Expires header if available. - $cache->expire = strtotime($value); + $date = new DrupalDateTime($value); + $cache->expire = $date->getTimestamp(); } } diff --git a/core/includes/form.inc b/core/includes/form.inc index 6956f04..4534611 100644 --- a/core/includes/form.inc +++ b/core/includes/form.inc @@ -7,6 +7,7 @@ use Drupal\Core\Utility\Color; use Drupal\Core\Template\Attribute; +use Drupal\Core\Datetime\DrupalDateTime; /** * @defgroup forms Form builder functions @@ -2922,7 +2923,9 @@ function password_confirm_validate($element, &$element_state) { } /** - * Returns HTML for a date selection form element. + * Returns HTML for an individual date html5 form element. + * Supports 'date', 'datetime', 'datetime-local', and 'time', + * falls back to a plain textfield. * * @param $variables * An associative array containing: @@ -2934,6 +2937,29 @@ function password_confirm_validate($element, &$element_state) { */ function theme_date($variables) { $element = $variables['element']; + if (empty($element['attribute']['type'])) { + $element['attribute']['type'] = 'date'; + } + element_set_attributes($element, array('id', 'name', 'type', 'min', 'max', 'step', 'value', 'size')); + _form_set_attributes($element, array('form-text', 'form-' . $element['attribute']['type'])); + + return ''; +} + +/** + * Returns HTML for a HTML5-compatible combination date/time form element. + * + * @param $variables + * An associative array containing: + * - element: An associative array containing the properties of the element. + * Properties used: #title, #value, #options, #description, #required, + * #attributes. + * + * @ingroup themeable + */ +function theme_form_datetime($variables) { + + $element = $variables['element']; $attributes = array(); if (isset($element['#id'])) { @@ -2948,91 +2974,478 @@ function theme_date($variables) { } /** - * Expands a date element into year, month, and day select elements. + * Expands a date element into 'date' and/or 'time' elements. All form + * elements are designed to have sane defaults so any or all can be + * omitted. Both the 'date' and 'time' components are configurable + * so they can be output as HTML5 datetime elements or not, as + * desired. + * + * Examples of possible configurations include: + * HTML5: + * Date: 'date'; Time: 'time' + * Date: 'datetime'; Time: 'none' + * Date: 'datetime-local'; Time: 'none' + * Date: 'none'; Time: 'time' + * Non-HTML5: + * Date: 'text'; Time: 'text' + * Date: 'text'; Time: 'none' + * + * Required settings: + * #default_value + * The default value should be expressed in ISO datetime format, + * using the format used by DrupalDateTime's __toString() function. + * Provide a date with or without a timzone name appended to it, + * adjusted to the proper local timezone, i.e. '2012-01-31 10:30:00 + * America/Chicago'. NOTE - Converting a date stored in the database + * from UTC to the local zone and converting it back to UTC before + * storing it is not handled here. This element simply explodes and + * displays the string date that is provided to it and converts the + * user input back into a string value on submission. + * Optional properties include: + * #date_date_format + * A date format string that describes the format that should + * be displayed to the end user for the date. When using HTML5 + * elements the format MUST use the appropriate HTML5 format + * for that element, no other format will work. See the + * format_date() function for a list of the possible formats. + * Defaults to variable_get('date_format_html_date', 'Y-m-d'). + * #date_date_element + * The HTML5 date part to use for the date element. Options are: + * - datetime + * - datetime-local + * - date + * - text (no HTML5 element) + * - none (do not display) + * #date_date_callbacks + * Array of optional callbacks for the date element. Can be used + * to add a jQuery datepicker, for instance. Drupal provides the + * 'datetime_jquery_datepicker_callback' as one possible choice + * for this property. + * #date_time_format + * A date format string that describes the format that should + * be displayed to the end user for the time. When using HTML5 + * elements the format MUST use the appropriate HTML5 format + * for that element, no other format will work. See the + * format_date() function for a list of the possible formats. + * Defaults to variable_get('date_format_html_time', 'H:i:s'). + * #date_time_element + * The HTML5 date part to use for the time element. Options are: + * - time + * - text (no HTML5 element) + * - none (do not display) + * #date_time_callbacks + * An array of optional callbacks for the time element. Can be used + * to add a jQuery timepicker or an 'All day' checkbox. + * See the core Timestamp field as an example of that. + * #date_year_range + * A description of the range of years to allow, like '1900:2050', + * '-3:+3' or '2000:+3', where the first value describes the earliest + * year and the second the latest year in the range. A year + * in either position means that specific year. A +/- value + * describes a dynamic value that is that many years earlier or + * later than the current year at the time the form is displayed. + * Used in jQueryUI datepicker and HTML5 settings. + * Defaults to '1900:2050'. + * #date_increment + * The increment to use for minutes and seconds, i.e. '15' would show + * only :00, :15, :30 and :45. Used for HTML5 step values and + * jQueryUI datepicker and HTML5 settings. + * Defaults to 1 to show every minute and second. + * #date_timezone + * The local timezone to use when creating dates with the defaul_value + * of this element. Generally this should be left empty and + * it will be set correctly for the user using the form. Useful + * if the default_value has no timezone. If the default_value + * includes both a date and a timezone, this value will be ignored. + * Defaults to drupal_get_user_timezone(). + * + * Example: + * $form = array( + * '#type' => 'datetime', + * '#default_value' => '2000-01-01 10:30:00', + * '#date_date_callbacks' => array('datetime_jquery_datepicker_callback'), + * '#date_year_range' => '2010:2020', + * ); */ -function form_process_date($element) { - // Default to current date - if (empty($element['#value'])) { - $element['#value'] = array( - 'day' => format_date(REQUEST_TIME, 'custom', 'j'), - 'month' => format_date(REQUEST_TIME, 'custom', 'n'), - 'year' => format_date(REQUEST_TIME, 'custom', 'Y'), - ); - } +function form_process_datetime($element, &$form_state) { + + // Set a fallback timezone. + $element['#date_timezone'] = !empty($element['#timezone']) ? $element['#date_timezone'] : drupal_get_user_timezone(); + + // The value callback has attempted to create a date object and + // populated the #value array. + $date = !empty($element['#value']['object']) ? $element['#value']['object'] : NULL; $element['#tree'] = TRUE; - // Determine the order of day, month, year in the site's chosen date format. - $format = variable_get('date_format_short', 'm/d/Y - H:i'); - $sort = array(); - $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j')); - $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M')); - $sort['year'] = strpos($format, 'Y'); - asort($sort); - $order = array_keys($sort); - - // Output multi-selector for date. - foreach ($order as $type) { - switch ($type) { - case 'day': - $options = drupal_map_assoc(range(1, 31)); - $title = t('Day'); - break; - - case 'month': - $options = drupal_map_assoc(range(1, 12), 'map_month'); - $title = t('Month'); - break; - - case 'year': - $options = drupal_map_assoc(range(1900, 2050)); - $title = t('Year'); - break; - } - - $element[$type] = array( - '#type' => 'select', - '#title' => $title, + if ($element['#date_date_element'] != 'none') { + + $date_format = $element['#date_date_element'] != 'none' ? datetime_get_format('date', $element) : ''; + $date_value = !empty($date) ? $date->format($date_format) : $element['#value']['date']; + + // Creating format examples on every individual date item is messy, + // and placeholders are invalid for HTML5 date and datetime, so an + // example format is appended to the title to appear in tooltips. + $extra_attributes = array( + 'title' => t('Date (i.e. %format)', array('%format' => datetime_format_example($date_format))), + 'type' => $element['#date_date_element'], + ); + + // Add the HTML5 date attributes. + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + $html5_min = clone($date); + $range = date_range_years($element['#date_year_range'], $date); + $html5_min->setDate($range[0], 1, 1)->setTime(0, 0, 0); + $html5_max = clone($date); + $html5_max->setDate($range[1], 12, 31)->setTime(23, 59, 59); + + $extra_attributes += array( + 'min' => $html5_min->format($date_format), + 'max' => $html5_max->format($date_format), + ); + } + + $element['date'] = array( + '#type' => 'date', + '#title' => t('Date'), '#title_display' => 'invisible', - '#value' => $element['#value'][$type], - '#attributes' => $element['#attributes'], - '#options' => $options, + '#value' => $date_value, + '#attributes' => $element['#attributes'] + $extra_attributes, + '#required' => $element['#required'], + '#size' => max(12, strlen($element['#value']['date'])), ); + + // Allow custom callbacks to alter the element. + if (!empty($element['#date_date_callbacks'])) { + foreach ($element['#date_date_callbacks'] as $callback) { + if (function_exists($callback)) { + $callback($element, $form_state, $date); + } + } + } } + if ($element['#date_time_element'] != 'none') { + + $time_format = $element['#date_time_element'] != 'none' ? datetime_get_format('time', $element) : ''; + $time_value = !empty($date) ? $date->format($time_format) : $element['#value']['time']; + + // Add the HTML5 attributes. + $extra_attributes = array( + 'title' =>t('Time (i.e. %format)', array('%format' => datetime_format_example($time_format))), + 'type' => $element['#date_time_element'], + 'step' => ($element['#date_increment'] * 60), + ); + $element['time'] = array( + '#type' => 'date', + '#title' => t('Time'), + '#title_display' => 'invisible', + '#value' => $time_value, + '#attributes' => $element['#attributes'] + $extra_attributes, + '#required' => $element['#required'], + '#size' => 12, + ); + + // Allow custom callbacks to alter the element. + if (!empty($element['#date_time_callbacks'])) { + foreach ($element['#date_time_callbacks'] as $callback) { + if (function_exists($callback)) { + $callback($element, $form_state, $date); + } + } + } + } return $element; } /** - * Validates the date type to prevent invalid dates (e.g., February 30, 2006). + * Helper function to create a valid date from a string value and the + * properties in an $element. + */ +function datetime_create_element_date($time, $element) { + + $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : drupal_get_user_timezone(); + $date = new DrupalDateTime($time, $timezone, datetime_full_format($element)); + + // If the created date has errors, we can't use it. + if (!$date instanceOf DrupalDateTime || $date->hasErrors()) { + $date = NULL; + } + else { + + // The timezone of the actual date we create might differ from the value + // in #date_timezone, for instance if the input string includes a timezone + // name or a timestamp. No matter what, the timezone of the created date + // will be the 'right' timezone for this date, so update the + // value in #date_timezone to reflect that. + $parts = date_parse($date->__toString()); + + // If this date has a valid timezone, prefer it over anything else. + // A zone_type of '3' is a complete timezone name. Other + // zone_types are offsets or timezone abbreviations, which are + // ambiguous so we won't use them. + if ($parts['zone_type'] == 3 && !empty($parts['tz_id'])) { + $element['#date_timezone'] = $parts['tz_id']; + } + } + return $date; +} + +/** + * Value callback for a datetime element. + * + * @param $element + * The form element whose value is being populated. + * @param $input + * The incoming input to populate the form element. If this is FALSE, + * the element's default value should be returned. + * + * @return + * The data that will appear in the $element_state['values'] collection + * for this element. Return nothing to use the default. + */ +function form_type_datetime_value($element, $input = FALSE) { + + if ($input !== FALSE) { + $date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : ''; + $time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : ''; + $date = datetime_create_element_date(trim($date_input . ' ' . $time_input), $element); + $input = array( + 'date' => $date_input, + 'time' => $time_input, + 'object' => $date instanceOf DrupalDateTime && !$date->hasErrors() ? $date : NULL, + ); + } + else { + $date = datetime_create_element_date($element['#default_value'], $element); + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + $input = array( + 'date' => $date->format($element['#date_date_format']), + 'time' => $date->format($element['#date_time_format']), + 'object' => $date, + ); + } + else { + $input = array( + 'date' => '', + 'time' => '', + 'object' => NULL, + ); + } + } + return $input; +} + +/** + * Validates the date and sets errors. + * + * If the date is valid, the date is set in the form as a string + * using the format designated in __toString(). */ -function date_validate($element) { - if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) { - form_error($element, t('The specified date is invalid.')); +function datetime_validate($element, &$form_state) { + + $input_exists = FALSE; + $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists); + if ($input_exists) { + + $title = !empty($element['#title']) ? $element['#title'] : ''; + $format = datetime_full_format($element); + + // If there's empty input and the field is not required, set it to empty. + if (empty($input['date']) && empty($input['time']) && !$element['#required']) { + form_set_value($element, NULL, $form_state); + } + // If there's empty input and the field is required, set an error. + // A reminder of the required format in the message is a better UX. + elseif (empty($input['date']) && empty($input['time']) && $element['#required']) { + form_error($element, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); + } + else { + // If there's a date with no errors, set the value. + $date = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : ''; + $time = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : ''; + if ($date = datetime_create_element_date(trim($date . ' ' . $time), $element)) { + form_set_value($element, $date->__toString(), $form_state); + } + // If the input is invalid, set an error. A reminder of the required + // format in the message is a better UX. + else { + form_error($element, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); + } + } } } /** - * Renders a month name for display. + * Callback to add the jQuery datepicker to a date element. + * The javascript in drupal.datepicker will check first for HTML5 + * compliance, and then apply the jQuery datepicker as a fallback, + * only if the HTML5 widget is not supported. + * + * @param array $element + * The 'date' element being altered. + * @param array $form_state + * The form state array. + * @param object $date + * The date object being manipulated by this element. + */ +function datetime_jquery_datepicker_callback(&$element, &$form_state, $date) { + + // Get the format used by the element, and then convert it to + // the format needed by the datepicker. + $element_format = datetime_get_format('date', $element); + $datepicker_format = datepicker_get_format($element_format); + + // Make sure the date range includes the current year to avoid odd + // behavior when the datepicker doesn't find it in the date range. + // The date_range_years function will ensure the current date is + // included in the range. + $range = date_range_years($element['#date_year_range'], $date); + + $settings = array( + 'changeMonth' => 'true', + 'changeYear' => 'true', + 'autoPopUp' => 'focus', + 'closeAtTop' => 'false', + 'speed' => 'immediate', + 'firstDay' => intval(variable_get('date_first_day', 0)), + 'dateFormat' => $datepicker_format, + 'yearRange' => $range[0] . ':' . $range[1], + ); + + // There could be an unknown number of instances of the datepicker + // on any page. Set a unique id for each element and its settings. + $new_id = datepicker_settings_id($element['#id'], $settings, $date); + $element['date']['#id'] = $new_id; + + $js_settings = array( + 'type' => 'setting', + 'data' => array( + 'dateTime' => array( + '#' . $new_id => $settings, + ), + ), + ); + $element['#attached']['js'][] = $js_settings; + $element['#attached']['library'][] = array('system', 'jquery.ui.datepicker'); + $element['#attached']['library'][] = array('system', 'drupal.datepicker'); +} + +/** + * A central function and static for creating a unique id for as + * many datepicker elements as might be created, to be used by multiple + * datepicker elements across a page request. + * + * @param $id + * The id of the element that contains the datepicker. + * @param $settings + * The settings array to pass to the jQuery function. + * + * @returns + * The CSS id to assign to the element that should have + * $func($settings) invoked on it. + */ +function datepicker_settings_id($id, &$settings, $date) { + static $id_count = array(); + + // We use a static array to account for possible multiple form_builder() + // calls in the same request (for instance on 'Preview') and when + // there are multiple values, as with multiple value fields. + + if (!isset($id_count[$id])) { + $id_count[$id] = 0; + } + return "$id-datepicker-" . $id_count[$id]++; +} + +/** + * Alter the format string for the jQuery datepicker. + * Used to transform a date format that uses the PHP format + * strings to the format used by the datepicker. * - * Callback for drupal_map_assoc() within form_process_date(). + * @param string $format + * A standard PHP format string. + * + * @return string + * Returns the format string formatted correctly for the jQuery + * timepicker. */ -function map_month($month) { - $months = &drupal_static(__FUNCTION__, array( - 1 => 'Jan', - 2 => 'Feb', - 3 => 'Mar', - 4 => 'Apr', - 5 => 'May', - 6 => 'Jun', - 7 => 'Jul', - 8 => 'Aug', - 9 => 'Sep', - 10 => 'Oct', - 11 => 'Nov', - 12 => 'Dec', - )); - return t($months[$month]); +function datepicker_get_format($format) { + $replace = array( + 'd' => 'dd', + 'j' => 'd', + 'l' => 'DD', + 'D' => 'D', + 'm' => 'mm', + 'n' => 'm', + 'F' => 'MM', + 'M' => 'M', + 'Y' => 'yy', + 'y' => 'y', + ); + return strtr($format, $replace); +} + +/** + * Helper function to retrieve the right format for a HTML5 + * date element. Important because these elements will not + * work with any other format. + * + * @param string $part + * The type of element format to retrieve. + * @param string $element + * The $element to assess. + * + * @return string + * Returns the right format for the type of element, or + * the original format if this is not a HTML5 element. + */ +function datetime_get_format($part, $element) { + switch ($part) { + case 'date': + switch ($element['#date_date_element']) { + case 'date': + return variable_get('date_format_html_date', 'Y-m-d'); + case 'datetime': + case 'datetime-local': + return variable_get('date_format_html_datetime', 'Y-m-d\TH:i:sO'); + default: + return $element['#date_date_format']; + } + break; + case 'time': + switch ($element['#date_time_element']) { + case 'time': + return variable_get('date_format_html_time', 'H:i:s'); + default: + return $element['#date_time_format']; + } + break; + } +} + +/** + * Helper function to retrieve the expected format for a full date + * from $element values. Used to make sure we consistently + * concantonate the 'date' and 'time' formats back together. + */ +function datetime_full_format($element) { + $date_format = $element['#date_date_element'] != 'none' ? datetime_get_format('date', $element) : ''; + $time_format = $element['#date_time_element'] != 'none' ? datetime_get_format('time', $element) : ''; + return trim($date_format . ' ' . $time_format); +} + +/** + * Helper function to display a date format example. + * Centralized for a consistent method of creating + * these examples. + */ +function datetime_format_example($format) { + $date = &drupal_static(__FUNCTION__); + if (empty($date)) { + $date = new DrupalDateTime(); + } + return $date->format($format); } /** diff --git a/core/includes/theme.inc b/core/includes/theme.inc index cc29a98..3317929 100644 --- a/core/includes/theme.inc +++ b/core/includes/theme.inc @@ -3051,6 +3051,9 @@ function drupal_common_theme() { 'date' => array( 'render element' => 'element', ), + 'form_datetime' => array( + 'render element' => 'element', + ), 'exposed_filters' => array( 'render element' => 'form', ), diff --git a/core/lib/Drupal/Component/Datetime/DateTimePlus.php b/core/lib/Drupal/Component/Datetime/DateTimePlus.php new file mode 100644 index 0000000..4ce9e9e --- /dev/null +++ b/core/lib/Drupal/Component/Datetime/DateTimePlus.php @@ -0,0 +1,734 @@ + 2014, 'month => 4). + * Defaults to 'now'. + * @param mixed $timezone + * PHP DateTimeZone object, string or NULL allowed. + * Defaults to NULL. + * @param string $format + * PHP date() type format for parsing the input. This is recommended + * for specialized input with a known format. If provided the + * date will be created using the createFromFormat() method. + * Defaults to NULL. + * @see http://us3.php.net/manual/en/datetime.createfromformat.php + * @param array $settings + * - boolean $validate_format + * The format used in createFromFormat() allows slightly different + * values than format(). If we use an input format that works in + * both functions we can add a validation step to confirm that the + * date created from a format string exactly matches the input. + * We need to know if this can be relied on to do that validation. + * Defaults to TRUE. + * - string $langcode + * The two letter language code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $country + * The two letter country code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $calendar + * A calendar name to use for the date, Defaults to + * DateTimePlus::CALENDAR. + * - boolean $debug + * Leave evidence of the input values in the resulting object + * for debugging purposes. Defaults to FALSE. + */ + public function __construct($time = 'now', $timezone = NULL, $format = NULL, $settings = array()) { + + // Unpack settings. + $this->validateFormat = !empty($settings['validate_format']) ? $settings['validate_format'] : TRUE; + $this->langcode = !empty($settings['langcode']) ? $settings['langcode'] : NULL; + $this->country = !empty($settings['country']) ? $settings['country'] : NULL; + $this->calendar = !empty($settings['calendar']) ? $settings['calendar'] : static::CALENDAR; + + // Store the original input so it is available for validation. + $this->inputTimeRaw = $time; + $this->inputTimeZoneRaw = $timezone; + $this->inputFormatRaw = $format; + + // Massage the input values as necessary. + $this->prepareTime($time); + $this->prepareTimezone($timezone); + $this->prepareFormat($format); + + // Create a date as a clone of an input DateTime object. + if ($this->inputIsObject()) { + $this->constructFromObject(); + } + + // Create date from array of date parts. + elseif ($this->inputIsArray()) { + $this->constructFromArray(); + } + + // Create a date from a Unix timestamp. + elseif ($this->inputIsTimestamp()) { + $this->constructFromTimestamp(); + } + + // Create a date from a time string and an expected format. + elseif ($this->inputIsFormat()) { + $this->constructFromFormat(); + } + + // Create a date from any other input. + else { + $this->constructFallback(); + } + + // Clean up the error messages. + $this->checkErrors(); + $this->errors = array_unique($this->errors); + + // Now that we've validated the input, clean up the extra values. + if (empty($settings['debug'])) { + unset( + $this->inputTimeRaw, + $this->inputTimeAdjusted, + $this->inputTimeZoneRaw, + $this->inputTimeZoneAdjusted, + $this->inputFormatRaw, + $this->inputFormatAdjusted, + $this->validateFormat + ); + } + + } + + /** + * Implementation of __toString() for dates. The base DateTime + * class does not implement this. + * + * @see https://bugs.php.net/bug.php?id=62911 and + * http://www.serverphorums.com/read.php?7,555645 + */ + public function __toString() { + $format = static::FORMAT; + return $this->format($format) . ' ' . $this->getTimeZone()->getName(); + } + + /** + * Prepare the input value before trying to use it. + * Can be overridden to handle special cases. + * + * @param mixed $time + * An input value, which could be a timestamp, a string, + * a date object, or an array of date parts. + */ + protected function prepareTime($time) { + $this->inputTimeAdjusted = $time; + } + + /** + * Prepare the timezone before trying to use it. + * Most imporantly, make sure we have a valid timezone + * object before moving further. + * + * @param mixed $timezone + * Either a timezone name or a timezone object or NULL. + */ + protected function prepareTimezone($timezone) { + // If the input timezone is a valid timezone object, use it. + if ($timezone instanceOf \DateTimezone) { + $timezone_adjusted = $timezone; + } + + // When the passed-in time is a DateTime object with its own + // timezone, try to use the date's timezone. + elseif (empty($timezone) && $this->inputTimeAdjusted instanceOf \DateTime) { + $timezone_adjusted = $this->inputTimeAdjusted->getTimezone(); + } + + // Allow string timezone input, and create a timezone from it. + elseif (!empty($timezone) && is_string($timezone)) { + $timezone_adjusted = new \DateTimeZone($timezone); + } + + // Default to the system timezone when not explicitly provided. + // If the system timezone is missing, use 'UTC'. + if (empty($timezone_adjusted) || !$timezone_adjusted instanceOf \DateTimezone) { + $system_timezone = date_default_timezone_get(); + $timezone_name = !empty($system_timezone) ? $system_timezone : 'UTC'; + $timezone_adjusted = new \DateTimeZone($timezone_name); + } + + // We are finally certain that we have a usable timezone. + $this->inputTimeZoneAdjusted = $timezone_adjusted; + } + + /** + * Prepare the input format before trying to use it. + * Can be overridden to handle special cases. + * + * @param string $format + * A PHP format string. + */ + protected function prepareFormat($format) { + $this->inputFormatAdjusted = $format; + } + + /** + * Check if input is a DateTime object. + * + * @return boolean + * TRUE if the input time is a DateTime object. + */ + public function inputIsObject() { + return $this->inputTimeAdjusted instanceOf \DateTime; + } + + /** + * Create a date object from an input date object. + */ + protected function constructFromObject() { + try { + $this->inputTimeAdjusted = $this->inputTimeAdjusted->format(static::FORMAT); + parent::__construct($this->inputTimeAdjusted, $this->inputTimeZoneAdjusted); + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + /** + * Check if input time seems to be a timestamp. + * + * Providing an input format will prevent ISO values without separators + * from being mis-interpreted as timestamps. Providing a format can also + * avoid interpreting a value like '2010' with a format of 'Y' as a + * timestamp. The 'U' format indicates this is a timestamp. + * + * @return boolean + * TRUE if the input time is a timestamp. + */ + public function inputIsTimestamp() { + return is_numeric($this->inputTimeAdjusted) && (empty($this->inputFormatAdjusted) || $this->inputFormatAdjusted == 'U'); + } + + /** + * Create a date object from timestamp input. + * + * The timezone for timestamps is always UTC. In this case the + * timezone we set controls the timezone used when displaying + * the value using format(). + */ + protected function constructFromTimestamp() { + try { + parent::__construct('', $this->inputTimeZoneAdjusted); + $this->setTimestamp($this->inputTimeAdjusted); + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + /** + * Check if input is an array of date parts. + * + * @return boolean + * TRUE if the input time is a DateTime object. + */ + public function inputIsArray() { + return is_array($this->inputTimeAdjusted); + } + + /** + * Create a date object from an array of date parts. + * + * Convert the input value into an ISO date, forcing a full ISO + * date even if some values are missing. + */ + protected function constructFromArray() { + try { + parent::__construct('', $this->inputTimeZoneAdjusted); + $this->inputTimeAdjusted = static::prepareArray($this->inputTimeAdjusted, TRUE); + if (static::checkArray($this->inputTimeAdjusted)) { + // Even with validation, we can end up with a value that the + // parent class won't handle, like a year outside the range + // of -9999 to 9999, which will pass checkdate() but + // fail to construct a date object. + $this->inputTimeAdjusted = static::arrayToISO($this->inputTimeAdjusted); + parent::__construct($this->inputTimeAdjusted, $this->inputTimeZoneAdjusted); + } + else { + throw new \Exception('The array contains invalid values.'); + } + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + /** + * Check if input is a string with an expected format. + * + * @return boolean + * TRUE if the input time is a string with an expected format. + */ + public function inputIsFormat() { + return is_string($this->inputTimeAdjusted) && !empty($this->inputFormatAdjusted); + } + + /** + * Create a date object from an input format. + * + */ + protected function constructFromFormat() { + + // Try to create a date from the format and use it if possible. + // A regular try/catch won't work right here, if the value is + // invalid it doesn't return an exception. + try { + parent::__construct('', $this->inputTimeZoneAdjusted); + $date = parent::createFromFormat($this->inputFormatAdjusted, $this->inputTimeAdjusted, $this->inputTimeZoneAdjusted); + if (!$date instanceOf \DateTime) { + throw new \Exception('The date cannot be created from a format.'); + } + else { + $this->setTimestamp($date->getTimestamp()); + $this->setTimezone($date->getTimezone()); + + try { + // The createFromFormat function is forgiving, it might + // create a date that is not exactly a match for the provided + // value, so test for that. For instance, an input value of + // '11' using a format of Y (4 digits) gets created as + // '0011' instead of '2011'. + // Use the parent::format() because we do not want to use + // the IntlDateFormatter here. + if ($this->validateFormat && parent::format($this->inputFormatAdjusted) != $this->inputTimeRaw) { + throw new \Exception('The created date does not match the input value.'); + } + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + /** + * Fallback construction for values that don't match any of the + * other patterns. + * + * Let the parent dateTime attempt to turn this string into a + * valid date. + */ + protected function constructFallback() { + + try { + // One last test for invalid input before we try to construct + // a date. If the input contains totally bogus information + // it will blow up badly if we pass it to the constructor. + // The date_parse() function will tell us if the input + // makes sense. + if (!empty($this->inputTimeAdjusted)) { + $test = date_parse($this->inputTimeAdjusted); + if (!empty($test['errors'])) { + $this->errors[] = $test['errors']; + } + } + + if (empty($this->errors)) { + @parent::__construct($this->inputTimeAdjusted, $this->inputTimeZoneAdjusted); + } + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + /** + * Examine getLastErrors() and see what errors to report. + * + * We're interested in two kinds of errors: anything that DateTime + * considers an error, and also a warning that the date was invalid. + * PHP creates a valid date from invalid data with only a warning, + * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that. + * + * @see http://us3.php.net/manual/en/time.getlasterrors.php + */ + public function checkErrors() { + $errors = $this->getLastErrors(); + if (!empty($errors['errors'])) { + $this->errors += $errors['errors']; + } + // Most warnings are messages that the date could not be parsed + // which causes it to be altered. We're going to consider a warning + // as bad as an error. + if (!empty($errors['warnings'])) { + $this->errors[] = 'The date is invalid.'; + } + } + + /** + * Detect if there were errors in the processing of this date. + */ + public function hasErrors() { + return (boolean) count($this->errors); + } + + /** + * Public function to retrieve the error messages. + */ + public function getErrors() { + return $this->errors; + } + + /** + * Creates an ISO date from an array of values. + * + * @param array $array + * An array of date values keyed by date part. + * @param bool $force_valid_date + * (optional) Whether to force a full date by filling in missing + * values. Defaults to FALSE. + * + * @return string + * The date as an ISO string. + */ + public static function arrayToISO($array, $force_valid_date = FALSE) { + $array = static::prepareArray($array, $force_valid_date); + $input_time = ''; + if ($array['year'] !== '') { + $input_time = static::datePad(intval($array['year']), 4); + if ($force_valid_date || $array['month'] !== '') { + $input_time .= '-' . static::datePad(intval($array['month'])); + if ($force_valid_date || $array['day'] !== '') { + $input_time .= '-' . static::datePad(intval($array['day'])); + } + } + } + if ($array['hour'] !== '') { + $input_time .= $input_time ? 'T' : ''; + $input_time .= static::datePad(intval($array['hour'])); + if ($force_valid_date || $array['minute'] !== '') { + $input_time .= ':' . static::datePad(intval($array['minute'])); + if ($force_valid_date || $array['second'] !== '') { + $input_time .= ':' . static::datePad(intval($array['second'])); + } + } + } + return $input_time; + } + + /** + * Creates a complete array from a possibly incomplete array of date parts. + * + * @param array $array + * An array of date values keyed by date part. + * @param bool $force_valid_date + * (optional) Whether to force a valid date by filling in missing + * values with valid values or just to use empty values instead. + * Defaults to FALSE. + * + * @return array + * A complete array of date parts. + */ + public static function prepareArray($array, $force_valid_date = FALSE) { + if ($force_valid_date) { + $now = new \DateTime(); + $array += array( + 'year' => $now->format('Y'), + 'month' => 1, + 'day' => 1, + 'hour' => 0, + 'minute' => 0, + 'second' => 0, + ); + } + else { + $array += array( + 'year' => '', + 'month' => '', + 'day' => '', + 'hour' => '', + 'minute' => '', + 'second' => '', + ); + } + return $array; + } + + /** + * Check that an array of date parts has a year, month, and day, + * and that those values create a valid date. If time is provided, + * verify that the time values are valid. Sort of an + * equivalent to checkdate(). + * + * @param array $array + * An array of datetime values keyed by date part. + * + * @return boolean + * TRUE if the datetime parts contain valid values, otherwise FALSE. + */ + public static function checkArray($array) { + $valid_date = FALSE; + $valid_time = TRUE; + // Check for a valid date using checkdate(). Only values that + // meet that test are valid. + if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) { + if (@checkdate($array['month'], $array['day'], $array['year'])) { + $valid_date = TRUE; + } + } + // Testing for valid time is reversed. Missing time is OK, + // but incorrect values are not. + foreach (array('hour', 'minute', 'second') as $key) { + if (array_key_exists($key, $array)) { + $value = $array[$key]; + switch ($value) { + case 'hour': + if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) { + $valid_time = FALSE; + } + break; + case 'minute': + case 'second': + default: + if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) { + $valid_time = FALSE; + } + break; + } + } + } + return $valid_date && $valid_time; + } + + /** + * Helper function to left pad date parts with zeros. + * + * Provided because this is needed so often with dates. + * + * @param int $value + * The value to pad. + * @param int $size + * (optional) Size expected, usually 2 or 4. Defaults to 2. + * + * @return string + * The padded value. + */ + public static function datePad($value, $size = 2) { + return sprintf("%0" . $size . "d", $value); + } + + + /** + * Test if the IntlDateFormatter is available and we have the + * right information to be able to use it. + */ + public function canUseIntl() { + return class_exists('IntlDateFormatter') && !empty($this->calendar) && !empty($this->langcode) && !empty($this->country); + } + + /** + * Format the date for display. + * + * Use the IntlDateFormatter to display the format, if possible. + * Because the IntlDateFormatter is not always available, we + * add an optional array of settings that provides the information + * the IntlDateFormatter will need. + * + * @param string $format + * A format string using either PHP's date() or the + * IntlDateFormatter() format. + * @param array $settings + * - string $format_string_type + * Which pattern is used by the format string. When using the + * Intl formatter, the format string must use the Intl pattern, + * which is different from the pattern used by the DateTime + * format function. Defaults to DateTimePlus::PHP. + * - string $timezone + * A timezone name. Defaults to the timezone of the date object. + * - string $langcode + * The two letter language code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $country + * The two letter country code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $calendar + * A calendar name to use for the date, Defaults to + * DateTimePlus::CALENDAR. + * - int $date_type + * The date type to use in the formatter, defaults to + * IntlDateFormatter::FULL. + * - int $time_type + * The date type to use in the formatter, defaults to + * IntlDateFormatter::FULL. + * - boolean $lenient + * Whether or not to use lenient processing in the intl + * formatter. Defaults to FALSE; + * + * @return string + * The formatted value of the date. + */ + public function format($format, $settings = array()) { + + // If there were construction errors, we can't format the date. + if ($this->hasErrors()) { + return; + } + + $format_string_type = isset($settings['format_string_type']) ? $settings['format_string_type'] : static::PHP; + $langcode = !empty($settings['langcode']) ? $settings['langcode'] : $this->langcode; + $country = !empty($settings['country']) ? $settings['country'] : $this->country; + $calendar = !empty($settings['calendar']) ? $settings['calendar'] : $this->calendar; + $time_zone = !empty($settings['timezone']) ? $settings['timezone'] : $this->getTimezone()->getName(); + $lenient = !empty($settings['lenient']) ? $settings['lenient'] : FALSE; + + // Format the date and catch errors. + try { + + // If we have what we need to use the IntlDateFormatter, do so. + if ($this->canUseIntl() && $format_string_type == static::INTL) { + + // Construct the $locale variable needed by the IntlDateFormatter. + $locale = $langcode . '_' . $country; + + // If we have information about a calendar, add it. + if (!empty($calendar) && $calendar != static::CALENDAR) { + $locale .= '@calendar=' . $calendar; + } + + // If we're working with a non-gregorian calendar, indicate that. + $calendar_type = \IntlDateFormatter::GREGORIAN; + if ($calendar != SELF::CALENDAR) { + $calendar_type = \IntlDateFormatter::TRADITIONAL; + } + + $date_type = !empty($settings['date_type']) ? $settings['date_type'] : \IntlDateFormatter::FULL; + $time_type = !empty($settings['time_type']) ? $settings['time_type'] : \IntlDateFormatter::FULL; + $formatter = new \IntlDateFormatter($locale, $date_type, $time_type, $time_zone, $calendar_type); + $formatter->setLenient($lenient); + $value = $formatter->format($format); + } + + // Otherwise, use the parent method. + else { + $value = parent::format($format); + } + } + catch (\Exception $e) { + $this->errors[] = $e->getMessage(); + } + return $value; + } +} diff --git a/core/lib/Drupal/Core/Datetime/DrupalDateTime.php b/core/lib/Drupal/Core/Datetime/DrupalDateTime.php new file mode 100644 index 0000000..6d8b128 --- /dev/null +++ b/core/lib/Drupal/Core/Datetime/DrupalDateTime.php @@ -0,0 +1,169 @@ + 2014, 'month => 4). + * Defaults to 'now'. + * @param mixed $timezone + * PHP DateTimeZone object, string or NULL allowed. + * Defaults to NULL. + * @param string $format + * PHP date() type format for parsing the input. This is recommended + * to use things like negative years, which php's parser fails on, or + * any other specialized input with a known format. If provided the + * date will be created using the createFromFormat() method. + * Defaults to NULL. + * @see http://us3.php.net/manual/en/datetime.createfromformat.php + * @param array $settings + * - boolean $validate_format + * The format used in createFromFormat() allows slightly different + * values than format(). If we use an input format that works in + * both functions we can add a validation step to confirm that the + * date created from a format string exactly matches the input. + * We need to know if this can be relied on to do that validation. + * Defaults to TRUE. + * - string $langcode + * The two letter language code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $country + * The two letter country code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $calendar + * A calendar name to use for the date, Defaults to + * DateTimePlus::CALENDAR. + * - boolean $debug + * Leave evidence of the input values in the resulting object + * for debugging purposes. Defaults to FALSE. + */ + public function __construct($time = 'now', $timezone = NULL, $format = NULL, $settings = array()) { + + // We can set the langcode and country using Drupal values. + $settings['langcode'] = !empty($settings['langcode']) ? $settings['langcode'] : language(LANGUAGE_TYPE_INTERFACE)->langcode; + $settings['country'] = !empty($settings['country']) ? $settings['country'] : variable_get('site_default_country'); + + // Instantiate the parent class. + parent::__construct($time, $timezone, $format, $settings); + + } + + /** + * Override basic component timezone handling to use Drupal's + * knowledge of the preferred user timezone. + */ + protected function prepareTimezone($timezone) { + $user_timezone = drupal_get_user_timezone(); + if (empty($timezone) && !empty($user_timezone)) { + $timezone = $user_timezone; + } + parent::prepareTimezone($timezone); + } + + /** + * Format the date for display. + * + * Use the IntlDateFormatter to display the format, if available. + * Because the IntlDateFormatter is not always available, we + * need to know whether the $format string uses the standard + * format strings used by the date() function or the alternative + * format provided by the IntlDateFormatter. + * + * @param string $format + * A format string using either date() or IntlDateFormatter() + * format. + * @param array $settings + * - string $format_string_type + * Which pattern is used by the format string. When using the + * Intl formatter, the format string must use the Intl pattern, + * which is different from the pattern used by the DateTime + * format function. Defaults to DateTimePlus::PHP. + * - string $timezone + * A timezone name. Defaults to the timezone of the date object. + * - string $langcode + * The two letter language code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $country + * The two letter country code to construct the locale string by the + * intlDateFormatter class. Used to control the result of the + * format() method if that class is available. Defaults to NULL. + * - string $calendar + * A calendar name to use for the date, Defaults to + * DateTimePlus::CALENDAR. + * - int $datetype + * The datetype to use in the formatter, defaults to + * IntlDateFormatter::FULL. + * - int $timetype + * The datetype to use in the formatter, defaults to + * IntlDateFormatter::FULL. + * - boolean $lenient + * Whether or not to use lenient processing in the intl + * formatter. Defaults to FALSE; + * + * @return string + * The formatted value of the date. + */ + public function format($format, $settings = array()) { + + $format_string_type = isset($settings['format_string_type']) ? $settings['format_string_type'] : static::PHP; + + $settings['langcode'] = !empty($settings['langcode']) ? $settings['langcode'] : $this->langcode; + $settings['country'] = !empty($settings['country']) ? $settings['country'] : $this->country; + + // Format the date and catch errors. + try { + + // If we have what we need to use the IntlDateFormatter, do so. + if ($this->canUseIntl() && $format_string_type == parent::INTL) { + $value = parent::format($format, $settings); + } + + // Otherwise, use the default Drupal method. + else { + + // Encode markers that should be translated. 'A' becomes + // '\xEF\AA\xFF'. xEF and xFF are invalid UTF-8 sequences, + // and we assume they are not in the input string. + // Paired backslashes are isolated to prevent errors in + // read-ahead evaluation. The read-ahead expression ensures that + // A matches, but not \A. + $format = preg_replace(array('/\\\\\\\\/', '/(?errors[] = $e->getMessage(); + } + return $value; + } +} diff --git a/core/lib/Drupal/Core/Datetime/Plugin/DateCalendar.php b/core/lib/Drupal/Core/Datetime/Plugin/DateCalendar.php new file mode 100644 index 0000000..7885849 --- /dev/null +++ b/core/lib/Drupal/Core/Datetime/Plugin/DateCalendar.php @@ -0,0 +1,65 @@ +langcode; + $this->discovery = new CacheDecorator(new HookDiscovery('datetime_calendar_info'), $cache_id); + $this->factory = new DefaultFactory($this->discovery); + } + + /** + * Implements Drupal\Component\Plugin\PluginManagerInterface::createInstance(). + * + * @param string $plugin_id + * The id of a plugin, i.e. the calendar type. + * @param array $configuration + * Not used in this plugin. + * + * @return Drupal\Core\TypedData\TypedDataInterface + */ + public function createInstance($plugin_id, array $configuration = array()) { + + // A missing or invalid calendar $plugin_id creates serious problems, + // so check first and swap in the known default calendar if the + // value won't work. + $plugins = array_keys($this->getDefinitions()); + if (!in_array($plugin_id, $plugins)) { + watchdog('datetime', t("The system was unable to use the '@calendar' calendar. Using @default calendar instead.", array('@calendar' => $plugin_id, '@default' => self::DEFAULT_CALENDAR))); + $plugin_id = self::DEFAULT_CALENDAR; + } + return $this->factory->createInstance($plugin_id, $configuration); + } + +} diff --git a/core/lib/Drupal/Core/Datetime/Plugin/DateCalendarInterface.php b/core/lib/Drupal/Core/Datetime/Plugin/DateCalendarInterface.php new file mode 100644 index 0000000..3e08c53 --- /dev/null +++ b/core/lib/Drupal/Core/Datetime/Plugin/DateCalendarInterface.php @@ -0,0 +1,271 @@ + 'January', + 2 => 'February', + 3 => 'March', + 4 => 'April', + 5 => 'May', + 6 => 'June', + 7 => 'July', + 8 => 'August', + 9 => 'September', + 10 => 'October', + 11 => 'November', + 12 => 'December', + ); + } + + /** + * Constructs an untranslated array of abbreviated month names. + * + * @return array + * An array of month names. + */ + public static function monthNamesAbbrUntranslated() { + // Force the key to use the correct month value, rather than + // starting with zero. + return array( + 1 => 'Jan', + 2 => 'Feb', + 3 => 'Mar', + 4 => 'Apr', + 5 => 'May', + 6 => 'Jun', + 7 => 'Jul', + 8 => 'Aug', + 9 => 'Sep', + 10 => 'Oct', + 11 => 'Nov', + 12 => 'Dec', + ); + } + + /** + * Returns a translated array of month names. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of month names. + */ + public static function monthNames($required = FALSE) { + // Force the key to use the correct month value, rather than + // starting with zero. + $monthnames = array( + 1 => t('January', array(), array('context' => 'Long month name')), + 2 => t('February', array(), array('context' => 'Long month name')), + 3 => t('March', array(), array('context' => 'Long month name')), + 4 => t('April', array(), array('context' => 'Long month name')), + 5 => t('May', array(), array('context' => 'Long month name')), + 6 => t('June', array(), array('context' => 'Long month name')), + 7 => t('July', array(), array('context' => 'Long month name')), + 8 => t('August', array(), array('context' => 'Long month name')), + 9 => t('September', array(), array('context' => 'Long month name')), + 10 => t('October', array(), array('context' => 'Long month name')), + 11 => t('November', array(), array('context' => 'Long month name')), + 12 => t('December', array(), array('context' => 'Long month name')), + ); + $none = array('' => ''); + return !$required ? $none + $monthnames : $monthnames; + } + + /** + * Constructs a translated array of month name abbreviations + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of month abbreviations. + */ + public static function monthNamesAbbr($required = FALSE) { + // Force the key to use the correct month value, rather than + // starting with zero. + $monthnames = array( + 1 => t('Jan'), + 2 => t('Feb'), + 3 => t('Mar'), + 4 => t('Apr'), + 5 => t('May'), + 6 => t('Jun'), + 7 => t('Jul'), + 8 => t('Aug'), + 9 => t('Sep'), + 10 => t('Oct'), + 11 => t('Nov'), + 12 => t('Dec'), + ); + $none = array('' => ''); + return !$required ? $none + $monthnames : $monthnames; + } + + /** + * Constructs an untranslated array of week days. + * + * @return array + * An array of week day names + */ + public static function weekDaysUntranslated() { + return array( + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + ); + } + + /** + * Returns a translated array of week names. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day names + */ + public static function weekDays($required = FALSE) { + $weekdays = array( + t('Sunday'), + t('Monday'), + t('Tuesday'), + t('Wednesday'), + t('Thursday'), + t('Friday'), + t('Saturday'), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Constructs a translated array of week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day abbreviations + */ + public static function weekDaysAbbr($required = FALSE) { + $weekdays = array( + t('Sun', array(), array('context' => 'Sunday abbreviation')), + t('Mon', array(), array('context' => 'Monday abbreviation')), + t('Tue', array(), array('context' => 'Tuesday abbreviation')), + t('Wed', array(), array('context' => 'Wednesday abbreviation')), + t('Thu', array(), array('context' => 'Thursday abbreviation')), + t('Fri', array(), array('context' => 'Friday abbreviation')), + t('Sat', array(), array('context' => 'Saturday abbreviation')), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Constructs a translated array of 2-letter week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day 2 letter abbreviations + */ + public static function weekDaysAbbr2($required = FALSE) { + $weekdays = array( + t('Su', array(), array('context' => 'Sunday 2 letter abbreviation')), + t('Mo', array(), array('context' => 'Monday 2 letter abbreviation')), + t('Tu', array(), array('context' => 'Tuesday 2 letter abbreviation')), + t('We', array(), array('context' => 'Wednesday 2 letter abbreviation')), + t('Th', array(), array('context' => 'Thursday 2 letter abbreviation')), + t('Fr', array(), array('context' => 'Friday 2 letter abbreviation')), + t('Sa', array(), array('context' => 'Saturday 2 letter abbreviation')), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Constructs a translated array of 1-letter week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day 1 letter abbreviations + */ + public static function weekDaysAbbr1($required = FALSE) { + $weekdays = array( + t('S', array(), array('context' => 'Sunday 1 letter abbreviation')), + t('M', array(), array('context' => 'Monday 1 letter abbreviation')), + t('T', array(), array('context' => 'Tuesday 1 letter abbreviation')), + t('W', array(), array('context' => 'Wednesday 1 letter abbreviation')), + t('T', array(), array('context' => 'Thursday 1 letter abbreviation')), + t('F', array(), array('context' => 'Friday 1 letter abbreviation')), + t('S', array(), array('context' => 'Saturday 1 letter abbreviation')), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Reorders weekdays to match the first day of the week. + * + * @param array $weekdays + * An array of weekdays. + * + * @return array + * An array of weekdays reordered to match the first day of the week. + */ + public static function weekDaysOrdered($weekdays) { + $first_day = variable_get('date_first_day', 0); + if ($first_day > 0) { + for ($i = 1; $i <= $first_day; $i++) { + $last = array_shift($weekdays); + array_push($weekdays, $last); + } + } + return $weekdays; + } + + /** + * Constructs an array of years in a specified range. + * + * @param int $min + * The minimum year in the array. + * @param int $max + * The maximum year in the array. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of years in the selected range. + */ + public static function years($min = 0, $max = 0, $required = FALSE) { + // Ensure $min and $max are valid values. + if (empty($min)) { + $min = intval(date('Y', REQUEST_TIME) - 3); + } + if (empty($max)) { + $max = intval(date('Y', REQUEST_TIME) + 3); + } + $none = array(0 => ''); + $range = drupal_map_assoc(range($min, $max)); + return !$required ? $none + $range : $range; + } + + /** + * Constructs an array of days in a month. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $month + * (optional) The month in which to find the number of days. + * @param int $year + * (optional) The year in which to find the number of days. + * + * @return array + * An array of days for the selected month. + */ + public static function days($required = FALSE, $month = NULL, $year = NULL) { + // If we have a month and year, find the right last day of the month. + if (!empty($month) && !empty($year)) { + $date = new DrupalDateTime($year . '-' . $month . '-01 00:00:00', 'UTC'); + $max = $date->format('t'); + } + // If there is no month and year given, default to 31. + if (empty($max)) { + $max = 31; + } + $none = array(0 => ''); + $range = drupal_map_assoc(range(1, $max)); + return !$required ? $none + $range : $range; + } + + + /** + * Constructs an array of hours. + * + * @param string $format + * A date format string that indicates the format to use for the hours. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of hours in the selected format. + */ + public static function hours($format = 'H', $required = FALSE) { + $hours = array(); + if ($format == 'h' || $format == 'g') { + $min = 1; + $max = 12; + } + else { + $min = 0; + $max = 23; + } + for ($i = $min; $i <= $max; $i++) { + $formatted = ($format == 'H' || $format == 'h') ? DrupalDateTime::datePad($i) : $i; + $hours[$i] = $formatted; + } + $none = array('' => ''); + return !$required ? $none + $hours : $hours; + } + + /** + * Constructs an array of minutes. + * + * @param string $format + * A date format string that indicates the format to use for the minutes. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $increment + * A the integer value to increment the values. Defaults to 1. + * + * @return array + * An array of minutes in the selected format. + */ + public static function minutes($format = 'i', $required = FALSE, $increment = 1) { + $minutes = array(); + // Ensure $increment has a value so we don't loop endlessly. + if (empty($increment)) { + $increment = 1; + } + for ($i = 0; $i < 60; $i += $increment) { + $formatted = $format == 'i' ? DrupalDateTime::datePad($i) : $i; + $minutes[$i] = $formatted; + } + $none = array('' => ''); + return !$required ? $none + $minutes : $minutes; + } + + /** + * Constructs an array of seconds. + * + * @param string $format + * A date format string that indicates the format to use for the seconds. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $increment + * A the integer value to increment the values. Defaults to 1. + * + * @return array + * An array of seconds in the selected format. + */ + public static function seconds($format = 's', $required = FALSE, $increment = 1) { + $seconds = array(); + // Ensure $increment has a value so we don't loop endlessly. + if (empty($increment)) { + $increment = 1; + } + for ($i = 0; $i < 60; $i += $increment) { + $formatted = $format == 's' ? DrupalDateTime::datePad($i) : $i; + $seconds[$i] = $formatted; + } + $none = array('' => ''); + return !$required ? $none + $seconds : $seconds; + } + + /** + * Constructs an array of AM and PM options. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of AM and PM options. + */ + public static function ampm($required = FALSE) { + $none = array('' => ''); + $ampm = array( + 'am' => t('am', array(), array('context' => 'ampm')), + 'pm' => t('pm', array(), array('context' => 'ampm')), + ); + return !$required ? $none + $ampm : $ampm; + } + + /** + * Identifies the number of days in a month for a date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * + * @return integer + * The number of days in the month. + */ + public static function daysInMonth($date = NULL) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + if (!$date->hasErrors()) { + return $date->format('t'); + } + return NULL; + } + + /** + * Identifies the number of days in a year for a date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * + * @return integer + * The number of days in the year. + */ + public static function daysInYear($date = NULL) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + if (!$date->hasErrors()) { + if ($date->format('L')) { + return 366; + } + else { + return 365; + } + } + return NULL; + } + + /** + * Returns day of week for a given date (0 = Sunday). + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * + * @return int + * The number of the day in the week. + */ + public static function dayOfWeek($date = NULL) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + if (!$date->hasErrors()) { + return $date->format('w'); + } + return NULL; + } + + /** + * Returns translated name of the day of week for a given date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * @param string $abbr + * (optional) Whether to return the abbreviated name for that day. + * Defaults to TRUE. + * + * @return string + * The name of the day in the week for that date. + */ + public static function dayOfWeekName($date = NULL, $abbr = TRUE) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + $dow = self::dayOfWeek($date); + $days = $abbr ? self::weekDaysAbbr() : self::weekDays(); + return $days[$dow]; + } + +} diff --git a/core/lib/Drupal/Core/TypedData/Type/Date.php b/core/lib/Drupal/Core/TypedData/Type/Date.php index 07767e9..3c0f3a9 100644 --- a/core/lib/Drupal/Core/TypedData/Type/Date.php +++ b/core/lib/Drupal/Core/TypedData/Type/Date.php @@ -7,16 +7,17 @@ namespace Drupal\Core\TypedData\Type; +use Drupal\Core\Datetime\DrupalDateTime; use Drupal\Core\TypedData\TypedDataInterface; -use DateTime; use InvalidArgumentException; /** * The date data type. * - * The plain value of a date is an instance of the DateTime class. For setting - * the value an instance of the DateTime class, any string supported by - * DateTime::__construct(), or a timestamp as integer may be passed. + * The plain value of a date is an instance of the DrupalDateTime class. For setting + * the value any value supported by the __construct() of the DrupalDateTime + * class will work, including a DateTime object, a timestamp, a string + * date, or an array of date parts. */ class Date extends TypedData implements TypedDataInterface { @@ -31,18 +32,17 @@ class Date extends TypedData implements TypedDataInterface { * Implements TypedDataInterface::setValue(). */ public function setValue($value) { - if ($value instanceof DateTime || !isset($value)) { + + // Don't try to create a date from an empty value. + // It would default to the current time. + if (!isset($value)) { $this->value = $value; } - // Treat integer values as timestamps, even if supplied as PHP string. - elseif ((string) (int) $value === (string) $value) { - $this->value = new DateTime('@' . $value); - } - elseif (is_string($value)) { - $this->value = new DateTime($value); - } else { - throw new InvalidArgumentException("Invalid date format given."); + $this->value = $value instanceOf DrupalDateTime ? $value : new DrupalDateTime($value); + if ($this->value->hasErrors()) { + throw new InvalidArgumentException("Invalid date format given."); + } } } @@ -50,7 +50,7 @@ public function setValue($value) { * Implements TypedDataInterface::getString(). */ public function getString() { - return (string) $this->getValue()->format(DateTime::ISO8601); + return (string) $this->getValue(); } /** diff --git a/core/misc/datepicker.js b/core/misc/datepicker.js new file mode 100644 index 0000000..3fef66a --- /dev/null +++ b/core/misc/datepicker.js @@ -0,0 +1,29 @@ +/** + * Attaches the datepicker behavior to all required fields + */ +(function ($) { +Drupal.behaviors.dateTime = { + attach: function (context, settings) { + + var i = document.createElement("input"); + i.setAttribute("type", "date"); + if (i.type == "text") { + // No native date picker support? Use jQueryUI. + for (var id in Drupal.settings.dateTime) { + $(id).bind('focus', Drupal.settings.dateTime[id], function(e) { + if (!$(this).hasClass('date-popup-init')) { + var dateTime = e.data; + $(this) + .datepicker(dateTime) + .addClass('date-popup-init') + $(this).click(function(){ + $(this).focus(); + }); + } + }); + } + } + } +}; +})(jQuery); + diff --git a/core/modules/comment/lib/Drupal/comment/CommentFormController.php b/core/modules/comment/lib/Drupal/comment/CommentFormController.php index cead0cd..3e3dcca 100644 --- a/core/modules/comment/lib/Drupal/comment/CommentFormController.php +++ b/core/modules/comment/lib/Drupal/comment/CommentFormController.php @@ -9,6 +9,7 @@ use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityFormController; +use Drupal\Core\Datetime\DrupalDateTime; /** * Base for controller for comment forms. @@ -236,7 +237,8 @@ public function validate(array $form, array &$form_state) { $account = user_load_by_name($form_state['values']['name']); $form_state['values']['uid'] = $account ? $account->uid : 0; - if ($form_state['values']['date'] && strtotime($form_state['values']['date']) === FALSE) { + $date = new DrupalDateTime($form_state['values']['date']); + if ($date->hasErrors()) { form_set_error('date', t('You have to specify a valid date.')); } if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) { @@ -271,7 +273,8 @@ public function submit(array $form, array &$form_state) { if (empty($comment->date)) { $comment->date = 'now'; } - $comment->created = strtotime($comment->date); + $date = new DrupalDateTime($comment->date); + $comment->created = $date->getTimestamp(); $comment->changed = REQUEST_TIME; // If the comment was posted by a registered user, assign the author's ID. diff --git a/core/modules/field/modules/datetime/datetime.info b/core/modules/field/modules/datetime/datetime.info new file mode 100644 index 0000000..5064609 --- /dev/null +++ b/core/modules/field/modules/datetime/datetime.info @@ -0,0 +1,6 @@ +name = Date +description = A simple date/time field. +package = Core +version = VERSION +core = 8.x +dependencies[] = field \ No newline at end of file diff --git a/core/modules/field/modules/datetime/datetime.install b/core/modules/field/modules/datetime/datetime.install new file mode 100644 index 0000000..910cff9 --- /dev/null +++ b/core/modules/field/modules/datetime/datetime.install @@ -0,0 +1,31 @@ + 'The date value', + 'type' => 'varchar', + 'length' => 20, + 'not null' => FALSE, + ); + $indexes = array( + 'value' => array('value'), + ); + return array('columns' => $db_columns, 'indexes' => $indexes); +} + +// @TODO +// Update any existing fields of the type 'datetime' to 'datetimeold', +// then add upgrade path in Date module for those types so we can +// re-use the field type name for a new field in core. +function datetime_install() { + +} \ No newline at end of file diff --git a/core/modules/field/modules/datetime/datetime.module b/core/modules/field/modules/datetime/datetime.module new file mode 100644 index 0000000..3e364cc --- /dev/null +++ b/core/modules/field/modules/datetime/datetime.module @@ -0,0 +1,124 @@ +getTimestamp(); + } + + $item = array(); + $item[0]['value'] = $value; + + return $item; +} + +/** + * Implements hook_field_is_empty(). + */ +function datetime_field_is_empty($item, $field) { + if (empty($item['value'])) { + return TRUE; + } + return FALSE; +} + +/** + * Implements hook_field_info(). + */ +function datetime_field_info() { + return array( + 'datetime' => array( + 'label' => 'Date', + 'description' => t('Create and store simple date values.'), + 'settings' => array( + 'datetime' => '', + ), + 'instance_settings' => array( + 'default_value' => 'now', + ), + 'default_widget' => 'datetime_datepicker', + 'default_formatter' => 'datetime_default', + 'default_token_formatter' => 'datetime_plain', + 'field item class' => '\Drupal\datetime\Type\DateTimeItem', + ), + ); +} + +/** + * Implements hook_field_settings_form(). + */ +function datetime_field_settings_form($field, $instance, $has_data) { + $settings = $field['settings']; + + $form['datetime'] = array( + '#type' => 'select', + '#title' => t('Date type'), + '#description' => t('Choose the type of date to create.'), + '#default_value' => $settings['datetime'], + '#options' => array( + '' => t('Date and time'), + 'date' => t('Date only'), + ), + ); + return $form; +} + +/** + * Implements hook_field_instance_settings_form(). + */ +function datetime_field_instance_settings_form($field, $instance) { + $widget = $instance['widget']; + $settings = $instance['settings']; + $widget_settings = $instance['widget']['settings']; + + $form['default_value'] = array( + '#type' => 'select', + '#title' => t('Default date'), + '#description' => t('Set a default value for this date.'), + '#default_value' => $settings['default_value'], + '#options' => array('blank' => t('No default value'), 'now' => t('The current date')), + '#weight' => 1, + ); + + return $form; +} + +/** + * Custom validation for the datetime form element. + * The date has already been validated by the datetime form type + * validator and transformed to an date string. We just need to + * convert the date back to a the right timezone and format for storage. + */ +function datetime_widget_validate(&$element, &$form_state) { + if (!form_get_errors()) { + $input_exists = FALSE; + $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists); + if ($input_exists) { + if (!empty($input['value'])) { + $date = new DrupalDateTime($input['value'], $element['value']['#date_timezone']); + if (!$date->hasErrors()) { + // If this is a date-only field, set the time to midnight. + if ($element['value']['#date_time_element'] == 'none') { + $date->setTime(0, 0, 0); + } + // Adjust the entered date to UTC for storage. + $date->setTimezone(new \DateTimezone('UTC')); + // Store the date using the ISO format. + form_set_value($element['value'], $date->format('Y-m-d\TH:i:s'), $form_state); + } + } + } + } +} diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php new file mode 100644 index 0000000..84b928b --- /dev/null +++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php @@ -0,0 +1,103 @@ + $item) { + $date = new DrupalDateTime($item['value'], 'UTC'); + $date->setTimeZone(timezone_open(drupal_get_user_timezone())); + $output = $this->dateFormat($date); + + $elements[$delta] = array('#markup' => $output); + } + + return $elements; + + } + + /** + * Format a date. + * + * @param object $date + * A date object. + * + * @return + * Returns a date formatted with the formatter's chosen format. + */ + function dateFormat($date) { + $format_type = $this->getSetting('format_type'); + return format_date($date->getTimestamp(), $format_type); + } + + /** + * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm(). + */ + public function settingsForm(array $form, array &$form_state) { + + $element = array(); + + $time = new DrupalDateTime(); + $format_types = system_get_date_types(); + if (!empty($format_types)) { + foreach ($format_types as $type => $type_info) { + $options[$type] = $type_info['title'] . ' (' . format_date($time->format('U'), $type) . ')'; + } + } + + $elements['format_type'] = array( + '#type' => 'select', + '#title' => t('Date format'), + '#description' => t("Choose a format for displaying the date."), + '#options' => $options, + '#default_value' => $this->getSetting('format_type'), + ); + + return $elements; + } + + /** + * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm(). + */ + public function settingsSummary() { + + $date = new DrupalDateTime(); + $output = array(); + $output[] = t('Format: @display', array('@display' => $this->dateFormat($date, FALSE))); + return implode('
', $output); + + } +} diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php new file mode 100644 index 0000000..293d1a9 --- /dev/null +++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php @@ -0,0 +1,45 @@ + $item) { + $elements[$delta] = array('#markup' => $item['value']); + } + + return $elements; + + } + +} diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatepicker.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatepicker.php new file mode 100644 index 0000000..7f82a1b --- /dev/null +++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatepicker.php @@ -0,0 +1,122 @@ +field; + $instance = $this->instance; + + // We're nesting some sub-elements inside the parent, so we + // need a wrapper. We also need to add another #title attribute + // at the top level for ease in identifying this item in error + // messages. We don't want to display this title because the + // actual title display is handled at a higher level by the Field + // module. + + $element['#theme_wrappers'][] = 'form_element'; + $element['#attributes']['class'] = 'container-inline'; + $element['#element_validate'][] = 'datetime_widget_validate'; + $element['#date_timezone'] = drupal_get_user_timezone(); + $date_format = variable_get('date_format_html_date', 'Y-m-d'); + $time_format = variable_get('date_format_html_time', 'H:i:s'); + + switch ($field['settings']['datetime']) { + case 'date': + $date_type = 'date'; + $time_type = 'none'; + $full_format = $date_format; + break; + default: + $date_type = 'date'; + $time_type = 'time'; + $full_format = $date_format . ' ' . $time_format; + break; + } + + foreach ($items as $delta => $item) { + + $data = isset($item['value']) ? $item['value'] : NULL; + $value = NULL; + if (!empty($data)) { + $date = new DrupalDateTime($data, 'UTC'); + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + $date->setTimezone( new \DateTimeZone($element['#date_timezone'])); + $value = $date->format($full_format); + } + } + $element['value'] = array( + '#type' => 'datetime', + '#title' => $instance->definition['label'], + '#title_display' => 'invisible', + '#delta' => $delta, + '#default_value' => $value, + '#date_increment' => 1, + '#date_date_format'=> $date_format, + '#date_date_element' => $date_type, + '#date_date_callbacks' => array('datetime_jquery_datepicker_callback'), + '#date_time_format' => $time_format, + '#date_time_element' => $time_type, + '#date_time_callbacks' => array(), + '#date_timezone' => $element['#date_timezone'], + '#required' => $element['#required'], + ); + } + + return $element; + } + +} diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php new file mode 100644 index 0000000..a51e98a --- /dev/null +++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php @@ -0,0 +1,39 @@ + 'date', + 'label' => t('Date value'), + ); + } + return self::$propertyDefinitions; + } +} diff --git a/core/modules/node/lib/Drupal/node/NodeFormController.php b/core/modules/node/lib/Drupal/node/NodeFormController.php index 5add3df..84a34c0 100644 --- a/core/modules/node/lib/Drupal/node/NodeFormController.php +++ b/core/modules/node/lib/Drupal/node/NodeFormController.php @@ -9,6 +9,7 @@ use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityFormController; +use Drupal\Core\Datetime\DrupalDateTime; /** * Form controller for the node edit forms. @@ -39,7 +40,7 @@ protected function prepareEntity(EntityInterface $node) { $node->created = REQUEST_TIME; } else { - $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O'); + $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s'); // Remove the log message from the original node entity. $node->log = NULL; } @@ -189,12 +190,11 @@ public function form(array $form, array &$form_state, EntityInterface $node) { '#weight' => -1, '#description' => t('Leave blank for %anonymous.', array('%anonymous' => $user_config->get('anonymous'))), ); - + $format = variable_get('date_format_html_date', 'Y-m-d') . ' ' . variable_get('date_format_html_time', 'H:i:s'); $form['author']['date'] = array( - '#type' => 'textfield', + '#type' => 'datetime', '#title' => t('Authored on'), - '#maxlength' => 25, - '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => !empty($node->date) ? date_format(date_create($node->date), 'Y-m-d H:i:s O') : format_date($node->created, 'custom', 'Y-m-d H:i:s O'), '%timezone' => !empty($node->date) ? date_format(date_create($node->date), 'O') : format_date($node->created, 'custom', 'O'))), + '#description' => t('Format: %format. Leave blank to use the time of form submission.', array('%format' => datetime_format_example($format))), '#default_value' => !empty($node->date) ? $node->date : '', ); @@ -288,9 +288,17 @@ public function validate(array $form, array &$form_state) { } // Validate the "authored on" field. - if (!empty($node->date) && strtotime($node->date) === FALSE) { + // The date element contains the date in its ISO form, transform + // it back to a timestamp. + $created = isset($node->date) ? $node->date : REQUEST_TIME; + $timezone = isset($form['date']['#date_timezone']) ? $form['date']['#date_timezone'] : drupal_get_user_timezone(); + $date = new DrupalDateTime($created, $timezone); + if ($date->hasErrors()) { form_set_error('date', t('You have to specify a valid date.')); } + else { + $node->date = $date->getTimestamp(); + } // Invoke hook_validate() for node type specific validation and // hook_node_validate() for miscellaneous validation needed by modules. diff --git a/core/modules/node/node.module b/core/modules/node/node.module index a997a04..a2aaa17 100644 --- a/core/modules/node/node.module +++ b/core/modules/node/node.module @@ -18,6 +18,7 @@ use Drupal\node\Plugin\Core\Entity\Node; use Drupal\file\Plugin\Core\Entity\File; use Drupal\Core\Entity\EntityInterface; +use Drupal\Core\Datetime\DrupalDateTime; /** * Denotes that the node is not published. @@ -1025,7 +1026,8 @@ function node_submit(Node $node) { $node->revision_uid = $user->uid; } - $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME; + $node_created = new DrupalDateTime(!empty($node->date) ? $node->date : REQUEST_TIME); + $node->created = $node_created->getTimestamp(); $node->validated = TRUE; return $node; diff --git a/core/modules/system/config/system.calendar.yml b/core/modules/system/config/system.calendar.yml new file mode 100644 index 0000000..a711b76 --- /dev/null +++ b/core/modules/system/config/system.calendar.yml @@ -0,0 +1 @@ +calendar: gregorian diff --git a/core/modules/system/lib/Drupal/system/Tests/Datetime/DateCalendarTest.php b/core/modules/system/lib/Drupal/system/Tests/Datetime/DateCalendarTest.php new file mode 100644 index 0000000..1470eac --- /dev/null +++ b/core/modules/system/lib/Drupal/system/Tests/Datetime/DateCalendarTest.php @@ -0,0 +1,70 @@ + 'Date Calendar', + 'description' => 'Test Date Calendar functionality.', + 'group' => 'Datetime', + ); + } + + /** + * Set up required modules. + */ + public static $modules = array('datetime_test'); + + /** + * Test setup. + */ + public function setUp() { + parent::setUp(); + } + + /** + * Test . + */ + public function testDateCalendar() { + + // Test gregorian system calendar. + $plugin = new DateCalendar(); + $calendar = $plugin->createInstance('gregorian'); + $this->assertTrue(in_array('January', $calendar->monthNames()), 'The gregorian calendar can be loaded.'); + + // Test alternate 'Gamma' calendar. + $plugin = new DateCalendar(); + $options = $plugin->getDefinitions(); + $this->assertTrue(array_key_exists('gamma', $options), 'An alternate calendar can be found.'); + + $calendar = $plugin->createInstance('gamma'); + $this->assertTrue(in_array('Alpha', $calendar->monthNames()), 'An alternate calendar can be loaded.'); + + // Test that a bogus calendar is switched to gregorian. + $plugin = new DateCalendar(); + $calendar = $plugin->createInstance('bogus'); + $this->assertTrue(in_array('January', $calendar->monthNames()), 'A nonexisting calendar is replaced with the gregorian calendar.'); + + + } + + /** + * Tear down after tests. + */ + public function tearDown() { + parent::tearDown(); + } +} diff --git a/core/modules/system/lib/Drupal/system/Tests/Datetime/DateTimePlusTest.php b/core/modules/system/lib/Drupal/system/Tests/Datetime/DateTimePlusTest.php new file mode 100644 index 0000000..9eb0162 --- /dev/null +++ b/core/modules/system/lib/Drupal/system/Tests/Datetime/DateTimePlusTest.php @@ -0,0 +1,418 @@ + 'DateTimePlus', + 'description' => 'Test DateTimePlus functionality.', + 'group' => 'Datetime', + ); + } + + /** + * Set up required modules. + */ + public static $modules = array(); + + /** + * Test creating dates from string input. + */ + public function testDateStrings() { + + // Create date object from datetime string. + $input = '2009-03-07 10:30'; + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2009-03-07T10:30:00-06:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + // Same during daylight savings time. + $input = '2009-06-07 10:30'; + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2009-06-07T10:30:00-05:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + // Create date object from date string. + $input = '2009-03-07'; + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2009-03-07T00:00:00-06:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + // Same during daylight savings time. + $input = '2009-06-07'; + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2009-06-07T00:00:00-05:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + // Create date object from date string. + $input = '2009-03-07 10:30'; + $timezone = 'Australia/Canberra'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2009-03-07T10:30:00+11:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + // Same during daylight savings time. + $input = '2009-06-07 10:30'; + $timezone = 'Australia/Canberra'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2009-06-07T10:30:00+10:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + } + + /** + * Test creating dates from arrays of date parts. + */ + function testDateArrays() { + + // Create date object from date array, date only. + $input = array('year' => 2010, 'month' => 2, 'day' => 28); + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2010-02-28T00:00:00-06:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28), $timezone): should be $expected, found $value."); + + // Create date object from date array with hour. + $input = array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10); + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2010-02-28T10:00:00-06:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10), $timezone): should be $expected, found $value."); + + // Create date object from date array, date only. + $input = array('year' => 2010, 'month' => 2, 'day' => 28); + $timezone = 'Europe/Berlin'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2010-02-28T00:00:00+01:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28), $timezone): should be $expected, found $value."); + + // Create date object from date array with hour. + $input = array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10); + $timezone = 'Europe/Berlin'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '2010-02-28T10:00:00+01:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10), $timezone): should be $expected, found $value."); + + } + + /** + * Test creating dates from timestamps. + */ + function testDateTimestamp() { + + // Create date object from a unix timestamp and display it in + // local time. + $input = 0; + $timezone = 'UTC'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '1970-01-01T00:00:00+00:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + $expected = 'UTC'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone is $value: should be $expected."); + $expected = 0; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset is $value: should be $expected."); + + $timezone = 'America/Los_Angeles'; + $date->setTimezone(new DateTimeZone($timezone)); + $value = $date->format('c'); + $expected = '1969-12-31T16:00:00-08:00'; + $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value."); + + $expected = 'America/Los_Angeles'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '-28800'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + + // Create a date using the timestamp of zero, then display its + // value both in UTC and the local timezone. + $input = 0; + $timezone = 'America/Los_Angeles'; + $date = new DateTimePlus($input, $timezone); + $offset = $date->getOffset(); + $value = $date->format('c'); + $expected = '1969-12-31T16:00:00-08:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value."); + + $expected = 'America/Los_Angeles'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '-28800'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + + $timezone = 'UTC'; + $date->setTimezone(new DateTimeZone($timezone)); + $value = $date->format('c'); + $expected = '1970-01-01T00:00:00+00:00'; + $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value."); + + $expected = 'UTC'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '0'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + } + + /** + * Test timezone manipulation. + */ + function testTimezoneConversion() { + + // Create date object from datetime string in UTC, and convert + // it to a local date. + $input = '1970-01-01 00:00:00'; + $timezone = 'UTC'; + $date = new DateTimePlus($input, $timezone); + $value = $date->format('c'); + $expected = '1970-01-01T00:00:00+00:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus('$input', '$timezone'): should be $expected, found $value."); + + $expected = 'UTC'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone is $value: should be $expected."); + $expected = 0; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset is $value: should be $expected."); + + $timezone = 'America/Los_Angeles'; + $date->setTimezone(new DateTimeZone($timezone)); + $value = $date->format('c'); + $expected = '1969-12-31T16:00:00-08:00'; + $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value."); + + $expected = 'America/Los_Angeles'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '-28800'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + + // Convert the local time to UTC using string input. + $input = '1969-12-31 16:00:00'; + $timezone = 'America/Los_Angeles'; + $date = new DateTimePlus($input, $timezone); + $offset = $date->getOffset(); + $value = $date->format('c'); + $expected = '1969-12-31T16:00:00-08:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus('$input', '$timezone'): should be $expected, found $value."); + + $expected = 'America/Los_Angeles'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '-28800'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + + $timezone = 'UTC'; + $date->setTimezone(new DateTimeZone($timezone)); + $value = $date->format('c'); + $expected = '1970-01-01T00:00:00+00:00'; + $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value."); + + $expected = 'UTC'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '0'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + + // Convert the local time to UTC using string input. + $input = '1969-12-31 16:00:00'; + $timezone = 'Europe/Warsaw'; + $date = new DateTimePlus($input, $timezone); + $offset = $date->getOffset(); + $value = $date->format('c'); + $expected = '1969-12-31T16:00:00+01:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus('$input', '$timezone'): should be $expected, found $value."); + + $expected = 'Europe/Warsaw'; + $value = $date->getTimeZone()->getName(); + $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value."); + $expected = '+3600'; + $value = $date->getOffset(); + $this->assertEqual($expected, $value, "The current offset should be $expected, found $value."); + + } + + /** + * Test creating dates from format strings. + */ + function testDateFormat() { + + // Create a year-only date. + $input = '2009'; + $timezone = NULL; + $format = 'Y'; + $date = new DateTimePlus($input, $timezone, $format); + $value = $date->format('Y'); + $expected = '2009'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value."); + + // Create a month and year-only date. + $input = '2009-10'; + $timezone = NULL; + $format = 'Y-m'; + $date = new DateTimePlus($input, $timezone, $format); + $value = $date->format('Y-m'); + $expected = '2009-10'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value."); + + // Create a time-only date. + $input = 'T10:30:00'; + $timezone = NULL; + $format = '\TH:i:s'; + $date = new DateTimePlus($input, $timezone, $format); + $value = $date->format('H:i:s'); + $expected = '10:30:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value."); + + // Create a time-only date. + $input = '10:30:00'; + $timezone = NULL; + $format = 'H:i:s'; + $date = new DateTimePlus($input, $timezone, $format); + $value = $date->format('H:i:s'); + $expected = '10:30:00'; + $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value."); + + } + + /** + * Test invalid date handling. + */ + function testInvalidDates() { + + // Test for invalid month names when we are using a short version + // of the month. + $input = '23 abc 2012'; + $timezone = NULL; + $format = 'd M Y'; + $date = new DateTimePlus($input, $timezone, $format); + $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid month name and produces errors."); + + // Test for invalid hour. + $input = '0000-00-00T45:30:00'; + $timezone = NULL; + $format = 'Y-m-d\TH:i:s'; + $date = new DateTimePlus($input, $timezone, $format); + $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid hour and produces errors."); + + // Test for invalid day. + $input = '0000-00-99T05:30:00'; + $timezone = NULL; + $format = 'Y-m-d\TH:i:s'; + $date = new DateTimePlus($input, $timezone, $format); + $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid day and produces errors."); + + // Test for invalid month. + $input = '0000-75-00T15:30:00'; + $timezone = NULL; + $format = 'Y-m-d\TH:i:s'; + $date = new DateTimePlus($input, $timezone, $format); + $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid month and produces errors."); + + // Test for invalid year. + $input = '11-08-01T15:30:00'; + $timezone = NULL; + $format = 'Y-m-d\TH:i:s'; + $date = new DateTimePlus($input, $timezone, $format); + $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid year and produces errors."); + + // Test for invalid year from date array. 10000 as a year will + // create an exception error in the PHP DateTime object. + $input = array('year' => 10000, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0); + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 10000, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0) contains an invalid year and produces errors."); + + // Test for invalid month from date array. + $input = array('year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0); + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0) contains an invalid month and produces errors."); + + // Test for invalid hour from date array. + $input = array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0); + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0) contains an invalid hour and produces errors."); + + // Test for invalid minute from date array. + $input = array('year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0); + $timezone = 'America/Chicago'; + $date = new DateTimePlus($input, $timezone); + $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0) contains an invalid minute and produces errors."); + + } + + /** + * Test that DrupalDateTime can detect the right timezone to use. + * When specified or not. + */ + public function testDateTimezone() { + global $user; + + $date_string = '2007-01-31 21:00:00'; + + // Detect the system timezone. + $system_timezone = date_default_timezone_get(); + + // Create a date object with an unspecified timezone, which should + // end up using the system timezone. + $date = new DateTimePlus($date_string); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == $system_timezone, 'DateTimePlus uses the system timezone when there is no site timezone.'); + + // Create a date object with a specified timezone name. + $date = new DateTimePlus($date_string, 'America/Yellowknife'); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == 'America/Yellowknife', 'DateTimePlus uses the specified timezone if provided.'); + + // Create a date object with a timezone object. + $date = new DateTimePlus($date_string, new \DateTimeZone('Australia/Canberra')); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == 'Australia/Canberra', 'DateTimePlus uses the specified timezone if provided.'); + + // Create a date object with another date object. + $new_date = new DateTimePlus('now', 'Pacific/Midway'); + $date = new DateTimePlus($new_date); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == 'Pacific/Midway', 'DateTimePlus uses the specified timezone if provided.'); + + } +} diff --git a/core/modules/system/lib/Drupal/system/Tests/Datetime/DrupalDateTimeTest.php b/core/modules/system/lib/Drupal/system/Tests/Datetime/DrupalDateTimeTest.php new file mode 100644 index 0000000..ea10896 --- /dev/null +++ b/core/modules/system/lib/Drupal/system/Tests/Datetime/DrupalDateTimeTest.php @@ -0,0 +1,110 @@ + 'DrupalDateTime', + 'description' => 'Test DrupalDateTime functionality.', + 'group' => 'Datetime', + ); + } + + /** + * Set up required modules. + */ + public static $modules = array(); + + /** + * Test setup. + */ + public function setUp() { + parent::setUp(); + + } + + /** + * Test that DrupalDateTime can detect the right timezone to use. + * Test with a variety of less commonly used timezone names to + * help ensure that the system timezone will be different than the + * stated timezones. + */ + public function testDateTimezone() { + global $user; + + $date_string = '2007-01-31 21:00:00'; + + // Make sure no site timezone has been set. + variable_set('date_default_timezone', NULL); + variable_set('configurable_timezones', 0); + + // Detect the system timezone. + $system_timezone = date_default_timezone_get(); + + // Create a date object with an unspecified timezone, which should + // end up using the system timezone. + $date = new DrupalDateTime($date_string); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == $system_timezone, 'DrupalDateTime uses the system timezone when there is no site timezone.'); + + // Create a date object with a specified timezone. + $date = new DrupalDateTime($date_string, 'America/Yellowknife'); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == 'America/Yellowknife', 'DrupalDateTime uses the specified timezone if provided.'); + + // Set a site timezone. + variable_set('date_default_timezone', 'Europe/Warsaw'); + + // Create a date object with an unspecified timezone, which should + // end up using the site timezone. + $date = new DrupalDateTime($date_string); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == 'Europe/Warsaw', 'DrupalDateTime uses the site timezone if provided.'); + + // Create user. + variable_set('configurable_timezones', 1); + $test_user = $this->drupalCreateUser(array()); + $this->drupalLogin($test_user); + + // Set up the user with a different timezone than the site. + $edit = array('mail' => $test_user->mail, 'timezone' => 'Asia/Manila'); + $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save')); + + // Disable session saving as we are about to modify the global $user. + drupal_save_session(FALSE); + // Save the original user and then replace it with the test user. + $real_user = $user; + $user = user_load($test_user->uid, TRUE); + + // Simulate a Drupal bootstrap with the logged-in user. + date_default_timezone_set(drupal_get_user_timezone()); + + // Create a date object with an unspecified timezone, which should + // end up using the user timezone. + + $date = new DrupalDateTime($date_string); + $timezone = $date->getTimezone()->getName(); + $this->assertTrue($timezone == 'Asia/Manila', 'DrupalDateTime uses the user timezone, if configurable timezones are used and it is set.'); + + // Restore the original user, and enable session saving. + $user = $real_user; + // Restore default time zone. + date_default_timezone_set(drupal_get_user_timezone()); + drupal_save_session(TRUE); + + + } +} diff --git a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php index 15d12d8..6d1f477 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php @@ -510,7 +510,7 @@ function testDisabledElements() { // All the elements should be marked as disabled, including the ones below // the disabled container. - $this->assertEqual(count($disabled_elements), 40, 'The correct elements have the disabled property in the HTML code.'); + $this->assertEqual(count($disabled_elements), 39, 'The correct elements have the disabled property in the HTML code.'); $this->drupalPost(NULL, $edit, t('Submit')); $returned_values['hijacked'] = drupal_json_decode($this->content); @@ -560,7 +560,7 @@ function testDisabledMarkup() { 'textarea' => 'textarea', 'select' => 'select', 'weight' => 'select', - 'date' => 'select', + 'datetime' => 'datetime', ); foreach ($form as $name => $item) { diff --git a/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php b/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php index 62bd35e..66a4272 100644 --- a/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php @@ -8,7 +8,7 @@ namespace Drupal\system\Tests\TypedData; use Drupal\simpletest\WebTestBase; -use DateTime; +use Drupal\Core\Datetime\DrupalDateTime; use DateInterval; /** @@ -72,7 +72,7 @@ public function testGetAndSet() { $this->assertNull($wrapper->getValue(), 'Float wrapper is null-able.'); // Date type. - $value = new DateTime('@' . REQUEST_TIME); + $value = new DrupalDateTime(); $wrapper = $this->createTypedData(array('type' => 'date'), $value); $this->assertTrue($wrapper->getValue() === $value, 'Date value was fetched.'); $new_value = REQUEST_TIME + 1; diff --git a/core/modules/system/system.admin.inc b/core/modules/system/system.admin.inc index c55289c..782934c 100644 --- a/core/modules/system/system.admin.inc +++ b/core/modules/system/system.admin.inc @@ -8,6 +8,7 @@ use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; +use Drupal\Core\Datetime\Plugin\DateCalendar; /** * Menu callback; Provide the administration overview page. @@ -1861,6 +1862,11 @@ function system_regional_settings() { // Date settings: $zones = system_time_zones(); + // Get calendar information. + $calendar_type = config('system.calendar')->get('calendar'); + $calendar_plugin = new DateCalendar(); + $calendar = $calendar_plugin->createInstance($calendar_type); + $form['locale'] = array( '#type' => 'fieldset', '#title' => t('Locale'), @@ -1875,11 +1881,23 @@ function system_regional_settings() { '#attributes' => array('class' => array('country-detect')), ); + // Find out what calendar systems are available. + foreach ($calendar_plugin->getDefinitions() as $name => $definition) { + $options[$name] = $definition['label']; + } + $form['locale']['calendar'] = array( + '#type' => 'select', + '#title' => t('Default calendar system'), + '#default_value' => $calendar_type, + '#options' => $options, + ); + + // Get a list of day names using the site calendar. $form['locale']['date_first_day'] = array( '#type' => 'select', '#title' => t('First day of week'), '#default_value' => variable_get('date_first_day', 0), - '#options' => array(0 => t('Sunday'), 1 => t('Monday'), 2 => t('Tuesday'), 3 => t('Wednesday'), 4 => t('Thursday'), 5 => t('Friday'), 6 => t('Saturday')), + '#options' => $calendar->weekDays(TRUE), ); $form['timezone'] = array( @@ -1930,10 +1948,23 @@ function system_regional_settings() { '#description' => t('Only applied if users may set their own time zone.') ); + $form['#submit'][] = 'system_calendar_settings_submit'; + return system_settings_form($form); } /** + * Form submission handler for system_calendar_settings(). + * + * @ingroup forms + */ +function system_calendar_settings_submit($form, &$form_state) { + $config = config('system.calendar'); + $config->set('calendar', $form_state['values']['calendar']); + $config->save(); +} + +/** * Form builder; Configure the site date and time settings. * * @ingroup forms diff --git a/core/modules/system/system.api.php b/core/modules/system/system.api.php index 2d09534..2b94fea 100644 --- a/core/modules/system/system.api.php +++ b/core/modules/system/system.api.php @@ -147,6 +147,34 @@ function hook_cron() { } /** + * Defines available calendar system information. + * + * Drupal provides a pluggable system for defining the calendar + * system used when displaying dates and date parts. Modules that provide + * information about calendar systems other than Gregorian can + * implement this hook and identify the calendar system being added + * and the values for days, weeks, and months in that system. + * + * @return array + * An associative array where the key is the calendar name and the value is + * again an associative array. Supported keys are: + * - label: The human readable label of the calendar system. + * - class: The associated calendar class. Must implement + * \Drupal\Core\Datetime\Plugin\DateCalendarInterface. + * + * @see system_calendar() + * @see \Drupal\Date\Datetime\Plugin\Type\Gregorian + */ +function hook_datetime_calendar_info() { + return array( + 'gregorian' => array( + 'label' => t('Gregorian'), + 'class' => '\Drupal\Core\Datetime\Plugin\Type\Gregorian', + ), + ); +} + +/** * Defines available data types for the typed data API. * * The typed data API allows modules to support any kind of data based upon diff --git a/core/modules/system/system.module b/core/modules/system/system.module index 98b0427..78dd245 100644 --- a/core/modules/system/system.module +++ b/core/modules/system/system.module @@ -7,6 +7,7 @@ use Drupal\Core\Utility\ModuleInfo; use Drupal\Core\TypedData\Primitive; +use Drupal\Core\Datetime\Plugin\DateCalendar; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; @@ -480,11 +481,25 @@ function system_element_info() { ); $types['date'] = array( '#input' => TRUE, - '#element_validate' => array('date_validate'), - '#process' => array('form_process_date'), '#theme' => 'date', '#theme_wrappers' => array('form_element'), ); + $types['datetime'] = array( + '#input' => TRUE, + '#element_validate' => array('datetime_validate'), + '#process' => array('form_process_datetime'), + '#theme' => 'form_datetime', + '#theme_wrappers' => array('form_element'), + '#date_date_format' => variable_get('date_format_html_date', 'Y-m-d'), + '#date_date_element' => 'date', + '#date_date_callbacks' => array('datetime_jquery_datepicker_callback'), + '#date_time_format' => variable_get('date_format_html_time', 'H:i:s'), + '#date_time_element' => 'time', + '#date_time_callbacks' => array(), + '#date_year_range' => '1900:2050', + '#date_increment' => 1, + '#date_timezone' => '', + ); $types['file'] = array( '#input' => TRUE, '#size' => 60, @@ -1942,7 +1957,21 @@ function system_library_info() { array('system', 'drupalSettings'), ), ); - + $libraries['drupal.datepicker'] = array( + 'title' => 'Drupal datepicker', + 'version' => VERSION, + 'js' => array( + 'core/misc/datepicker.js' => array(), + ), + 'dependencies' => array( + array('system', 'jquery'), + array('system', 'jquery.ui.core'), + array('system', 'jquery.ui.datepicker'), + array('system', 'jquery.once'), + array('system', 'drupal'), + array('system', 'drupalSettings'), + ), + ); $libraries['drupal.system'] = array( 'title' => 'System', 'version' => VERSION, @@ -2005,6 +2034,29 @@ function system_stream_wrappers() { } /** + * Implements hook_datetime_calendar_info(). + */ +function system_datetime_calendar_info() { + return array( + 'gregorian' => array( + 'label' => t('Gregorian'), + 'class' => '\Drupal\Core\Datetime\Plugin\Type\Gregorian', + ), + ); +} + +/** +* Get system calendar information. +*/ +function system_calendar($calendar = NULL) { + if (!isset($calendar)) { + $calendar = config('system.calendar')->get('calendar'); + } + $plugin = new DateCalendar(); + return $plugin->createInstance($calendar); +} + +/** * Implements hook_data_type_info(). */ function system_data_type_info() { diff --git a/core/modules/system/tests/modules/datetime_test/datetime_test.info b/core/modules/system/tests/modules/datetime_test/datetime_test.info new file mode 100644 index 0000000..127781f --- /dev/null +++ b/core/modules/system/tests/modules/datetime_test/datetime_test.info @@ -0,0 +1,6 @@ +name = "Datetime Test" +description = "Support module for Datetime tests." +core = 8.x +package = Testing +version = VERSION +hidden = TRUE diff --git a/core/modules/system/tests/modules/datetime_test/datetime_test.module b/core/modules/system/tests/modules/datetime_test/datetime_test.module new file mode 100644 index 0000000..569b6f3 --- /dev/null +++ b/core/modules/system/tests/modules/datetime_test/datetime_test.module @@ -0,0 +1,19 @@ + array( + 'label' => t('Gamma'), + 'class' => '\Drupal\datetime_test\Gamma', + ), + ); +} + diff --git a/core/modules/system/tests/modules/datetime_test/lib/Drupal/datetime_test/Gamma.php b/core/modules/system/tests/modules/datetime_test/lib/Drupal/datetime_test/Gamma.php new file mode 100644 index 0000000..7eb3a76 --- /dev/null +++ b/core/modules/system/tests/modules/datetime_test/lib/Drupal/datetime_test/Gamma.php @@ -0,0 +1,273 @@ + 'Alpha', + 2 => 'Beta', + 3 => 'Gamma', + 4 => 'Delta', + ); + } + + /** + * Constructs a translated array of month name abbreviations + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of month abbreviations. + */ + public static function monthNamesAbbr($required = FALSE) {} + + /** + * Constructs an untranslated array of week days. + * + * @return array + * An array of week day names + */ + public static function weekDaysUntranslated() {} + + /** + * Returns a translated array of week names. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day names + */ + public static function weekDays($required = FALSE) {} + + /** + * Constructs a translated array of week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day abbreviations + */ + public static function weekDaysAbbr($required = FALSE) {} + + /** + * Constructs a translated array of 2-letter week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day 2 letter abbreviations + */ + public static function weekDaysAbbr2($required = FALSE) {} + + /** + * Constructs a translated array of 1-letter week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day 1 letter abbreviations + */ + public static function weekDaysAbbr1($required = FALSE) {} + + /** + * Reorders weekdays to match the first day of the week. + * + * @param array $weekdays + * An array of weekdays. + * + * @return array + * An array of weekdays reordered to match the first day of the week. + */ + public static function weekDaysOrdered($weekdays) {} + + /** + * Constructs an array of years in a specified range. + * + * @param int $min + * The minimum year in the array. + * @param int $max + * The maximum year in the array. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of years in the selected range. + */ + public static function years($min = 0, $max = 0, $required = FALSE) {} + + /** + * Constructs an array of days in a month. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $month + * (optional) The month in which to find the number of days. + * @param int $year + * (optional) The year in which to find the number of days. + * + * @return array + * An array of days for the selected month. + */ + public static function days($required = FALSE, $month = NULL, $year = NULL) {} + + /** + * Constructs an array of hours. + * + * @param string $format + * A date format string that indicates the format to use for the hours. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of hours in the selected format. + */ + public static function hours($format = 'H', $required = FALSE) {} + + /** + * Constructs an array of minutes. + * + * @param string $format + * A date format string that indicates the format to use for the minutes. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $increment + * A the integer value to increment the values. Defaults to 1. + * + * @return array + * An array of minutes in the selected format. + */ + public static function minutes($format = 'i', $required = FALSE, $increment = 1) {} + + /** + * Constructs an array of seconds. + * + * @param string $format + * A date format string that indicates the format to use for the seconds. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $increment + * A the integer value to increment the values. Defaults to 1. + * + * @return array + * An array of seconds in the selected format. + */ + public static function seconds($format = 's', $required = FALSE, $increment = 1) {} + + /** + * Constructs an array of AM and PM options. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of AM and PM options. + */ + public static function ampm($required = FALSE) {} + + /** + * Identifies the number of days in a month for a date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * + * @return integer + * The number of days in the month. + */ + public static function daysInMonth($date = NULL) {} + + /** + * Identifies the number of days in a year for a date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * + * @return integer + * The number of days in the year. + */ + public static function daysInYear($date = NULL) {} + + /** + * Returns day of week for a given date (0 = Sunday). + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * + * @return int + * The number of the day in the week. + */ + public static function dayOfWeek($date = NULL) {} + + /** + * Returns translated name of the day of week for a given date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to current date. + * @param string $abbr + * (optional) Whether to return the abbreviated name for that day. + * Defaults to TRUE. + * + * @return string + * The name of the day in the week for that date. + */ + public static function dayOfWeekName($date = NULL, $abbr = TRUE) {} + +} diff --git a/core/modules/system/tests/modules/form_test/form_test.module b/core/modules/system/tests/modules/form_test/form_test.module index 03b7cb8..eac8dda 100644 --- a/core/modules/system/tests/modules/form_test/form_test.module +++ b/core/modules/system/tests/modules/form_test/form_test.module @@ -1721,23 +1721,6 @@ function _form_test_disabled_elements($form, &$form_state) { '#disabled' => TRUE, ); - // Date. - $form['date'] = array( - '#type' => 'date', - '#title' => 'date', - '#disabled' => TRUE, - '#default_value' => array( - 'day' => 19, - 'month' => 11, - 'year' => 1978, - ), - '#test_hijack_value' => array( - 'day' => 20, - 'month' => 12, - 'year' => 1979, - ), - ); - // The #disabled state should propagate to children. $form['disabled_container'] = array( '#disabled' => TRUE, @@ -1751,6 +1734,17 @@ function _form_test_disabled_elements($form, &$form_state) { ); } + // Date. + $form['disabled_container']['disabled_container_datetime'] = array( + '#type' => 'datetime', + '#title' => 'datetime', + '#default_value' => '1978-11-01 10:30:00', + '#expected_value' => '1978-11-01 10:30:00 Europe/Berlin', + '#test_hijack_value' => '1978-12-02 11:30:00 Europe/Berlin', + '#date_timezone' => 'Europe/Berlin', + ); + + // Try to hijack the email field with a valid email. $form['disabled_container']['disabled_container_email'] = array( '#type' => 'email',