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