PageRenderTime 2ms CodeModel.GetById 14ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/symphony/lib/core/class.datetimeobj.php

https://bitbucket.org/bauhouse/symphony-2
PHP | 294 lines | 106 code | 31 blank | 157 comment | 27 complexity | 40708545572f0e0a7b16f3799cad1d56 MD5 | raw file
  1<?php
  2
  3	/**
  4	 * @package core
  5	 */
  6
  7	 /**
  8	  * The DateTimeObj provides static functions regarding dates in Symphony.
  9	  * Symphony will set the default timezone of the system using the value from
 10	  * the Configuration values. Alternatively a new settings can be set using the
 11	  * `setSettings` function. Symphony parses all input dates against the Configuration
 12	  * date formats by default for better support with non English dates.
 13	  */
 14	Class DateTimeObj {
 15
 16		/**
 17		 * Holds the various settings for the formats that the `DateTimeObj` should
 18		 * use when parsing input dates.
 19		 *
 20		 * @since Symphony 2.2.4
 21		 * @var array
 22		 */
 23		private static $settings = array();
 24
 25		/**
 26		 * This function takes an array of settings for `DateTimeObj` to use when parsing
 27		 * input dates. The following settings are supported, `time_format`, `date_format`,
 28		 * `datetime_separator` and `timezone`. This equates to Symphony's default `region`
 29		 * group set in the `Configuration` class. If any of these values are not provided
 30		 * the class will fallback to existing `self::$settings` values
 31		 *
 32		 * @since Symphony 2.2.4
 33		 * @param array $settings
 34		 *  An associative array of formats for this class to use to format
 35		 *  dates
 36		 */
 37		public static function setSettings(array $settings = array()) {
 38			// Date format
 39			if(isset($settings['date_format'])) {
 40				self::$settings['date_format'] = $settings['date_format'];
 41			}
 42
 43			// Time format
 44			if(isset($settings['time_format'])) {
 45				self::$settings['time_format'] = $settings['time_format'];
 46			}
 47
 48			// Datetime separator
 49			if(isset($settings['datetime_separator'])) {
 50				self::$settings['datetime_separator'] = $settings['datetime_separator'];
 51			}
 52			else if (!isset(self::$settings['datetime_separator'])) {
 53				self::$settings['datetime_separator'] = ' ';
 54			}
 55
 56			// Datetime format
 57			if(isset($settings['datetime_format'])) {
 58				self::$settings['datetime_format'] = $settings['datetime_format'];
 59			}
 60			else {
 61				self::$settings['datetime_format'] = self::$settings['date_format'] . self::$settings['datetime_separator'] . self::$settings['time_format'];
 62			}
 63
 64			// Timezone
 65			if(isset($settings['timezone'])) {
 66				self::$settings['timezone'] = $settings['timezone'];
 67				self::setDefaultTimezone($settings['timezone']);
 68			}
 69		}
 70
 71		/**
 72		 * Accessor function for the settings of the DateTimeObj. Currently
 73		 * the available settings are `time_format`, `date_format`,
 74		 * `datetime_format` and `datetime_separator`. If `$name` is not
 75		 * provided, the entire `$settings` array is returned.
 76		 *
 77		 * @since Symphony 2.2.4
 78		 * @param string $name
 79		 * @return array|string|null
 80		 *  If `$name` is omitted this function returns array.
 81		 *  If `$name` is not set, this fucntion returns `null`
 82		 *  If `$name` is set, this function returns string
 83		 */
 84		public static function getSetting($name = null) {
 85			if(is_null($name)) return self::$settings;
 86
 87			if(isset(self::$settings[$name])) return self::$settings[$name];
 88
 89			return null;
 90		}
 91
 92		/**
 93		 * Uses PHP's date_default_timezone_set function to set the system
 94		 * timezone. If the timezone provided is invalid, a `E_USER_WARNING` will be
 95		 * raised.
 96		 *
 97		 * @link http://php.net/manual/en/function.date-default-timezone-set.php
 98		 * @link http://www.php.net/manual/en/timezones.php
 99		 * @param string $timezone
100		 *  A valid timezone identifier, such as UTC or Europe/Lisbon
101		 */
102		public static function setDefaultTimezone($timezone){
103			if(!@date_default_timezone_set($timezone)) trigger_error(__("Invalid timezone '{$timezone}'"), E_USER_WARNING);
104		}
105
106		/**
107		 * Validate a given date and time string
108		 *
109		 * @param string $string
110		 *	A date and time string to validate
111		 * @return boolean
112		 *	Returns true for valid dates, otherwise false
113		 */
114		public static function validate($string) {
115			try {
116				$date = new DateTime(Lang::standardizeDate($string));
117			}
118			catch(Exception $ex) {
119				return false;
120			}
121
122			// String is empty or not a valid date
123			if(empty($string) || $date === false) {
124				return false;
125			}
126
127			// String is a valid date
128			else {
129				return true;
130			}
131		}
132
133		/**
134		 * Given a `$format`, and a `$timestamp`,
135		 * return the date in the format provided. This function is a basic
136		 * wrapper for PHP's DateTime object. If the `$timestamp` is omitted,
137		 * the current timestamp will be used. Optionally, you pass a
138		 * timezone identifier with this function to localise the output
139		 *
140		 * If you like to display a date in the backend, please make use
141		 * of `DateTimeObj::format()` which allows date and time localization
142		 *
143		 * @see class.datetimeobj.php#format()
144		 * @link http://www.php.net/manual/en/book.datetime.php
145		 * @param string $format
146		 *  A valid PHP date format
147		 * @param integer $timestamp (optional)
148		 *  A unix timestamp to format. 'now' or omitting this parameter will
149		 *  result in the current time being used
150		 * @param string $timezone (optional)
151		 *  The timezone associated with the timestamp
152		 * @return string|boolean
153		 *  The formatted date, of if the date could not be parsed, false.
154		 */
155		public static function get($format, $timestamp = 'now', $timezone = null) {
156			return self::format($timestamp, $format, false, $timezone);
157		}
158
159		/**
160		 * Formats the given date and time `$string` based on the given `$format`.
161		 * Optionally the result will be localized and respect a timezone differing
162		 * from the system default. The default output is ISO 8601.
163		 * Please note that for best compatibility with European dates it is recommended
164		 * that your site be in a PHP5.3 environment.
165		 *
166		 * @since Symphony 2.2.1
167		 * @param string $string (optional)
168		 *  A string containing date and time, defaults to the current date and time
169		 * @param string $format (optional)
170		 *  A valid PHP date format, defaults to ISO 8601
171		 * @param boolean $localize (optional)
172		 *  Localizes the output, if true, defaults to true
173		 * @param string $timezone (optional)
174		 *  The timezone associated with the timestamp
175		 * @return string|boolean
176		 *  The formatted date, of if the date could not be parsed, false.
177		 */
178		public static function format($string = 'now', $format = DateTime::ISO8601, $localize = true, $timezone = null) {
179
180			// Current date and time
181			if($string == 'now' || empty($string)) {
182				$date = new DateTime();
183			}
184
185			// Timestamp
186			elseif(is_numeric($string)) {
187				$date = new DateTime('@' . $string);
188			}
189
190			// Attempt to parse the date provided against the Symphony configuration setting
191			// in an effort to better support multilingual date formats. Should this fail
192			// this block will fallback to just passing the date to DateTime constructor,
193			// which will parse the date assuming it's in an English format.
194			else {
195				// Standardize date
196				// Convert date string to English
197				$string = Lang::standardizeDate($string);
198
199				// PHP 5.3: Apply Symphony date format using `createFromFormat`
200				if(method_exists('DateTime', 'createFromFormat')) {
201					$date = DateTime::createFromFormat(self::$settings['datetime_format'], $string);
202					if($date === false) {
203						$date = DateTime::createFromFormat(self::$settings['date_format'], $string);
204					}
205
206					// Handle dates that are in a different format to Symphony's config
207					// DateTime is much the same as `strtotime` and will handle relative
208					// dates.
209					if($date === false) {
210						try {
211							$date = new DateTime($string);
212						}
213						catch(Exception $ex) {
214							// Invalid date, it can't be parsed
215							return false;
216						}
217					}
218				}
219
220				// PHP 5.2: Fallback to DateTime parsing.
221				// Note that this parsing will not respect European dates.
222				else {
223					try {
224						$date = new DateTime($string);
225					}
226					catch(Exception $ex) {
227						// Invalid date, it can't be parsed
228						return false;
229					}
230				}
231
232				// If the date is still invalid, just return false.
233				if($date === false) {
234					return false;
235				}
236			}
237
238			// Timezone
239			// If a timezone was given, apply it
240			if($timezone !== null) {
241				$date->setTimezone(new DateTimeZone($timezone));
242			}
243			// No timezone given, apply the default timezone
244			else if (isset(self::$settings['timezone'])) {
245				$date->setTimezone(new DateTimeZone(self::$settings['timezone']));
246			}
247
248			// Format date
249			$date = $date->format($format);
250
251			// Localize date
252			// Convert date string from English back to the activated Language
253			if($localize === true) {
254				$date = Lang::localizeDate($date);
255			}
256
257			// Return custom formatted date, use ISO 8601 date by default
258			return $date;
259		}
260
261		/**
262		 * A wrapper for get, this function will force the GMT timezone.
263		 *
264		 * @param string $format
265		 *  A valid PHP date format
266		 * @param integer $timestamp (optional)
267		 *  A unix timestamp to format. Omitting this parameter will
268		 *  result in the current time being used
269		 * @return string
270		 *  The formatted date in GMT
271		 */
272		public static function getGMT($format, $timestamp = 'now'){
273			return self::format($timestamp, $format, false, 'GMT');
274		}
275
276		/**
277		 * A wrapper for get, this function will return a HTML string representing
278		 * an `<abbr>` element which contained the formatted date of now, and an
279		 * RFC 2822 formatted date (Thu, 21 Dec 2000 16:01:07 +0200) as the title
280		 * attribute. Symphony uses this in it's status messages so that it can
281		 * dynamically update how long ago the action took place using Javascript.
282		 *
283		 * @param string $format
284		 *  A valid PHP date format
285		 * @return string
286		 *  A HTML string of an `<abbr>` element with a class of 'timeago' and the current
287		 *  date (RFC 2822) as the title element. The value is the current time as
288		 *  specified by the `$format`.
289		 */
290		public static function getTimeAgo($format){
291			return '<abbr class="timeago" title="' . self::get(DateTime::RFC2822) . '">' . self::get($format) . '</abbr>';
292		}
293
294	}