PageRenderTime 3ms CodeModel.GetById 3ms app.highlight 8ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/rainerborene/symphony-2
PHP | 230 lines | 77 code | 24 blank | 129 comment | 16 complexity | f3311b33b47c95ece062a6d670ec9f68 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 it's configuration
 10	  * values.
 11	  */
 12	Class DateTimeObj {
 13
 14		/**
 15		 * Uses PHP's date_default_timezone_set function to set the system
 16		 * timezone. If the timezone provided is invalid, a `E_USER_WARNING` will be
 17		 * raised.
 18		 *
 19		 * @link http://php.net/manual/en/function.date-default-timezone-set.php
 20		 * @link http://www.php.net/manual/en/timezones.php
 21		 * @param string $timezone
 22		 *  A valid timezone identifier, such as UTC or Europe/Lisbon
 23		 */
 24		public static function setDefaultTimezone($timezone){
 25			if(!@date_default_timezone_set($timezone)) trigger_error(__("Invalid timezone '{$timezone}'"), E_USER_WARNING);
 26		}
 27
 28		/**
 29		 * Validate a given date and time string
 30		 *
 31		 * @param string $string
 32		 *	A date and time string to validate
 33		 * @return boolean
 34		 *	Returns true for valid dates, otherwise false
 35		 */
 36		public static function validate($string) {
 37			$string = trim($string);
 38
 39			// String is empty or not a valid date string
 40			if(empty($string) || !strtotime(Lang::standardizeDate($string))) {
 41				return false;
 42			}
 43
 44			// String is a valid date
 45			else {
 46				return true;
 47			}
 48		}
 49
 50		/**
 51		 * Given a `$format`, and a `$timestamp`,
 52		 * return the date in the format provided. This function is a basic
 53		 * wrapper for PHP's DateTime object. If the `$timestamp` is omitted,
 54		 * the current timestamp will be used. Optionally, you pass a
 55		 * timezone identifier with this function to localise the output
 56		 *
 57		 * If you like to display a date in the backend, please make use
 58		 * of `DateTimeObj::format()` which allows date and time localization
 59		 *
 60		 * @see class.datetimeobj.php#format()
 61		 * @link http://www.php.net/manual/en/book.datetime.php
 62		 * @param string $format
 63		 *  A valid PHP date format
 64		 * @param integer $timestamp (optional)
 65		 *  A unix timestamp to format. 'now' or omitting this parameter will
 66		 *  result in the current time being used
 67		 * @param string $timezone (optional)
 68		 *  The timezone associated with the timestamp
 69		 * @return string
 70		 *  The formatted date
 71		 */
 72		public static function get($format, $timestamp = 'now', $timezone = null) {
 73			return self::format($timestamp, $format, false, $timezone);
 74		}
 75
 76		/**
 77		 * Formats the given date and time `$string` based on the given `$format`.
 78		 * Optionally the result will be localized and respect a timezone differing
 79		 * from the system default. The default output is ISO 8601.
 80		 *
 81		 * @since Symphony 2.2.1
 82		 * @param string $string (optional)
 83		 *  A string containing date and time, defaults to the current date and time
 84		 * @param string $format (optional)
 85		 *  A valid PHP date format, defaults to ISO 8601
 86		 * @param boolean $localize (optional)
 87		 *  Localizes the output, if true, defaults to true
 88		 * @param string $timezone (optional)
 89		 *  The timezone associated with the timestamp
 90		 * @return string
 91		 *  The formatted date
 92		 */
 93		public static function format($string = 'now', $format = DateTime::ISO8601, $localize = true, $timezone = null) {
 94
 95			// Current date and time
 96			if($string == 'now' || empty($string)) {
 97				$date = new DateTime();
 98			}
 99
100			// Timestamp
101			elseif(is_numeric($string)) {
102				$date = new Datetime(date(DateTime::ISO8601, $string));
103			}
104
105			// Attempt to parse the date provided against the Symphony configuration setting
106			// in an effort to better support multilingual date formats. Should this fail
107			// this block will fallback to using `strtotime`, which will parse the date assuming
108			// it's in an English format
109			else {
110				// Standardize date
111				// Convert date string to English
112				$string = Lang::standardizeDate($string);
113
114				// PHP 5.3: Apply Symphony date format using `createFromFormat`
115				if(method_exists('DateTime', 'createFromFormat')) {
116					$date = DateTime::createFromFormat(__SYM_DATETIME_FORMAT__, $string);
117					if($date === false) {
118						$date = DateTime::createFromFormat(__SYM_DATE_FORMAT__, $string);
119					}
120				}
121
122				// PHP 5.2: Fallback to `strptime`
123				else {
124					$date = strptime($string, DateTimeObj::dateFormatToStrftime(__SYM_DATETIME_FORMAT__));
125					if($date === false) {
126						$date = DateTimeObj::dateFormatToStrftime(__SYM_DATE_FORMAT__, $string);
127					}
128
129					if(is_array($date)) {
130						$date = date(DateTime::ISO8601, mktime(
131							// Time
132							$date['tm_hour'], $date['tm_min'], $date['tm_sec'],
133							// Date (Months since Jan / Years since 1900)
134							$date['tm_mon'] + 1, $date['tm_mday'], 1900 + $date['tm_year']
135						));
136						$date = new DateTime($date);
137					}
138				}
139
140				// Handle non-standard dates (ie. relative dates, tomorrow etc.)
141				if($date === false) {
142					$date = new DateTime($string);
143				}
144			}
145
146			// Timezone
147			if($timezone !== null) {
148				$date->setTimezone(new DateTimeZone($timezone));
149			}
150
151			// Format date
152			$date = $date->format($format);
153
154			// Localize date
155			// Convert date string from English back to the activated Language
156			if($localize === true) {
157				$date = Lang::localizeDate($date);
158			}
159
160			// Return custom formatted date, use ISO 8601 date by default
161			return $date;
162		}
163
164		/**
165		 * Convert a date format to a `strftime` format
166		 * Timezone conversion is done for unix. Windows users must exchange %z and %Z.
167		 *
168		 * Unsupported `date` formats : S, n, t, L, B, G, u, e, I, P, Z, c, r
169		 * Unsupported `strftime` formats : %U, %W, %C, %g, %r, %R, %T, %X, %c, %D, %F, %x
170		 *
171		 * @since Symphony 2.2.1
172		 * @link http://www.php.net/manual/en/function.strftime.php#96424
173		 * @param string $dateFormat a date format
174		 * @return string
175		 */
176		public static function dateFormatToStrftime($dateFormat) {
177			$caracs = array(
178				// Day - no strf eq : S
179				'd' => '%d', 'D' => '%a', 'j' => '%e', 'l' => '%A', 'N' => '%u', 'w' => '%w', 'z' => '%j',
180				// Week - no date eq : %U, %W
181				'W' => '%V',
182				// Month - no strf eq : n, t
183				'F' => '%B', 'm' => '%m', 'M' => '%b',
184				// Year - no strf eq : L; no date eq : %C, %g
185				'o' => '%G', 'Y' => '%Y', 'y' => '%y',
186				// Time - no strf eq : B, G, u; no date eq : %r, %R, %T, %X
187				'a' => '%P', 'A' => '%p', 'g' => '%l', 'h' => '%I', 'H' => '%H', 'i' => '%M', 's' => '%S',
188				// Timezone - no strf eq : e, I, P, Z
189				'O' => '%z', 'T' => '%Z',
190				// Full Date / Time - no strf eq : c, r; no date eq : %c, %D, %F, %x
191				'U' => '%s'
192			);
193
194			return strtr((string)$dateFormat, $caracs);
195		}
196
197		/**
198		 * A wrapper for get, this function will force the GMT timezone.
199		 *
200		 * @param string $format
201		 *  A valid PHP date format
202		 * @param integer $timestamp (optional)
203		 *  A unix timestamp to format. Omitting this parameter will
204		 *  result in the current time being used
205		 * @return string
206		 *  The formatted date in GMT
207		 */
208		public static function getGMT($format, $timestamp = 'now'){
209			return self::format($timestamp, $format, false, 'GMT');
210		}
211
212		/**
213		 * A wrapper for get, this function will return a HTML string representing
214		 * an `<abbr>` element which contained the formatted date of now, and an
215		 * RFC 2822 formatted date (Thu, 21 Dec 2000 16:01:07 +0200) as the title
216		 * attribute. Symphony uses this in it's status messages so that it can
217		 * dynamically update how long ago the action took place using Javascript.
218		 *
219		 * @param string $format
220		 *  A valid PHP date format
221		 * @return string
222		 *  A HTML string of an `<abbr>` element with a class of 'timeago' and the current
223		 *  date (RFC 2822) as the title element. The value is the current time as
224		 *  specified by the `$format`.
225		 */
226		public static function getTimeAgo($format){
227			return '<abbr class="timeago" title="' . self::get(DateTime::RFC2822) . '">' . self::get($format) . '</abbr>';
228		}
229
230	}