date_api.module 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784
  1. <?php
  2. /**
  3. * @file
  4. * This module will make the date API available to other modules.
  5. * Designed to provide a light but flexible assortment of functions
  6. * and constants, with more functionality in additional files that
  7. * are not loaded unless other modules specifically include them.
  8. */
  9. /**
  10. * Set up some constants.
  11. *
  12. * Includes standard date types, format strings, strict regex strings for ISO
  13. * and DATETIME formats (seconds are optional).
  14. *
  15. * The loose regex will find any variety of ISO date and time, with or
  16. * without time, with or without dashes and colons separating the elements,
  17. * and with either a 'T' or a space separating date and time.
  18. */
  19. define('DATE_ISO', 'date');
  20. define('DATE_UNIX', 'datestamp');
  21. define('DATE_DATETIME', 'datetime');
  22. define('DATE_ARRAY', 'array');
  23. define('DATE_OBJECT', 'object');
  24. define('DATE_ICAL', 'ical');
  25. define('DATE_FORMAT_ISO', "Y-m-d\TH:i:s");
  26. define('DATE_FORMAT_UNIX', "U");
  27. define('DATE_FORMAT_DATETIME', "Y-m-d H:i:s");
  28. define('DATE_FORMAT_ICAL', "Ymd\THis");
  29. define('DATE_FORMAT_ICAL_DATE', "Ymd");
  30. define('DATE_FORMAT_DATE', 'Y-m-d');
  31. define('DATE_REGEX_ISO', '/(\d{4})?(-(\d{2}))?(-(\d{2}))?([T\s](\d{2}))?(:(\d{2}))?(:(\d{2}))?/');
  32. define('DATE_REGEX_DATETIME', '/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):?(\d{2})?/');
  33. define('DATE_REGEX_LOOSE', '/(\d{4})-?(\d{1,2})-?(\d{1,2})([T\s]?(\d{2}):?(\d{2}):?(\d{2})?(\.\d+)?(Z|[\+\-]\d{2}:?\d{2})?)?/');
  34. define('DATE_REGEX_ICAL_DATE', '/(\d{4})(\d{2})(\d{2})/');
  35. define('DATE_REGEX_ICAL_DATETIME', '/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z)?/');
  36. /**
  37. * Core DateTime extension module used for as many date operations as possible.
  38. */
  39. /**
  40. * Implements hook_help().
  41. */
  42. function date_help($path, $arg) {
  43. switch ($path) {
  44. case 'admin/help#date':
  45. $output = '';
  46. $messages = date_api_status();
  47. $output = '<h2>Date API Status</h2>';
  48. if (!empty($messages['success'])) {
  49. $output .= '<ul><li>' . implode('</li><li>', $messages['success']) . '</li></ul>';
  50. }
  51. if (!empty($messages['errors'])) {
  52. $output .= '<h3>Errors</h3><ul class="error"><li>' . implode('</li><li>', $messages['errors']) . '</li></ul>';
  53. }
  54. if (module_exists('date_tools')) {
  55. $output .= '<h3>Date Tools</h3>' . t('Dates and calendars can be complicated to set up. The !date_wizard makes it easy to create a simple date content type and with a date field. ', array('!date_wizard' => l(t('Date wizard'), 'admin/config/date/tools/date_wizard')));
  56. }
  57. else {
  58. $output .= '<h3>Date Tools</h3>' . t('Dates and calendars can be complicated to set up. If you enable the Date Tools module, it provides a Date Wizard that makes it easy to create a simple date content type with a date field. ');
  59. }
  60. $output .= '<h2>More Information</h2><p>' . t('Complete documentation for the Date and Date API modules is available at <a href="@link">http://drupal.org/node/92460</a>.', array('@link' => 'http://drupal.org/node/262062')) . '</p>';
  61. return $output;
  62. break;
  63. }
  64. }
  65. /**
  66. * Helper function to retun the status of required date variables.
  67. */
  68. function date_api_status() {
  69. $t = get_t();
  70. $error_messages = array();
  71. $success_messages = array();
  72. $value = variable_get('date_default_timezone');
  73. if (isset($value)) {
  74. $success_messages[] = $t('The timezone has been set to <a href="@regional_settings">@timezone</a>.', array('@regional_settings' => url('admin/config/regional/settings'), '@timezone' => $value));
  75. }
  76. else {
  77. $error_messages[] = $t('The Date API requires that you set up the <a href="@regional_settings">site timezone</a> to function correctly.', array('@regional_settings' => url('admin/config/regional/settings')));
  78. }
  79. $value = variable_get('date_first_day');
  80. if (isset($value)) {
  81. $days = date_week_days();
  82. $success_messages[] = $t('The first day of the week has been set to <a href="@regional_settings">@day</a>.', array('@regional_settings' => url('admin/config/regional/settings'), '@day' => $days[$value]));
  83. }
  84. else {
  85. $error_messages[] = $t('The Date API requires that you set up the <a href="@regional_settings">site first day of week settings</a> to function correctly.', array('@regional_settings' => url('admin/config/regional/settings')));
  86. }
  87. $value = variable_get('date_format_medium');
  88. if (isset($value)) {
  89. $now = date_now();
  90. $success_messages[] = $t('The medium date format type has been set to to @value. You may find it helpful to add new format types like Date, Time, Month, or Year, with appropriate formats, at <a href="@regional_date_time">Date and time</a> settings.', array('@value' => $now->format($value), '@regional_date_time' => url('admin/config/regional/date-time')));
  91. }
  92. else {
  93. $error_messages[] = $t('The Date API requires that you set up the <a href="@regional_date_time">system date formats</a> to function correctly.', array('@regional_date_time' => url('admin/config/regional/date-time')));
  94. }
  95. return array('errors', $error_messages, 'success' => $success_messages);
  96. }
  97. /**
  98. * Implements hook_menu().
  99. *
  100. * Creates a 'Date API' section on the administration page for Date
  101. * modules to use for their configuration and settings.
  102. */
  103. function date_api_menu() {
  104. $items['admin/config/date'] = array(
  105. 'title' => 'Date API',
  106. 'description' => 'Settings for modules the use the Date API.',
  107. 'position' => 'left',
  108. 'weight' => -10,
  109. 'page callback' => 'system_admin_menu_block_page',
  110. 'access arguments' => array('administer site configuration'),
  111. 'file' => 'system.admin.inc',
  112. 'file path' => drupal_get_path('module', 'system'),
  113. );
  114. return $items;
  115. }
  116. /**
  117. * Extend PHP DateTime class with granularity handling, merge functionality and
  118. * slightly more flexible initialization parameters.
  119. *
  120. * This class is a Drupal independent extension of the >= PHP 5.2 DateTime
  121. * class.
  122. *
  123. * @see FeedsDateTimeElement class
  124. */
  125. class DateObject extends DateTime {
  126. public $granularity = array();
  127. public $errors = array();
  128. protected static $allgranularity = array('year', 'month', 'day', 'hour', 'minute', 'second', 'timezone');
  129. private $serializedTime;
  130. private $serializedTimezone;
  131. /**
  132. * Prepares the object during serialization.
  133. *
  134. * We are extending a core class and core classes cannot be serialized.
  135. *
  136. * @return array
  137. * Returns an array with the names of the variables that were serialized.
  138. *
  139. * @see http://bugs.php.net/41334
  140. * @see http://bugs.php.net/39821
  141. */
  142. public function __sleep() {
  143. $this->serializedTime = $this->format('c');
  144. $this->serializedTimezone = $this->getTimezone()->getName();
  145. return array('serializedTime', 'serializedTimezone');
  146. }
  147. /**
  148. * Re-builds the object using local variables.
  149. */
  150. public function __wakeup() {
  151. $this->__construct($this->serializedTime, new DateTimeZone($this->serializedTimezone));
  152. }
  153. /**
  154. * Returns the date object as a string.
  155. *
  156. * @return string
  157. * The date object formatted as a string.
  158. */
  159. public function __toString() {
  160. return $this->format(DATE_FORMAT_DATETIME) . ' ' . $this->getTimeZone()->getName();
  161. }
  162. /**
  163. * Constructs a date object.
  164. *
  165. * @param string $time
  166. * A date/time string or array. Defaults to 'now'.
  167. * @param object|string|null $tz
  168. * PHP DateTimeZone object, string or NULL allowed. Defaults to NULL.
  169. * @param string $format
  170. * PHP date() type format for parsing. Doesn't support timezones; if you
  171. * have a timezone, send NULL and the default constructor method will
  172. * hopefully parse it. $format is recommended in order to use negative or
  173. * large years, which php's parser fails on.
  174. */
  175. public function __construct($time = 'now', $tz = NULL, $format = NULL) {
  176. $this->timeOnly = FALSE;
  177. $this->dateOnly = FALSE;
  178. // Store the raw time input so it is available for validation.
  179. $this->originalTime = $time;
  180. // Allow string timezones.
  181. if (!empty($tz) && !is_object($tz)) {
  182. $tz = new DateTimeZone($tz);
  183. }
  184. // Default to the site timezone when not explicitly provided.
  185. elseif (empty($tz)) {
  186. $tz = date_default_timezone_object();
  187. }
  188. // Special handling for Unix timestamps expressed in the local timezone.
  189. // Create a date object in UTC and convert it to the local timezone. Don't
  190. // try to turn things like '2010' with a format of 'Y' into a timestamp.
  191. if (is_numeric($time) && (empty($format) || $format == 'U')) {
  192. // Assume timestamp.
  193. $time = "@" . $time;
  194. $date = new DateObject($time, 'UTC');
  195. if ($tz->getName() != 'UTC') {
  196. $date->setTimezone($tz);
  197. }
  198. $time = $date->format(DATE_FORMAT_DATETIME);
  199. $format = DATE_FORMAT_DATETIME;
  200. $this->addGranularity('timezone');
  201. }
  202. elseif (is_array($time)) {
  203. // Assume we were passed an indexed array.
  204. if (empty($time['year']) && empty($time['month']) && empty($time['day'])) {
  205. $this->timeOnly = TRUE;
  206. }
  207. if (empty($time['hour']) && empty($time['minute']) && empty($time['second'])) {
  208. $this->dateOnly = TRUE;
  209. }
  210. $this->errors = $this->arrayErrors($time);
  211. // Make this into an ISO date, forcing a full ISO date even if some values
  212. // are missing.
  213. $time = $this->toISO($time, TRUE);
  214. // We checked for errors already, skip parsing the input values.
  215. $format = NULL;
  216. }
  217. else {
  218. // Make sure dates like 2010-00-00T00:00:00 get converted to
  219. // 2010-01-01T00:00:00 before creating a date object
  220. // to avoid unintended changes in the month or day.
  221. $time = date_make_iso_valid($time);
  222. }
  223. // The parse function will also set errors on the date parts.
  224. if (!empty($format)) {
  225. $arg = self::$allgranularity;
  226. $element = array_pop($arg);
  227. while (!$this->parse($time, $tz, $format) && $element != 'year') {
  228. $element = array_pop($arg);
  229. $format = date_limit_format($format, $arg);
  230. }
  231. if ($element == 'year') {
  232. return FALSE;
  233. }
  234. }
  235. elseif (is_string($time)) {
  236. // PHP < 5.3 doesn't like the GMT- notation for parsing timezones.
  237. $time = str_replace("GMT-", "-", $time);
  238. $time = str_replace("GMT+", "+", $time);
  239. // We are going to let the parent dateObject do a best effort attempt to
  240. // turn this string into a valid date. It might fail and we want to
  241. // control the error messages.
  242. try {
  243. @parent::__construct($time, $tz);
  244. }
  245. catch (Exception $e) {
  246. $this->errors['date'] = $e;
  247. return;
  248. }
  249. if (empty($this->granularity)) {
  250. $this->setGranularityFromTime($time, $tz);
  251. }
  252. }
  253. // If we haven't got a valid timezone name yet, we need to set one or
  254. // we will get undefined index errors.
  255. // This can happen if $time had an offset or no timezone.
  256. if (!$this->getTimezone() || !preg_match('/[a-zA-Z]/', $this->getTimezone()->getName())) {
  257. // If the original $tz has a name, use it.
  258. if (preg_match('/[a-zA-Z]/', $tz->getName())) {
  259. $this->setTimezone($tz);
  260. }
  261. // We have no information about the timezone so must fallback to a default.
  262. else {
  263. $this->setTimezone(new DateTimeZone("UTC"));
  264. $this->errors['timezone'] = t('No valid timezone name was provided.');
  265. }
  266. }
  267. }
  268. /**
  269. * Merges two date objects together using the current date values as defaults.
  270. *
  271. * @param object $other
  272. * Another date object to merge with.
  273. *
  274. * @return object
  275. * A merged date object.
  276. */
  277. public function merge(FeedsDateTime $other) {
  278. $other_tz = $other->getTimezone();
  279. $this_tz = $this->getTimezone();
  280. // Figure out which timezone to use for combination.
  281. $use_tz = ($this->hasGranularity('timezone') || !$other->hasGranularity('timezone')) ? $this_tz : $other_tz;
  282. $this2 = clone $this;
  283. $this2->setTimezone($use_tz);
  284. $other->setTimezone($use_tz);
  285. $val = $this2->toArray(TRUE);
  286. $otherval = $other->toArray();
  287. foreach (self::$allgranularity as $g) {
  288. if ($other->hasGranularity($g) && !$this2->hasGranularity($g)) {
  289. // The other class has a property we don't; steal it.
  290. $this2->addGranularity($g);
  291. $val[$g] = $otherval[$g];
  292. }
  293. }
  294. $other->setTimezone($other_tz);
  295. $this2->setDate($val['year'], $val['month'], $val['day']);
  296. $this2->setTime($val['hour'], $val['minute'], $val['second']);
  297. return $this2;
  298. }
  299. /**
  300. * Sets the time zone for the current date.
  301. *
  302. * Overrides default DateTime function. Only changes output values if
  303. * actually had time granularity. This should be used as a "converter" for
  304. * output, to switch tzs.
  305. *
  306. * In order to set a timezone for a datetime that doesn't have such
  307. * granularity, merge() it with one that does.
  308. *
  309. * @param object $tz
  310. * A timezone object.
  311. * @param bool $force
  312. * Whether or not to skip a date with no time. Defaults to FALSE.
  313. */
  314. public function setTimezone($tz, $force = FALSE) {
  315. // PHP 5.2.6 has a fatal error when setting a date's timezone to itself.
  316. // http://bugs.php.net/bug.php?id=45038
  317. if (version_compare(PHP_VERSION, '5.2.7', '<') && $tz == $this->getTimezone()) {
  318. $tz = new DateTimeZone($tz->getName());
  319. }
  320. if (!$this->hasTime() || !$this->hasGranularity('timezone') || $force) {
  321. // This has no time or timezone granularity, so timezone doesn't mean
  322. // much. We set the timezone using the method, which will change the
  323. // day/hour, but then we switch back.
  324. $arr = $this->toArray(TRUE);
  325. parent::setTimezone($tz);
  326. $this->setDate($arr['year'], $arr['month'], $arr['day']);
  327. $this->setTime($arr['hour'], $arr['minute'], $arr['second']);
  328. $this->addGranularity('timezone');
  329. return;
  330. }
  331. return parent::setTimezone($tz);
  332. }
  333. /**
  334. * Returns date formatted according to given format.
  335. *
  336. * Overrides base format function, formats this date according to its
  337. * available granularity, unless $force'ed not to limit to granularity.
  338. *
  339. * @TODO Add translation into this so translated names will be provided.
  340. *
  341. * @param string $format
  342. * A date format string.
  343. * @param bool $force
  344. * Whether or not to limit the granularity. Defaults to FALSE.
  345. *
  346. * @return string|false
  347. * Returns the formatted date string on success or FALSE on failure.
  348. */
  349. public function format($format, $force = FALSE) {
  350. return parent::format($force ? $format : date_limit_format($format, $this->granularity));
  351. }
  352. /**
  353. * Adds a granularity entry to the array.
  354. *
  355. * @param string $g
  356. * A single date part.
  357. */
  358. public function addGranularity($g) {
  359. $this->granularity[] = $g;
  360. $this->granularity = array_unique($this->granularity);
  361. }
  362. /**
  363. * Removes a granularity entry from the array.
  364. *
  365. * @param string $g
  366. * A single date part.
  367. */
  368. public function removeGranularity($g) {
  369. if ($key = array_search($g, $this->granularity)) {
  370. unset($this->granularity[$key]);
  371. }
  372. }
  373. /**
  374. * Checks granularity array for a given entry.
  375. *
  376. * @param array|null $g
  377. * An array of date parts. Defaults to NULL.
  378. *
  379. * @returns bool
  380. * TRUE if the date part is present in the date's granularity.
  381. */
  382. public function hasGranularity($g = NULL) {
  383. if ($g === NULL) {
  384. // Just want to know if it has something valid means no lower
  385. // granularities without higher ones.
  386. $last = TRUE;
  387. foreach (self::$allgranularity as $arg) {
  388. if ($arg == 'timezone') {
  389. continue;
  390. }
  391. if (in_array($arg, $this->granularity) && !$last) {
  392. return FALSE;
  393. }
  394. $last = in_array($arg, $this->granularity);
  395. }
  396. return in_array('year', $this->granularity);
  397. }
  398. if (is_array($g)) {
  399. foreach ($g as $gran) {
  400. if (!in_array($gran, $this->granularity)) {
  401. return FALSE;
  402. }
  403. }
  404. return TRUE;
  405. }
  406. return in_array($g, $this->granularity);
  407. }
  408. /**
  409. * Determines if a a date is valid for a given granularity.
  410. *
  411. * @param array|null $granularity
  412. * An array of date parts. Defaults to NULL.
  413. * @param bool $flexible
  414. * TRUE if the granuliarty is flexible, FALSE otherwise. Defaults to FALSE.
  415. *
  416. * @return bool
  417. * Whether a date is valid for a given granularity.
  418. */
  419. public function validGranularity($granularity = NULL, $flexible = FALSE) {
  420. $true = $this->hasGranularity() && (!$granularity || $flexible || $this->hasGranularity($granularity));
  421. if (!$true && $granularity) {
  422. foreach ((array) $granularity as $part) {
  423. if (!$this->hasGranularity($part) && in_array($part, array('second', 'minute', 'hour', 'day', 'month', 'year'))) {
  424. switch ($part) {
  425. case 'second':
  426. $this->errors[$part] = t('The second is missing.');
  427. break;
  428. case 'minute':
  429. $this->errors[$part] = t('The minute is missing.');
  430. break;
  431. case 'hour':
  432. $this->errors[$part] = t('The hour is missing.');
  433. break;
  434. case 'day':
  435. $this->errors[$part] = t('The day is missing.');
  436. break;
  437. case 'month':
  438. $this->errors[$part] = t('The month is missing.');
  439. break;
  440. case 'year':
  441. $this->errors[$part] = t('The year is missing.');
  442. break;
  443. }
  444. }
  445. }
  446. }
  447. return $true;
  448. }
  449. /**
  450. * Returns whether this object has time set.
  451. *
  452. * Used primarily for timezone conversion and formatting.
  453. *
  454. * @return bool
  455. * TRUE if the date contains time parts, FALSE otherwise.
  456. */
  457. public function hasTime() {
  458. return $this->hasGranularity('hour');
  459. }
  460. /**
  461. * Returns whether the input values included a year.
  462. *
  463. * Useful to use pseudo date objects when we only are interested in the time.
  464. *
  465. * @todo $this->completeDate does not actually exist?
  466. */
  467. public function completeDate() {
  468. return $this->completeDate;
  469. }
  470. /**
  471. * Removes unwanted date parts from a date.
  472. *
  473. * In common usage we should not unset timezone through this.
  474. *
  475. * @param array $granularity
  476. * An array of date parts.
  477. */
  478. public function limitGranularity($granularity) {
  479. foreach ($this->granularity as $key => $val) {
  480. if ($val != 'timezone' && !in_array($val, $granularity)) {
  481. unset($this->granularity[$key]);
  482. }
  483. }
  484. }
  485. /**
  486. * Determines the granularity of a date based on the constructor's arguments.
  487. *
  488. * @param string $time
  489. * A date string.
  490. * @param bool $tz
  491. * TRUE if the date has a timezone, FALSE otherwise.
  492. */
  493. protected function setGranularityFromTime($time, $tz) {
  494. $this->granularity = array();
  495. $temp = date_parse($time);
  496. // Special case for 'now'.
  497. if ($time == 'now') {
  498. $this->granularity = array('year', 'month', 'day', 'hour', 'minute', 'second');
  499. }
  500. else {
  501. // This PHP date_parse() method currently doesn't have resolution down to
  502. // seconds, so if there is some time, all will be set.
  503. foreach (self::$allgranularity as $g) {
  504. if ((isset($temp[$g]) && is_numeric($temp[$g])) || ($g == 'timezone' && (isset($temp['zone_type']) && $temp['zone_type'] > 0))) {
  505. $this->granularity[] = $g;
  506. }
  507. }
  508. }
  509. if ($tz) {
  510. $this->addGranularity('timezone');
  511. }
  512. }
  513. /**
  514. * Converts a date string into a date object.
  515. *
  516. * @param string $date
  517. * The date string to parse.
  518. * @param object $tz
  519. * A timezone object.
  520. * @param string $format
  521. * The date format string.
  522. *
  523. * @return object
  524. * Returns the date object.
  525. */
  526. protected function parse($date, $tz, $format) {
  527. $array = date_format_patterns();
  528. foreach ($array as $key => $value) {
  529. // The letter with no preceding '\'.
  530. $patterns[] = "`(^|[^\\\\\\\\])" . $key . "`";
  531. // A single character.
  532. $repl1[] = '${1}(.)';
  533. // The.
  534. $repl2[] = '${1}(' . $value . ')';
  535. }
  536. $patterns[] = "`\\\\\\\\([" . implode(array_keys($array)) . "])`";
  537. $repl1[] = '${1}';
  538. $repl2[] = '${1}';
  539. $format_regexp = preg_quote($format);
  540. // Extract letters.
  541. $regex1 = preg_replace($patterns, $repl1, $format_regexp, 1);
  542. $regex1 = str_replace('A', '(.)', $regex1);
  543. $regex1 = str_replace('a', '(.)', $regex1);
  544. preg_match('`^' . $regex1 . '$`', stripslashes($format), $letters);
  545. array_shift($letters);
  546. // Extract values.
  547. $regex2 = preg_replace($patterns, $repl2, $format_regexp, 1);
  548. $regex2 = str_replace('A', '(AM|PM)', $regex2);
  549. $regex2 = str_replace('a', '(am|pm)', $regex2);
  550. preg_match('`^' . $regex2 . '$`u', $date, $values);
  551. array_shift($values);
  552. // If we did not find all the values for the patterns in the format, abort.
  553. if (count($letters) != count($values)) {
  554. $this->errors['invalid'] = t('The value @date does not match the expected format.', array('@date' => $date));
  555. return FALSE;
  556. }
  557. $this->granularity = array();
  558. $final_date = array('hour' => 0, 'minute' => 0, 'second' => 0, 'month' => 1, 'day' => 1, 'year' => 0);
  559. foreach ($letters as $i => $letter) {
  560. $value = $values[$i];
  561. switch ($letter) {
  562. case 'd':
  563. case 'j':
  564. $final_date['day'] = intval($value);
  565. $this->addGranularity('day');
  566. break;
  567. case 'n':
  568. case 'm':
  569. $final_date['month'] = intval($value);
  570. $this->addGranularity('month');
  571. break;
  572. case 'F':
  573. $array_month_long = array_flip(date_month_names());
  574. $final_date['month'] = array_key_exists($value, $array_month_long) ? $array_month_long[$value] : -1;
  575. $this->addGranularity('month');
  576. break;
  577. case 'M':
  578. $array_month = array_flip(date_month_names_abbr());
  579. $final_date['month'] = array_key_exists($value, $array_month) ? $array_month[$value] : -1;
  580. $this->addGranularity('month');
  581. break;
  582. case 'Y':
  583. $final_date['year'] = $value;
  584. $this->addGranularity('year');
  585. if (strlen($value) < 4) {
  586. $this->errors['year'] = t('The year is invalid. Please check that entry includes four digits.');
  587. }
  588. break;
  589. case 'y':
  590. $year = $value;
  591. // If no century, we add the current one ("06" => "2006").
  592. $final_date['year'] = str_pad($year, 4, substr(date("Y"), 0, 2), STR_PAD_LEFT);
  593. $this->addGranularity('year');
  594. break;
  595. case 'a':
  596. case 'A':
  597. $ampm = strtolower($value);
  598. break;
  599. case 'g':
  600. case 'h':
  601. case 'G':
  602. case 'H':
  603. $final_date['hour'] = intval($value);
  604. $this->addGranularity('hour');
  605. break;
  606. case 'i':
  607. $final_date['minute'] = intval($value);
  608. $this->addGranularity('minute');
  609. break;
  610. case 's':
  611. $final_date['second'] = intval($value);
  612. $this->addGranularity('second');
  613. break;
  614. case 'U':
  615. parent::__construct($value, $tz ? $tz : new DateTimeZone("UTC"));
  616. $this->addGranularity('year');
  617. $this->addGranularity('month');
  618. $this->addGranularity('day');
  619. $this->addGranularity('hour');
  620. $this->addGranularity('minute');
  621. $this->addGranularity('second');
  622. return $this;
  623. break;
  624. }
  625. }
  626. if (isset($ampm) && $ampm == 'pm' && $final_date['hour'] < 12) {
  627. $final_date['hour'] += 12;
  628. }
  629. elseif (isset($ampm) && $ampm == 'am' && $final_date['hour'] == 12) {
  630. $final_date['hour'] -= 12;
  631. }
  632. // Blank becomes current time, given TZ.
  633. parent::__construct('', $tz ? $tz : new DateTimeZone("UTC"));
  634. if ($tz) {
  635. $this->addGranularity('timezone');
  636. }
  637. // SetDate expects an integer value for the year, results can be unexpected
  638. // if we feed it something like '0100' or '0000'.
  639. $final_date['year'] = intval($final_date['year']);
  640. $this->errors += $this->arrayErrors($final_date);
  641. $granularity = drupal_map_assoc($this->granularity);
  642. // If the input value is '0000-00-00', PHP's date class will later
  643. // incorrectly convert it to something like '-0001-11-30' if we do setDate()
  644. // here. If we don't do setDate() here, it will default to the current date
  645. // and we will lose any way to tell that there was no date in the orignal
  646. // input values. So set a flag we can use later to tell that this date
  647. // object was created using only time values, and that the date values are
  648. // artifical.
  649. if (empty($final_date['year']) && empty($final_date['month']) && empty($final_date['day'])) {
  650. $this->timeOnly = TRUE;
  651. }
  652. elseif (empty($this->errors)) {
  653. // setDate() expects a valid year, month, and day.
  654. // Set some defaults for dates that don't use this to
  655. // keep PHP from interpreting it as the last day of
  656. // the previous month or last month of the previous year.
  657. if (empty($granularity['month'])) {
  658. $final_date['month'] = 1;
  659. }
  660. if (empty($granularity['day'])) {
  661. $final_date['day'] = 1;
  662. }
  663. $this->setDate($final_date['year'], $final_date['month'], $final_date['day']);
  664. }
  665. if (!isset($final_date['hour']) && !isset($final_date['minute']) && !isset($final_date['second'])) {
  666. $this->dateOnly = TRUE;
  667. }
  668. elseif (empty($this->errors)) {
  669. $this->setTime($final_date['hour'], $final_date['minute'], $final_date['second']);
  670. }
  671. return $this;
  672. }
  673. /**
  674. * Returns all standard date parts in an array.
  675. *
  676. * Will return '' for parts in which it lacks granularity.
  677. *
  678. * @param bool $force
  679. * Whether or not to limit the granularity. Defaults to FALSE.
  680. *
  681. * @return array
  682. * An array of formatted date part values, keyed by date parts.
  683. */
  684. public function toArray($force = FALSE) {
  685. return array(
  686. 'year' => $this->format('Y', $force),
  687. 'month' => $this->format('n', $force),
  688. 'day' => $this->format('j', $force),
  689. 'hour' => intval($this->format('H', $force)),
  690. 'minute' => intval($this->format('i', $force)),
  691. 'second' => intval($this->format('s', $force)),
  692. 'timezone' => $this->format('e', $force),
  693. );
  694. }
  695. /**
  696. * Creates an ISO date from an array of values.
  697. *
  698. * @param array $arr
  699. * An array of date values keyed by date part.
  700. * @param bool $full
  701. * (optional) Whether to force a full date by filling in missing values.
  702. * Defaults to FALSE.
  703. */
  704. public function toISO($arr, $full = FALSE) {
  705. // Add empty values to avoid errors. The empty values must create a valid
  706. // date or we will get date slippage, i.e. a value of 2011-00-00 will get
  707. // interpreted as November of 2010 by PHP.
  708. if ($full) {
  709. $arr += array('year' => 0, 'month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0, 'second' => 0);
  710. }
  711. else {
  712. $arr += array('year' => '', 'month' => '', 'day' => '', 'hour' => '', 'minute' => '', 'second' => '');
  713. }
  714. $datetime = '';
  715. if ($arr['year'] !== '') {
  716. $datetime = date_pad(intval($arr['year']), 4);
  717. if ($full || $arr['month'] !== '') {
  718. $datetime .= '-' . date_pad(intval($arr['month']));
  719. if ($full || $arr['day'] !== '') {
  720. $datetime .= '-' . date_pad(intval($arr['day']));
  721. }
  722. }
  723. }
  724. if ($arr['hour'] !== '') {
  725. $datetime .= $datetime ? 'T' : '';
  726. $datetime .= date_pad(intval($arr['hour']));
  727. if ($full || $arr['minute'] !== '') {
  728. $datetime .= ':' . date_pad(intval($arr['minute']));
  729. if ($full || $arr['second'] !== '') {
  730. $datetime .= ':' . date_pad(intval($arr['second']));
  731. }
  732. }
  733. }
  734. return $datetime;
  735. }
  736. /**
  737. * Forces an incomplete date to be valid.
  738. *
  739. * E.g., add a valid year, month, and day if only the time has been defined.
  740. *
  741. * @param array|string $date
  742. * An array of date parts or a datetime string with values to be massaged
  743. * into a valid date object.
  744. * @param string $format
  745. * (optional) The format of the date. Defaults to NULL.
  746. * @param string $default
  747. * (optional) If the fallback should use the first value of the date part,
  748. * or the current value of the date part. Defaults to 'first'.
  749. */
  750. public function setFuzzyDate($date, $format = NULL, $default = 'first') {
  751. $timezone = $this->getTimeZone() ? $this->getTimeZone()->getName() : NULL;
  752. $comp = new DateObject($date, $timezone, $format);
  753. $arr = $comp->toArray(TRUE);
  754. foreach ($arr as $key => $value) {
  755. // Set to intval here and then test that it is still an integer.
  756. // Needed because sometimes valid integers come through as strings.
  757. $arr[$key] = $this->forceValid($key, intval($value), $default, $arr['month'], $arr['year']);
  758. }
  759. $this->setDate($arr['year'], $arr['month'], $arr['day']);
  760. $this->setTime($arr['hour'], $arr['minute'], $arr['second']);
  761. }
  762. /**
  763. * Converts a date part into something that will produce a valid date.
  764. *
  765. * @param string $part
  766. * The date part.
  767. * @param int $value
  768. * The date value for this part.
  769. * @param string $default
  770. * (optional) If the fallback should use the first value of the date part,
  771. * or the current value of the date part. Defaults to 'first'.
  772. * @param int $month
  773. * (optional) Used when the date part is less than 'month' to specify the
  774. * date. Defaults to NULL.
  775. * @param int $year
  776. * (optional) Used when the date part is less than 'year' to specify the
  777. * date. Defaults to NULL.
  778. *
  779. * @return int
  780. * A valid date value.
  781. */
  782. protected function forceValid($part, $value, $default = 'first', $month = NULL, $year = NULL) {
  783. $now = date_now();
  784. switch ($part) {
  785. case 'year':
  786. $fallback = $now->format('Y');
  787. return !is_int($value) || empty($value) || $value < variable_get('date_min_year', 1) || $value > variable_get('date_max_year', 4000) ? $fallback : $value;
  788. break;
  789. case 'month':
  790. $fallback = $default == 'first' ? 1 : $now->format('n');
  791. return !is_int($value) || empty($value) || $value <= 0 || $value > 12 ? $fallback : $value;
  792. break;
  793. case 'day':
  794. $fallback = $default == 'first' ? 1 : $now->format('j');
  795. $max_day = isset($year) && isset($month) ? date_days_in_month($year, $month) : 31;
  796. return !is_int($value) || empty($value) || $value <= 0 || $value > $max_day ? $fallback : $value;
  797. break;
  798. case 'hour':
  799. $fallback = $default == 'first' ? 0 : $now->format('G');
  800. return !is_int($value) || $value < 0 || $value > 23 ? $fallback : $value;
  801. break;
  802. case 'minute':
  803. $fallback = $default == 'first' ? 0 : $now->format('i');
  804. return !is_int($value) || $value < 0 || $value > 59 ? $fallback : $value;
  805. break;
  806. case 'second':
  807. $fallback = $default == 'first' ? 0 : $now->format('s');
  808. return !is_int($value) || $value < 0 || $value > 59 ? $fallback : $value;
  809. break;
  810. }
  811. }
  812. /**
  813. * Finds possible errors in an array of date part values.
  814. *
  815. * The forceValid() function will change an invalid value to a valid one, so
  816. * we just need to see if the value got altered.
  817. *
  818. * @param array $arr
  819. * An array of date values, keyed by date part.
  820. *
  821. * @return array
  822. * An array of error messages, keyed by date part.
  823. */
  824. public function arrayErrors($arr) {
  825. $errors = array();
  826. $now = date_now();
  827. $default_month = !empty($arr['month']) ? $arr['month'] : $now->format('n');
  828. $default_year = !empty($arr['year']) ? $arr['year'] : $now->format('Y');
  829. $this->granularity = array();
  830. foreach ($arr as $part => $value) {
  831. // Explicitly set the granularity to the values in the input array.
  832. if (is_numeric($value)) {
  833. $this->addGranularity($part);
  834. }
  835. // Avoid false errors when a numeric value is input as a string by casting
  836. // as an integer.
  837. $value = intval($value);
  838. if (!empty($value) && $this->forceValid($part, $value, 'now', $default_month, $default_year) != $value) {
  839. // Use a switch/case to make translation easier by providing a different
  840. // message for each part.
  841. switch ($part) {
  842. case 'year':
  843. $errors['year'] = t('The year is invalid.');
  844. break;
  845. case 'month':
  846. $errors['month'] = t('The month is invalid.');
  847. break;
  848. case 'day':
  849. $errors['day'] = t('The day is invalid.');
  850. break;
  851. case 'hour':
  852. $errors['hour'] = t('The hour is invalid.');
  853. break;
  854. case 'minute':
  855. $errors['minute'] = t('The minute is invalid.');
  856. break;
  857. case 'second':
  858. $errors['second'] = t('The second is invalid.');
  859. break;
  860. }
  861. }
  862. }
  863. if ($this->hasTime()) {
  864. $this->addGranularity('timezone');
  865. }
  866. return $errors;
  867. }
  868. /**
  869. * Computes difference between two days using a given measure.
  870. *
  871. * @param object $date2_in
  872. * The stop date.
  873. * @param string $measure
  874. * (optional) A granularity date part. Defaults to 'seconds'.
  875. * @param boolean $absolute
  876. * (optional) Indicate whether the absolute value of the difference should
  877. * be returned or if the sign should be retained. Defaults to TRUE.
  878. */
  879. public function difference($date2_in, $measure = 'seconds', $absolute = TRUE) {
  880. // Create cloned objects or original dates will be impacted by the
  881. // date_modify() operations done in this code.
  882. $date1 = clone($this);
  883. $date2 = clone($date2_in);
  884. if (is_object($date1) && is_object($date2)) {
  885. $diff = date_format($date2, 'U') - date_format($date1, 'U');
  886. if ($diff == 0) {
  887. return 0;
  888. }
  889. elseif ($diff < 0 && $absolute) {
  890. // Make sure $date1 is the smaller date.
  891. $temp = $date2;
  892. $date2 = $date1;
  893. $date1 = $temp;
  894. $diff = date_format($date2, 'U') - date_format($date1, 'U');
  895. }
  896. $year_diff = intval(date_format($date2, 'Y') - date_format($date1, 'Y'));
  897. switch ($measure) {
  898. // The easy cases first.
  899. case 'seconds':
  900. return $diff;
  901. case 'minutes':
  902. return $diff / 60;
  903. case 'hours':
  904. return $diff / 3600;
  905. case 'years':
  906. return $year_diff;
  907. case 'months':
  908. $format = 'n';
  909. $item1 = date_format($date1, $format);
  910. $item2 = date_format($date2, $format);
  911. if ($year_diff == 0) {
  912. return intval($item2 - $item1);
  913. }
  914. elseif ($year_diff < 0) {
  915. $item_diff = 0 - $item1;
  916. $item_diff -= intval((abs($year_diff) - 1) * 12);
  917. return $item_diff - (12 - $item2);
  918. }
  919. else {
  920. $item_diff = 12 - $item1;
  921. $item_diff += intval(($year_diff - 1) * 12);
  922. return $item_diff + $item2;
  923. }
  924. break;
  925. case 'days':
  926. $format = 'z';
  927. $item1 = date_format($date1, $format);
  928. $item2 = date_format($date2, $format);
  929. if ($year_diff == 0) {
  930. return intval($item2 - $item1);
  931. }
  932. elseif ($year_diff < 0) {
  933. $item_diff = 0 - $item1;
  934. for ($i = 1; $i < abs($year_diff); $i++) {
  935. date_modify($date1, '-1 year');
  936. $item_diff -= date_days_in_year($date1);
  937. }
  938. return $item_diff - (date_days_in_year($date2) - $item2);
  939. }
  940. else {
  941. $item_diff = date_days_in_year($date1) - $item1;
  942. for ($i = 1; $i < $year_diff; $i++) {
  943. date_modify($date1, '+1 year');
  944. $item_diff += date_days_in_year($date1);
  945. }
  946. return $item_diff + $item2;
  947. }
  948. break;
  949. case 'weeks':
  950. $week_diff = date_format($date2, 'W') - date_format($date1, 'W');
  951. $year_diff = date_format($date2, 'o') - date_format($date1, 'o');
  952. $sign = ($year_diff < 0) ? -1 : 1;
  953. for ($i = 1; $i <= abs($year_diff); $i++) {
  954. date_modify($date1, (($sign > 0) ? '+': '-').'1 year');
  955. $week_diff += (date_iso_weeks_in_year($date1) * $sign);
  956. }
  957. return $week_diff;
  958. }
  959. }
  960. return NULL;
  961. }
  962. }
  963. /**
  964. * Determines if the date element needs to be processed.
  965. *
  966. * Helper function to see if date element has been hidden by FAPI to see if it
  967. * needs to be processed or just pass the value through. This is needed since
  968. * normal date processing explands the date element into parts and then
  969. * reconstructs it, which is not needed or desirable if the field is hidden.
  970. *
  971. * @param array $element
  972. * The date element to check.
  973. *
  974. * @return bool
  975. * TRUE if the element is effectively hidden, FALSE otherwise.
  976. */
  977. function date_hidden_element($element) {
  978. // @TODO What else needs to be tested to see if dates are hidden or disabled?
  979. if ((isset($element['#access']) && empty($element['#access']))
  980. || !empty($element['#programmed'])
  981. || in_array($element['#type'], array('hidden', 'value'))) {
  982. return TRUE;
  983. }
  984. return FALSE;
  985. }
  986. /**
  987. * Helper function for getting the format string for a date type.
  988. *
  989. * @param string $type
  990. * A date type format name.
  991. *
  992. * @return string
  993. * A date type format, like 'Y-m-d H:i:s'.
  994. */
  995. function date_type_format($type) {
  996. switch ($type) {
  997. case DATE_ISO:
  998. return DATE_FORMAT_ISO;
  999. case DATE_UNIX:
  1000. return DATE_FORMAT_UNIX;
  1001. case DATE_DATETIME:
  1002. return DATE_FORMAT_DATETIME;
  1003. case DATE_ICAL:
  1004. return DATE_FORMAT_ICAL;
  1005. }
  1006. }
  1007. /**
  1008. * Constructs an untranslated array of month names.
  1009. *
  1010. * Needed for CSS, translation functions, strtotime(), and other places
  1011. * that use the English versions of these words.
  1012. *
  1013. * @return array
  1014. * An array of month names.
  1015. */
  1016. function date_month_names_untranslated() {
  1017. static $month_names;
  1018. if (empty($month_names)) {
  1019. $month_names = array(
  1020. 1 => 'January',
  1021. 2 => 'February',
  1022. 3 => 'March',
  1023. 4 => 'April',
  1024. 5 => 'May',
  1025. 6 => 'June',
  1026. 7 => 'July',
  1027. 8 => 'August',
  1028. 9 => 'September',
  1029. 10 => 'October',
  1030. 11 => 'November',
  1031. 12 => 'December',
  1032. );
  1033. }
  1034. return $month_names;
  1035. }
  1036. /**
  1037. * Returns a translated array of month names.
  1038. *
  1039. * @param bool $required
  1040. * (optional) If FALSE, the returned array will include a blank value.
  1041. * Defaults to FALSE.
  1042. *
  1043. * @return array
  1044. * An array of month names.
  1045. */
  1046. function date_month_names($required = FALSE) {
  1047. $month_names = array();
  1048. foreach (date_month_names_untranslated() as $key => $month) {
  1049. $month_names[$key] = t($month, array(), array('context' => 'Long month name'));
  1050. }
  1051. $none = array('' => '');
  1052. return !$required ? $none + $month_names : $month_names;
  1053. }
  1054. /**
  1055. * Constructs a translated array of month name abbreviations
  1056. *
  1057. * @param bool $required
  1058. * (optional) If FALSE, the returned array will include a blank value.
  1059. * Defaults to FALSE.
  1060. * @param int $length
  1061. * (optional) The length of the abbreviation. Defaults to 3.
  1062. *
  1063. * @return array
  1064. * An array of month abbreviations.
  1065. */
  1066. function date_month_names_abbr($required = FALSE, $length = 3) {
  1067. $month_names = array();
  1068. foreach (date_month_names_untranslated() as $key => $month) {
  1069. if ($length == 3) {
  1070. $month_names[$key] = t(substr($month, 0, $length), array());
  1071. }
  1072. else {
  1073. $month_names[$key] = t(substr($month, 0, $length), array(), array('context' => 'month_abbr'));
  1074. }
  1075. }
  1076. $none = array('' => '');
  1077. return !$required ? $none + $month_names : $month_names;
  1078. }
  1079. /**
  1080. * Constructs an untranslated array of week days.
  1081. *
  1082. * Needed for CSS, translation functions, strtotime(), and other places
  1083. * that use the English versions of these words.
  1084. *
  1085. * @param bool $refresh
  1086. * (optional) Whether to refresh the list. Defaults to TRUE.
  1087. *
  1088. * @return array
  1089. * An array of week day names
  1090. */
  1091. function date_week_days_untranslated($refresh = TRUE) {
  1092. static $weekdays;
  1093. if ($refresh || empty($weekdays)) {
  1094. $weekdays = array(
  1095. 'Sunday',
  1096. 'Monday',
  1097. 'Tuesday',
  1098. 'Wednesday',
  1099. 'Thursday',
  1100. 'Friday',
  1101. 'Saturday',
  1102. );
  1103. }
  1104. return $weekdays;
  1105. }
  1106. /**
  1107. * Returns a translated array of week names.
  1108. *
  1109. * @param bool $required
  1110. * (optional) If FALSE, the returned array will include a blank value.
  1111. * Defaults to FALSE.
  1112. *
  1113. * @return array
  1114. * An array of week day names
  1115. */
  1116. function date_week_days($required = FALSE, $refresh = TRUE) {
  1117. $weekdays = array();
  1118. foreach (date_week_days_untranslated() as $key => $day) {
  1119. $weekdays[$key] = t($day, array(), array('context' => ''));
  1120. }
  1121. $none = array('' => '');
  1122. return !$required ? $none + $weekdays : $weekdays;
  1123. }
  1124. /**
  1125. * Constructs a translated array of week day abbreviations.
  1126. *
  1127. * @param bool $required
  1128. * (optional) If FALSE, the returned array will include a blank value.
  1129. * Defaults to FALSE.
  1130. * @param bool $refresh
  1131. * (optional) Whether to refresh the list. Defaults to TRUE.
  1132. * @param int $length
  1133. * (optional) The length of the abbreviation. Defaults to 3.
  1134. *
  1135. * @return array
  1136. * An array of week day abbreviations
  1137. */
  1138. function date_week_days_abbr($required = FALSE, $refresh = TRUE, $length = 3) {
  1139. $weekdays = array();
  1140. switch ($length) {
  1141. case 1:
  1142. $context = 'day_abbr1';
  1143. break;
  1144. case 2:
  1145. $context = 'day_abbr2';
  1146. break;
  1147. default:
  1148. $context = '';
  1149. break;
  1150. }
  1151. foreach (date_week_days_untranslated() as $key => $day) {
  1152. $weekdays[$key] = t(substr($day, 0, $length), array(), array('context' => $context));
  1153. }
  1154. $none = array('' => '');
  1155. return !$required ? $none + $weekdays : $weekdays;
  1156. }
  1157. /**
  1158. * Reorders weekdays to match the first day of the week.
  1159. *
  1160. * @param array $weekdays
  1161. * An array of weekdays.
  1162. *
  1163. * @return array
  1164. * An array of weekdays reordered to match the first day of the week.
  1165. */
  1166. function date_week_days_ordered($weekdays) {
  1167. $first_day = variable_get('date_first_day', 0);
  1168. if ($first_day > 0) {
  1169. for ($i = 1; $i <= $first_day; $i++) {
  1170. $last = array_shift($weekdays);
  1171. array_push($weekdays, $last);
  1172. }
  1173. }
  1174. return $weekdays;
  1175. }
  1176. /**
  1177. * Constructs an array of years.
  1178. *
  1179. * @param int $min
  1180. * The minimum year in the array.
  1181. * @param int $max
  1182. * The maximum year in the array.
  1183. * @param bool $required
  1184. * (optional) If FALSE, the returned array will include a blank value.
  1185. * Defaults to FALSE.
  1186. *
  1187. * @return array
  1188. * An array of years in the selected range.
  1189. */
  1190. function date_years($min = 0, $max = 0, $required = FALSE) {
  1191. // Ensure $min and $max are valid values.
  1192. if (empty($min)) {
  1193. $min = intval(date('Y', REQUEST_TIME) - 3);
  1194. }
  1195. if (empty($max)) {
  1196. $max = intval(date('Y', REQUEST_TIME) + 3);
  1197. }
  1198. $none = array(0 => '');
  1199. return !$required ? $none + drupal_map_assoc(range($min, $max)) : drupal_map_assoc(range($min, $max));
  1200. }
  1201. /**
  1202. * Constructs an array of days in a month.
  1203. *
  1204. * @param bool $required
  1205. * (optional) If FALSE, the returned array will include a blank value.
  1206. * Defaults to FALSE.
  1207. * @param int $month
  1208. * (optional) The month in which to find the number of days.
  1209. * @param int $year
  1210. * (optional) The year in which to find the number of days.
  1211. *
  1212. * @return array
  1213. * An array of days for the selected month.
  1214. */
  1215. function date_days($required = FALSE, $month = NULL, $year = NULL) {
  1216. // If we have a month and year, find the right last day of the month.
  1217. if (!empty($month) && !empty($year)) {
  1218. $date = new DateObject($year . '-' . $month . '-01 00:00:00', 'UTC');
  1219. $max = $date->format('t');
  1220. }
  1221. // If there is no month and year given, default to 31.
  1222. if (empty($max)) {
  1223. $max = 31;
  1224. }
  1225. $none = array(0 => '');
  1226. return !$required ? $none + drupal_map_assoc(range(1, $max)) : drupal_map_assoc(range(1, $max));
  1227. }
  1228. /**
  1229. * Constructs an array of hours.
  1230. *
  1231. * @param string $format
  1232. * A date format string.
  1233. * @param bool $required
  1234. * (optional) If FALSE, the returned array will include a blank value.
  1235. * Defaults to FALSE.
  1236. *
  1237. * @return array
  1238. * An array of hours in the selected format.
  1239. */
  1240. function date_hours($format = 'H', $required = FALSE) {
  1241. $hours = array();
  1242. if ($format == 'h' || $format == 'g') {
  1243. $min = 1;
  1244. $max = 12;
  1245. }
  1246. else {
  1247. $min = 0;
  1248. $max = 23;
  1249. }
  1250. for ($i = $min; $i <= $max; $i++) {
  1251. $hours[$i] = $i < 10 && ($format == 'H' || $format == 'h') ? "0$i" : $i;
  1252. }
  1253. $none = array('' => '');
  1254. return !$required ? $none + $hours : $hours;
  1255. }
  1256. /**
  1257. * Constructs an array of minutes.
  1258. *
  1259. * @param string $format
  1260. * A date format string.
  1261. * @param bool $required
  1262. * (optional) If FALSE, the returned array will include a blank value.
  1263. * Defaults to FALSE.
  1264. *
  1265. * @return array
  1266. * An array of minutes in the selected format.
  1267. */
  1268. function date_minutes($format = 'i', $required = FALSE, $increment = 1) {
  1269. $minutes = array();
  1270. // Ensure $increment has a value so we don't loop endlessly.
  1271. if (empty($increment)) {
  1272. $increment = 1;
  1273. }
  1274. for ($i = 0; $i < 60; $i += $increment) {
  1275. $minutes[$i] = $i < 10 && $format == 'i' ? "0$i" : $i;
  1276. }
  1277. $none = array('' => '');
  1278. return !$required ? $none + $minutes : $minutes;
  1279. }
  1280. /**
  1281. * Constructs an array of seconds.
  1282. *
  1283. * @param string $format
  1284. * A date format string.
  1285. * @param bool $required
  1286. * (optional) If FALSE, the returned array will include a blank value.
  1287. * Defaults to FALSE.
  1288. *
  1289. * @return array
  1290. * An array of seconds in the selected format.
  1291. */
  1292. function date_seconds($format = 's', $required = FALSE, $increment = 1) {
  1293. $seconds = array();
  1294. // Ensure $increment has a value so we don't loop endlessly.
  1295. if (empty($increment)) {
  1296. $increment = 1;
  1297. }
  1298. for ($i = 0; $i < 60; $i += $increment) {
  1299. $seconds[$i] = $i < 10 && $format == 's' ? "0$i" : $i;
  1300. }
  1301. $none = array('' => '');
  1302. return !$required ? $none + $seconds : $seconds;
  1303. }
  1304. /**
  1305. * Constructs an array of AM and PM options.
  1306. *
  1307. * @param bool $required
  1308. * (optional) If FALSE, the returned array will include a blank value.
  1309. * Defaults to FALSE.
  1310. *
  1311. * @return array
  1312. * An array of AM and PM options.
  1313. */
  1314. function date_ampm($required = FALSE) {
  1315. $none = array('' => '');
  1316. $ampm = array(
  1317. 'am' => t('am', array(), array('context' => 'ampm')),
  1318. 'pm' => t('pm', array(), array('context' => 'ampm')),
  1319. );
  1320. return !$required ? $none + $ampm : $ampm;
  1321. }
  1322. /**
  1323. * Constructs an array of regex replacement strings for date format elements.
  1324. *
  1325. * @param bool $strict
  1326. * Whether or not to force 2 digits for elements that sometimes allow either
  1327. * 1 or 2 digits.
  1328. *
  1329. * @return array
  1330. * An array of date() format letters and their regex equivalents.
  1331. */
  1332. function date_format_patterns($strict = FALSE) {
  1333. return array(
  1334. 'd' => '\d{' . ($strict ? '2' : '1,2') . '}',
  1335. 'm' => '\d{' . ($strict ? '2' : '1,2') . '}',
  1336. 'h' => '\d{' . ($strict ? '2' : '1,2') . '}',
  1337. 'H' => '\d{' . ($strict ? '2' : '1,2') . '}',
  1338. 'i' => '\d{' . ($strict ? '2' : '1,2') . '}',
  1339. 's' => '\d{' . ($strict ? '2' : '1,2') . '}',
  1340. 'j' => '\d{1,2}',
  1341. 'N' => '\d',
  1342. 'S' => '\w{2}',
  1343. 'w' => '\d',
  1344. 'z' => '\d{1,3}',
  1345. 'W' => '\d{1,2}',
  1346. 'n' => '\d{1,2}',
  1347. 't' => '\d{2}',
  1348. 'L' => '\d',
  1349. 'o' => '\d{4}',
  1350. 'Y' => '-?\d{1,6}',
  1351. 'y' => '\d{2}',
  1352. 'B' => '\d{3}',
  1353. 'g' => '\d{1,2}',
  1354. 'G' => '\d{1,2}',
  1355. 'e' => '\w*',
  1356. 'I' => '\d',
  1357. 'T' => '\w*',
  1358. 'U' => '\d*',
  1359. 'z' => '[+-]?\d*',
  1360. 'O' => '[+-]?\d{4}',
  1361. // Using S instead of w and 3 as well as 4 to pick up non-ASCII chars like
  1362. // German umlaut. Per http://drupal.org/node/1101284, we may need as little
  1363. // as 2 and as many as 5 characters in some languages.
  1364. 'D' => '\S{2,5}',
  1365. 'l' => '\S*',
  1366. 'M' => '\S{2,5}',
  1367. 'F' => '\S*',
  1368. 'P' => '[+-]?\d{2}\:\d{2}',
  1369. 'O' => '[+-]\d{4}',
  1370. 'c' => '(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})([+-]?\d{2}\:\d{2})',
  1371. 'r' => '(\w{3}), (\d{2})\s(\w{3})\s(\d{2,4})\s(\d{2}):(\d{2}):(\d{2})([+-]?\d{4})?',
  1372. );
  1373. }
  1374. /**
  1375. * Constructs an array of granularity options and their labels.
  1376. *
  1377. * @return array
  1378. * An array of translated date parts, keyed by their machine name.
  1379. */
  1380. function date_granularity_names() {
  1381. return array(
  1382. 'year' => t('Year', array(), array('context' => 'datetime')),
  1383. 'month' => t('Month', array(), array('context' => 'datetime')),
  1384. 'day' => t('Day', array(), array('context' => 'datetime')),
  1385. 'hour' => t('Hour', array(), array('context' => 'datetime')),
  1386. 'minute' => t('Minute', array(), array('context' => 'datetime')),
  1387. 'second' => t('Second', array(), array('context' => 'datetime')),
  1388. );
  1389. }
  1390. /**
  1391. * Sorts a granularity array.
  1392. *
  1393. * @param array $granularity
  1394. * An array of date parts.
  1395. */
  1396. function date_granularity_sorted($granularity) {
  1397. return array_intersect(array('year', 'month', 'day', 'hour', 'minute', 'second'), $granularity);
  1398. }
  1399. /**
  1400. * Constructs an array of granularity based on a given precision.
  1401. *
  1402. * @param string $precision
  1403. * A granularity item.
  1404. *
  1405. * @return array
  1406. * A granularity array containing the given precision and all those above it.
  1407. * For example, passing in 'month' will return array('year', 'month').
  1408. */
  1409. function date_granularity_array_from_precision($precision) {
  1410. $granularity_array = array('year', 'month', 'day', 'hour', 'minute', 'second');
  1411. switch ($precision) {
  1412. case 'year':
  1413. return array_slice($granularity_array, -6, 1);
  1414. case 'month':
  1415. return array_slice($granularity_array, -6, 2);
  1416. case 'day':
  1417. return array_slice($granularity_array, -6, 3);
  1418. case 'hour':
  1419. return array_slice($granularity_array, -6, 4);
  1420. case 'minute':
  1421. return array_slice($granularity_array, -6, 5);
  1422. default:
  1423. return $granularity_array;
  1424. }
  1425. }
  1426. /**
  1427. * Give a granularity array, return the highest precision.
  1428. *
  1429. * @param array $granularity_array
  1430. * An array of date parts.
  1431. *
  1432. * @return string
  1433. * The most precise element in a granularity array.
  1434. */
  1435. function date_granularity_precision($granularity_array) {
  1436. $input = date_granularity_sorted($granularity_array);
  1437. return array_pop($input);
  1438. }
  1439. /**
  1440. * Constructs a valid DATETIME format string for the granularity of an item.
  1441. *
  1442. * @todo This function is no longer used as of
  1443. * http://drupalcode.org/project/date.git/commit/07efbb5.
  1444. */
  1445. function date_granularity_format($granularity) {
  1446. if (is_array($granularity)) {
  1447. $granularity = date_granularity_precision($granularity);
  1448. }
  1449. $format = 'Y-m-d H:i:s';
  1450. switch ($granularity) {
  1451. case 'year':
  1452. return substr($format, 0, 1);
  1453. case 'month':
  1454. return substr($format, 0, 3);
  1455. case 'day':
  1456. return substr($format, 0, 5);
  1457. case 'hour';
  1458. return substr($format, 0, 7);
  1459. case 'minute':
  1460. return substr($format, 0, 9);
  1461. default:
  1462. return $format;
  1463. }
  1464. }
  1465. /**
  1466. * Returns a translated array of timezone names.
  1467. *
  1468. * Cache the untranslated array, make the translated array a static variable.
  1469. *
  1470. * @param bool $required
  1471. * (optional) If FALSE, the returned array will include a blank value.
  1472. * Defaults to FALSE.
  1473. * @param bool $refresh
  1474. * (optional) Whether to refresh the list. Defaults to TRUE.
  1475. *
  1476. * @return array
  1477. * An array of timezone names.
  1478. */
  1479. function date_timezone_names($required = FALSE, $refresh = FALSE) {
  1480. static $zonenames;
  1481. if (empty($zonenames) || $refresh) {
  1482. $cached = cache_get('date_timezone_identifiers_list');
  1483. $zonenames = !empty($cached) ? $cached->data : array();
  1484. if ($refresh || empty($cached) || empty($zonenames)) {
  1485. $data = timezone_identifiers_list();
  1486. asort($data);
  1487. foreach ($data as $delta => $zone) {
  1488. // Because many timezones exist in PHP only for backward compatibility
  1489. // reasons and should not be used, the list is filtered by a regular
  1490. // expression.
  1491. if (preg_match('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
  1492. $zonenames[$zone] = $zone;
  1493. }
  1494. }
  1495. if (!empty($zonenames)) {
  1496. cache_set('date_timezone_identifiers_list', $zonenames);
  1497. }
  1498. }
  1499. foreach ($zonenames as $zone) {
  1500. $zonenames[$zone] = t('!timezone', array('!timezone' => t($zone)));
  1501. }
  1502. }
  1503. $none = array('' => '');
  1504. return !$required ? $none + $zonenames : $zonenames;
  1505. }
  1506. /**
  1507. * Returns an array of system-allowed timezone abbreviations.
  1508. *
  1509. * Cache an array of just the abbreviation names because the whole
  1510. * timezone_abbreviations_list() is huge, so we don't want to retrieve it more
  1511. * than necessary.
  1512. *
  1513. * @param bool $refresh
  1514. * (optional) Whether to refresh the list. Defaults to TRUE.
  1515. *
  1516. * @return array
  1517. * An array of allowed timezone abbreviations.
  1518. */
  1519. function date_timezone_abbr($refresh = FALSE) {
  1520. $cached = cache_get('date_timezone_abbreviations');
  1521. $data = isset($cached->data) ? $cached->data : array();
  1522. if (empty($data) || $refresh) {
  1523. $data = array_keys(timezone_abbreviations_list());
  1524. cache_set('date_timezone_abbreviations', $data);
  1525. }
  1526. return $data;
  1527. }
  1528. /**
  1529. * Formats a date, using a date type or a custom date format string.
  1530. *
  1531. * Reworked from Drupal's format_date function to handle pre-1970 and
  1532. * post-2038 dates and accept a date object instead of a timestamp as input.
  1533. * Translates formatted date results, unlike PHP function date_format().
  1534. * Should only be used for display, not input, because it can't be parsed.
  1535. *
  1536. * @param object $date
  1537. * A date object.
  1538. * @param string $type
  1539. * (optional) The date format to use. Can be 'small', 'medium' or 'large' for
  1540. * the preconfigured date formats. If 'custom' is specified, then $format is
  1541. * required as well. Defaults to 'medium'.
  1542. * @param string $format
  1543. * (optional) A PHP date format string as required by date(). A backslash
  1544. * should be used before a character to avoid interpreting the character as
  1545. * part of a date format. Defaults to an empty string.
  1546. * @param string $langcode
  1547. * (optional) Language code to translate to. Defaults to NULL.
  1548. *
  1549. * @return string
  1550. * A translated date string in the requested format.
  1551. *
  1552. * @see format_date()
  1553. */
  1554. function date_format_date($date, $type = 'medium', $format = '', $langcode = NULL) {
  1555. if (empty($date)) {
  1556. return '';
  1557. }
  1558. if ($type != 'custom') {
  1559. $format = variable_get('date_format_' . $type);
  1560. }
  1561. if ($type != 'custom' && empty($format)) {
  1562. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1563. }
  1564. $format = date_limit_format($format, $date->granularity);
  1565. $max = strlen($format);
  1566. $datestring = '';
  1567. for ($i = 0; $i < $max; $i++) {
  1568. $c = $format[$i];
  1569. switch ($c) {
  1570. case 'l':
  1571. $datestring .= t($date->format('l'), array(), array('context' => '', 'langcode' => $langcode));
  1572. break;
  1573. case 'D':
  1574. $datestring .= t($date->format('D'), array(), array('context' => '', 'langcode' => $langcode));
  1575. break;
  1576. case 'F':
  1577. $datestring .= t($date->format('F'), array(), array('context' => 'Long month name', 'langcode' => $langcode));
  1578. break;
  1579. case 'M':
  1580. $datestring .= t($date->format('M'), array(), array('langcode' => $langcode));
  1581. break;
  1582. case 'A':
  1583. case 'a':
  1584. $datestring .= t($date->format($c), array(), array('context' => 'ampm', 'langcode' => $langcode));
  1585. break;
  1586. // The timezone name translations can use t().
  1587. case 'e':
  1588. case 'T':
  1589. $datestring .= t($date->format($c));
  1590. break;
  1591. // Remaining date parts need no translation.
  1592. case 'O':
  1593. $datestring .= sprintf('%s%02d%02d', (date_offset_get($date) < 0 ? '-' : '+'), abs(date_offset_get($date) / 3600), abs(date_offset_get($date) % 3600) / 60);
  1594. break;
  1595. case 'P':
  1596. $datestring .= sprintf('%s%02d:%02d', (date_offset_get($date) < 0 ? '-' : '+'), abs(date_offset_get($date) / 3600), abs(date_offset_get($date) % 3600) / 60);
  1597. break;
  1598. case 'Z':
  1599. $datestring .= date_offset_get($date);
  1600. break;
  1601. case '\\':
  1602. $datestring .= $format[++$i];
  1603. break;
  1604. case 'r':
  1605. $datestring .= date_format_date($date, 'custom', 'D, d M Y H:i:s O', $langcode);
  1606. break;
  1607. default:
  1608. if (strpos('BdcgGhHiIjLmnNosStTuUwWYyz', $c) !== FALSE) {
  1609. $datestring .= $date->format($c);
  1610. }
  1611. else {
  1612. $datestring .= $c;
  1613. }
  1614. }
  1615. }
  1616. return $datestring;
  1617. }
  1618. /**
  1619. * Formats a time interval with granularity, including past and future context.
  1620. *
  1621. * @param object $date
  1622. * The current date object.
  1623. * @param int $granularity
  1624. * (optional) Number of units to display in the string. Defaults to 2.
  1625. *
  1626. * @return string
  1627. * A translated string representation of the interval.
  1628. *
  1629. * @see format_interval()
  1630. */
  1631. function date_format_interval($date, $granularity = 2, $display_ago = TRUE) {
  1632. // If no date is sent, then return nothing.
  1633. if (empty($date)) {
  1634. return NULL;
  1635. }
  1636. $interval = REQUEST_TIME - $date->format('U');
  1637. if ($interval > 0) {
  1638. return $display_ago ? t('!time ago', array('!time' => format_interval($interval, $granularity))) :
  1639. t('!time', array('!time' => format_interval($interval, $granularity)));
  1640. }
  1641. else {
  1642. return format_interval(abs($interval), $granularity);
  1643. }
  1644. }
  1645. /**
  1646. * A date object for the current time.
  1647. *
  1648. * @param object $timezone
  1649. * (optional) Optionally force time to a specific timezone, defaults to user
  1650. * timezone, if set, otherwise site timezone. Defaults to NULL.
  1651. *
  1652. * @param boolean $reset [optional]
  1653. * Static cache reset
  1654. *
  1655. * @return object
  1656. * The current time as a date object.
  1657. */
  1658. function date_now($timezone = NULL, $reset = FALSE) {
  1659. if ($reset) {
  1660. drupal_static_reset(__FUNCTION__ . $timezone);
  1661. }
  1662. $now = &drupal_static(__FUNCTION__ . $timezone);
  1663. if (!isset($now)) {
  1664. $now = new DateObject('now', $timezone);
  1665. }
  1666. // Avoid unexpected manipulation of cached $now object
  1667. // by subsequent code execution
  1668. // @see https://drupal.org/node/2261395
  1669. $clone = clone $now;
  1670. return $clone;
  1671. }
  1672. /**
  1673. * Determines if a timezone string is valid.
  1674. *
  1675. * @param string $timezone
  1676. * A potentially invalid timezone string.
  1677. *
  1678. * @return bool
  1679. * TRUE if the timezone is valid, FALSE otherwise.
  1680. */
  1681. function date_timezone_is_valid($timezone) {
  1682. static $timezone_names;
  1683. if (empty($timezone_names)) {
  1684. $timezone_names = array_keys(date_timezone_names(TRUE));
  1685. }
  1686. return in_array($timezone, $timezone_names);
  1687. }
  1688. /**
  1689. * Returns a timezone name to use as a default.
  1690. *
  1691. * @param bool $check_user
  1692. * (optional) Whether or not to check for a user-configured timezone.
  1693. * Defaults to TRUE.
  1694. *
  1695. * @return string
  1696. * The default timezone for a user, if available, otherwise the site.
  1697. */
  1698. function date_default_timezone($check_user = TRUE) {
  1699. global $user;
  1700. if ($check_user && variable_get('configurable_timezones', 1) && !empty($user->timezone)) {
  1701. return $user->timezone;
  1702. }
  1703. else {
  1704. $default = variable_get('date_default_timezone', '');
  1705. return empty($default) ? 'UTC' : $default;
  1706. }
  1707. }
  1708. /**
  1709. * Returns a timezone object for the default timezone.
  1710. *
  1711. * @param bool $check_user
  1712. * (optional) Whether or not to check for a user-configured timezone.
  1713. * Defaults to TRUE.
  1714. *
  1715. * @return object
  1716. * The default timezone for a user, if available, otherwise the site.
  1717. */
  1718. function date_default_timezone_object($check_user = TRUE) {
  1719. return timezone_open(date_default_timezone($check_user));
  1720. }
  1721. /**
  1722. * Identifies the number of days in a month for a date.
  1723. */
  1724. function date_days_in_month($year, $month) {
  1725. // Pick a day in the middle of the month to avoid timezone shifts.
  1726. $datetime = date_pad($year, 4) . '-' . date_pad($month) . '-15 00:00:00';
  1727. $date = new DateObject($datetime);
  1728. return $date->format('t');
  1729. }
  1730. /**
  1731. * Identifies the number of days in a year for a date.
  1732. *
  1733. * @param mixed $date
  1734. * (optional) The current date object, or a date string. Defaults to NULL.
  1735. *
  1736. * @return integer
  1737. * The number of days in the year.
  1738. */
  1739. function date_days_in_year($date = NULL) {
  1740. if (empty($date)) {
  1741. $date = date_now();
  1742. }
  1743. elseif (!is_object($date)) {
  1744. $date = new DateObject($date);
  1745. }
  1746. if (is_object($date)) {
  1747. if ($date->format('L')) {
  1748. return 366;
  1749. }
  1750. else {
  1751. return 365;
  1752. }
  1753. }
  1754. return NULL;
  1755. }
  1756. /**
  1757. * Identifies the number of ISO weeks in a year for a date.
  1758. *
  1759. * December 28 is always in the last ISO week of the year.
  1760. *
  1761. * @param mixed $date
  1762. * (optional) The current date object, or a date string. Defaults to NULL.
  1763. *
  1764. * @return integer
  1765. * The number of ISO weeks in a year.
  1766. */
  1767. function date_iso_weeks_in_year($date = NULL) {
  1768. if (empty($date)) {
  1769. $date = date_now();
  1770. }
  1771. elseif (!is_object($date)) {
  1772. $date = new DateObject($date);
  1773. }
  1774. if (is_object($date)) {
  1775. date_date_set($date, $date->format('Y'), 12, 28);
  1776. return $date->format('W');
  1777. }
  1778. return NULL;
  1779. }
  1780. /**
  1781. * Returns day of week for a given date (0 = Sunday).
  1782. *
  1783. * @param mixed $date
  1784. * (optional) A date, default is current local day. Defaults to NULL.
  1785. *
  1786. * @return int
  1787. * The number of the day in the week.
  1788. */
  1789. function date_day_of_week($date = NULL) {
  1790. if (empty($date)) {
  1791. $date = date_now();
  1792. }
  1793. elseif (!is_object($date)) {
  1794. $date = new DateObject($date);
  1795. }
  1796. if (is_object($date)) {
  1797. return $date->format('w');
  1798. }
  1799. return NULL;
  1800. }
  1801. /**
  1802. * Returns translated name of the day of week for a given date.
  1803. *
  1804. * @param mixed $date
  1805. * (optional) A date, default is current local day. Defaults to NULL.
  1806. * @param string $abbr
  1807. * (optional) Whether to return the abbreviated name for that day.
  1808. * Defaults to TRUE.
  1809. *
  1810. * @return string
  1811. * The name of the day in the week for that date.
  1812. */
  1813. function date_day_of_week_name($date = NULL, $abbr = TRUE) {
  1814. if (!is_object($date)) {
  1815. $date = new DateObject($date);
  1816. }
  1817. $dow = date_day_of_week($date);
  1818. $days = $abbr ? date_week_days_abbr() : date_week_days();
  1819. return $days[$dow];
  1820. }
  1821. /**
  1822. * Calculates the start and end dates for a calendar week.
  1823. *
  1824. * The dates are adjusted to use the chosen first day of week for this site.
  1825. *
  1826. * @param int $week
  1827. * The week value.
  1828. * @param int $year
  1829. * The year value.
  1830. *
  1831. * @return array
  1832. * A numeric array containing the start and end dates of a week.
  1833. */
  1834. function date_week_range($week, $year) {
  1835. if (variable_get('date_api_use_iso8601', FALSE)) {
  1836. return date_iso_week_range($week, $year);
  1837. }
  1838. $min_date = new DateObject($year . '-01-01 00:00:00');
  1839. $min_date->setTimezone(date_default_timezone_object());
  1840. // Move to the right week.
  1841. date_modify($min_date, '+' . strval(7 * ($week - 1)) . ' days');
  1842. // Move backwards to the first day of the week.
  1843. $first_day = variable_get('date_first_day', 0);
  1844. $day_wday = date_format($min_date, 'w');
  1845. date_modify($min_date, '-' . strval((7 + $day_wday - $first_day) % 7) . ' days');
  1846. // Move forwards to the last day of the week.
  1847. $max_date = clone($min_date);
  1848. date_modify($max_date, '+7 days');
  1849. if (date_format($min_date, 'Y') != $year) {
  1850. $min_date = new DateObject($year . '-01-01 00:00:00');
  1851. }
  1852. return array($min_date, $max_date);
  1853. }
  1854. /**
  1855. * Calculates the start and end dates for an ISO week.
  1856. *
  1857. * @param int $week
  1858. * The week value.
  1859. * @param int $year
  1860. * The year value.
  1861. *
  1862. * @return array
  1863. * A numeric array containing the start and end dates of an ISO week.
  1864. */
  1865. function date_iso_week_range($week, $year) {
  1866. // Get to the last ISO week of the previous year.
  1867. $min_date = new DateObject(($year - 1) . '-12-28 00:00:00');
  1868. date_timezone_set($min_date, date_default_timezone_object());
  1869. // Find the first day of the first ISO week in the year.
  1870. date_modify($min_date, '+1 Monday');
  1871. // Jump ahead to the desired week for the beginning of the week range.
  1872. if ($week > 1) {
  1873. date_modify($min_date, '+ ' . ($week - 1) . ' weeks');
  1874. }
  1875. // Move forwards to the last day of the week.
  1876. $max_date = clone($min_date);
  1877. date_modify($max_date, '+7 days');
  1878. return array($min_date, $max_date);
  1879. }
  1880. /**
  1881. * The number of calendar weeks in a year.
  1882. *
  1883. * PHP week functions return the ISO week, not the calendar week.
  1884. *
  1885. * @param int $year
  1886. * A year value.
  1887. *
  1888. * @return int
  1889. * Number of calendar weeks in selected year.
  1890. */
  1891. function date_weeks_in_year($year) {
  1892. $date = new DateObject(($year + 1) . '-01-01 12:00:00', 'UTC');
  1893. date_modify($date, '-1 day');
  1894. return date_week($date->format('Y-m-d'));
  1895. }
  1896. /**
  1897. * The calendar week number for a date.
  1898. *
  1899. * PHP week functions return the ISO week, not the calendar week.
  1900. *
  1901. * @param string $date
  1902. * A date string in the format Y-m-d.
  1903. *
  1904. * @return int
  1905. * The calendar week number.
  1906. */
  1907. function date_week($date) {
  1908. $date = substr($date, 0, 10);
  1909. $parts = explode('-', $date);
  1910. $date = new DateObject($date . ' 12:00:00', 'UTC');
  1911. // If we are using ISO weeks, this is easy.
  1912. if (variable_get('date_api_use_iso8601', FALSE)) {
  1913. return intval($date->format('W'));
  1914. }
  1915. $year_date = new DateObject($parts[0] . '-01-01 12:00:00', 'UTC');
  1916. $week = intval($date->format('W'));
  1917. $year_week = intval(date_format($year_date, 'W'));
  1918. $date_year = intval($date->format('o'));
  1919. // Remove the leap week if it's present.
  1920. if ($date_year > intval($parts[0])) {
  1921. $last_date = clone($date);
  1922. date_modify($last_date, '-7 days');
  1923. $week = date_format($last_date, 'W') + 1;
  1924. }
  1925. elseif ($date_year < intval($parts[0])) {
  1926. $week = 0;
  1927. }
  1928. if ($year_week != 1) {
  1929. $week++;
  1930. }
  1931. // Convert to ISO-8601 day number, to match weeks calculated above.
  1932. $iso_first_day = 1 + (variable_get('date_first_day', 0) + 6) % 7;
  1933. // If it's before the starting day, it's the previous week.
  1934. if (intval($date->format('N')) < $iso_first_day) {
  1935. $week--;
  1936. }
  1937. // If the year starts before, it's an extra week at the beginning.
  1938. if (intval(date_format($year_date, 'N')) < $iso_first_day) {
  1939. $week++;
  1940. }
  1941. return $week;
  1942. }
  1943. /**
  1944. * Helper function to left pad date parts with zeros.
  1945. *
  1946. * Provided because this is needed so often with dates.
  1947. *
  1948. * @param int $value
  1949. * The value to pad.
  1950. * @param int $size
  1951. * (optional) Total size expected, usually 2 or 4. Defaults to 2.
  1952. *
  1953. * @return string
  1954. * The padded value.
  1955. */
  1956. function date_pad($value, $size = 2) {
  1957. return sprintf("%0" . $size . "d", $value);
  1958. }
  1959. /**
  1960. * Determines if the granularity contains a time portion.
  1961. *
  1962. * @param array $granularity
  1963. * An array of allowed date parts, all others will be removed.
  1964. *
  1965. * @return bool
  1966. * TRUE if the granularity contains a time portion, FALSE otherwise.
  1967. */
  1968. function date_has_time($granularity) {
  1969. if (!is_array($granularity)) {
  1970. $granularity = array();
  1971. }
  1972. return (bool) count(array_intersect($granularity, array('hour', 'minute', 'second')));
  1973. }
  1974. /**
  1975. * Determines if the granularity contains a date portion.
  1976. *
  1977. * @param array $granularity
  1978. * An array of allowed date parts, all others will be removed.
  1979. *
  1980. * @return bool
  1981. * TRUE if the granularity contains a date portion, FALSE otherwise.
  1982. */
  1983. function date_has_date($granularity) {
  1984. if (!is_array($granularity)) {
  1985. $granularity = array();
  1986. }
  1987. return (bool) count(array_intersect($granularity, array('year', 'month', 'day')));
  1988. }
  1989. /**
  1990. * Helper function to get a format for a specific part of a date field.
  1991. *
  1992. * @param string $part
  1993. * The date field part, either 'time' or 'date'.
  1994. * @param string $format
  1995. * A date format string.
  1996. *
  1997. * @return string
  1998. * The date format for the given part.
  1999. */
  2000. function date_part_format($part, $format) {
  2001. switch ($part) {
  2002. case 'date':
  2003. return date_limit_format($format, array('year', 'month', 'day'));
  2004. case 'time':
  2005. return date_limit_format($format, array('hour', 'minute', 'second'));
  2006. default:
  2007. return date_limit_format($format, array($part));
  2008. }
  2009. }
  2010. /**
  2011. * Limits a date format to include only elements from a given granularity array.
  2012. *
  2013. * Example:
  2014. * date_limit_format('F j, Y - H:i', array('year', 'month', 'day'));
  2015. * returns 'F j, Y'
  2016. *
  2017. * @param string $format
  2018. * A date format string.
  2019. * @param array $granularity
  2020. * An array of allowed date parts, all others will be removed.
  2021. *
  2022. * @return string
  2023. * The format string with all other elements removed.
  2024. */
  2025. function date_limit_format($format, $granularity) {
  2026. // Use the advanced drupal_static() pattern to improve performance.
  2027. static $drupal_static_fast;
  2028. if (!isset($drupal_static_fast)) {
  2029. $drupal_static_fast['formats'] = &drupal_static(__FUNCTION__);
  2030. }
  2031. $formats = &$drupal_static_fast['formats'];
  2032. $format_granularity_cid = $format .'|'. implode(',', $granularity);
  2033. if (isset($formats[$format_granularity_cid])) {
  2034. return $formats[$format_granularity_cid];
  2035. }
  2036. // If punctuation has been escaped, remove the escaping. Done using strtr()
  2037. // because it is easier than getting the escape character extracted using
  2038. // preg_replace().
  2039. $replace = array(
  2040. '\-' => '-',
  2041. '\:' => ':',
  2042. "\'" => "'",
  2043. '\. ' => ' . ',
  2044. '\,' => ',',
  2045. );
  2046. $format = strtr($format, $replace);
  2047. // Get the 'T' out of ISO date formats that don't have both date and time.
  2048. if (!date_has_time($granularity) || !date_has_date($granularity)) {
  2049. $format = str_replace('\T', ' ', $format);
  2050. $format = str_replace('T', ' ', $format);
  2051. }
  2052. $regex = array();
  2053. if (!date_has_time($granularity)) {
  2054. $regex[] = '((?<!\\\\)[a|A])';
  2055. }
  2056. // Create regular expressions to remove selected values from string.
  2057. // Use (?<!\\\\) to keep escaped letters from being removed.
  2058. foreach (date_nongranularity($granularity) as $element) {
  2059. switch ($element) {
  2060. case 'year':
  2061. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[Yy])';
  2062. break;
  2063. case 'day':
  2064. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[l|D|d|dS|j|jS|N|w|W|z]{1,2})';
  2065. break;
  2066. case 'month':
  2067. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[FMmn])';
  2068. break;
  2069. case 'hour':
  2070. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[HhGg])';
  2071. break;
  2072. case 'minute':
  2073. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[i])';
  2074. break;
  2075. case 'second':
  2076. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[s])';
  2077. break;
  2078. case 'timezone':
  2079. $regex[] = '([\-/\.,:]?\s?(?<!\\\\)[TOZPe])';
  2080. break;
  2081. }
  2082. }
  2083. // Remove empty parentheses, brackets, pipes.
  2084. $regex[] = '(\(\))';
  2085. $regex[] = '(\[\])';
  2086. $regex[] = '(\|\|)';
  2087. // Remove selected values from string.
  2088. $format = trim(preg_replace($regex, array(), $format));
  2089. // Remove orphaned punctuation at the beginning of the string.
  2090. $format = preg_replace('`^([\-/\.,:\'])`', '', $format);
  2091. // Remove orphaned punctuation at the end of the string.
  2092. $format = preg_replace('([\-/,:\']$)', '', $format);
  2093. $format = preg_replace('(\\$)', '', $format);
  2094. // Trim any whitespace from the result.
  2095. $format = trim($format);
  2096. // After removing the non-desired parts of the format, test if the only things
  2097. // left are escaped, non-date, characters. If so, return nothing.
  2098. // Using S instead of w to pick up non-ASCII characters.
  2099. $test = trim(preg_replace('(\\\\\S{1,3})u', '', $format));
  2100. if (empty($test)) {
  2101. $format = '';
  2102. }
  2103. // Store the return value in the static array for performance.
  2104. $formats[$format_granularity_cid] = $format;
  2105. return $format;
  2106. }
  2107. /**
  2108. * Converts a format to an ordered array of granularity parts.
  2109. *
  2110. * Example:
  2111. * date_format_order('m/d/Y H:i')
  2112. * returns
  2113. * array(
  2114. * 0 => 'month',
  2115. * 1 => 'day',
  2116. * 2 => 'year',
  2117. * 3 => 'hour',
  2118. * 4 => 'minute',
  2119. * );
  2120. *
  2121. * @param string $format
  2122. * A date format string.
  2123. *
  2124. * @return array
  2125. * An array of ordered granularity elements from the given format string.
  2126. */
  2127. function date_format_order($format) {
  2128. $order = array();
  2129. if (empty($format)) {
  2130. return $order;
  2131. }
  2132. $max = strlen($format);
  2133. for ($i = 0; $i <= $max; $i++) {
  2134. if (!isset($format[$i])) {
  2135. break;
  2136. }
  2137. switch ($format[$i]) {
  2138. case 'd':
  2139. case 'j':
  2140. $order[] = 'day';
  2141. break;
  2142. case 'F':
  2143. case 'M':
  2144. case 'm':
  2145. case 'n':
  2146. $order[] = 'month';
  2147. break;
  2148. case 'Y':
  2149. case 'y':
  2150. $order[] = 'year';
  2151. break;
  2152. case 'g':
  2153. case 'G':
  2154. case 'h':
  2155. case 'H':
  2156. $order[] = 'hour';
  2157. break;
  2158. case 'i':
  2159. $order[] = 'minute';
  2160. break;
  2161. case 's':
  2162. $order[] = 'second';
  2163. break;
  2164. }
  2165. }
  2166. return $order;
  2167. }
  2168. /**
  2169. * Strips out unwanted granularity elements.
  2170. *
  2171. * @param array $granularity
  2172. * An array like ('year', 'month', 'day', 'hour', 'minute', 'second');
  2173. *
  2174. * @return array
  2175. * A reduced set of granularitiy elements.
  2176. */
  2177. function date_nongranularity($granularity) {
  2178. return array_diff(array('year', 'month', 'day', 'hour', 'minute', 'second', 'timezone'), (array) $granularity);
  2179. }
  2180. /**
  2181. * Implements hook_element_info().
  2182. */
  2183. function date_api_element_info() {
  2184. module_load_include('inc', 'date_api', 'date_api_elements');
  2185. return _date_api_element_info();
  2186. }
  2187. /**
  2188. * Implements hook_theme().
  2189. */
  2190. function date_api_theme($existing, $type, $theme, $path) {
  2191. $base = array(
  2192. 'file' => 'theme.inc',
  2193. 'path' => "$path/theme",
  2194. );
  2195. return array(
  2196. 'date_nav_title' => $base + array('variables' => array('granularity' => NULL, 'view' => NULL, 'link' => NULL, 'format' => NULL)),
  2197. 'date_timezone' => $base + array('render element' => 'element'),
  2198. 'date_select' => $base + array('render element' => 'element'),
  2199. 'date_text' => $base + array('render element' => 'element'),
  2200. 'date_select_element' => $base + array('render element' => 'element'),
  2201. 'date_textfield_element' => $base + array('render element' => 'element'),
  2202. 'date_part_hour_prefix' => $base + array('render element' => 'element'),
  2203. 'date_part_minsec_prefix' => $base + array('render element' => 'element'),
  2204. 'date_part_label_year' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2205. 'date_part_label_month' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2206. 'date_part_label_day' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2207. 'date_part_label_hour' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2208. 'date_part_label_minute' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2209. 'date_part_label_second' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2210. 'date_part_label_ampm' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2211. 'date_part_label_timezone' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2212. 'date_part_label_date' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2213. 'date_part_label_time' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
  2214. 'date_views_filter_form' => $base + array('template' => 'date-views-filter-form', 'render element' => 'form'),
  2215. 'date_calendar_day' => $base + array('variables' => array('date' => NULL)),
  2216. 'date_time_ago' => $base + array('variables' => array('start_date' => NULL, 'end_date' => NULL, 'interval' => NULL)),
  2217. );
  2218. }
  2219. /**
  2220. * Function to figure out which local timezone applies to a date and select it.
  2221. *
  2222. * @param string $handling
  2223. * The timezone handling.
  2224. * @param string $timezone
  2225. * (optional) A timezone string. Defaults to an empty string.
  2226. *
  2227. * @return string
  2228. * The timezone string.
  2229. */
  2230. function date_get_timezone($handling, $timezone = '') {
  2231. switch ($handling) {
  2232. case 'date':
  2233. $timezone = !empty($timezone) ? $timezone : date_default_timezone();
  2234. break;
  2235. case 'utc':
  2236. $timezone = 'UTC';
  2237. break;
  2238. default:
  2239. $timezone = date_default_timezone();
  2240. }
  2241. return $timezone > '' ? $timezone : date_default_timezone();
  2242. }
  2243. /**
  2244. * Function to figure out which db timezone applies to a date.
  2245. *
  2246. * @param string $handling
  2247. * The timezone handling.
  2248. * @param string $timezone
  2249. * (optional) When $handling is 'date', date_get_timezone_db() returns this
  2250. * value.
  2251. *
  2252. * @return string
  2253. * The timezone string.
  2254. */
  2255. function date_get_timezone_db($handling, $timezone = NULL) {
  2256. switch ($handling) {
  2257. case ('utc'):
  2258. case ('site'):
  2259. case ('user'):
  2260. // These handling modes all convert to UTC before storing in the DB.
  2261. $timezone = 'UTC';
  2262. break;
  2263. case ('date'):
  2264. if ($timezone == NULL) {
  2265. // This shouldn't happen, since it's meaning is undefined. But we need
  2266. // to fall back to *something* that's a legal timezone.
  2267. $timezone = date_default_timezone();
  2268. }
  2269. break;
  2270. case ('none'):
  2271. default:
  2272. $timezone = date_default_timezone();
  2273. break;
  2274. }
  2275. return $timezone;
  2276. }
  2277. /**
  2278. * Helper function for converting back and forth from '+1' to 'First'.
  2279. */
  2280. function date_order_translated() {
  2281. return array(
  2282. '+1' => t('First', array(), array('context' => 'date_order')),
  2283. '+2' => t('Second', array(), array('context' => 'date_order')),
  2284. '+3' => t('Third', array(), array('context' => 'date_order')),
  2285. '+4' => t('Fourth', array(), array('context' => 'date_order')),
  2286. '+5' => t('Fifth', array(), array('context' => 'date_order')),
  2287. '-1' => t('Last', array(), array('context' => 'date_order_reverse')),
  2288. '-2' => t('Next to last', array(), array('context' => 'date_order_reverse')),
  2289. '-3' => t('Third from last', array(), array('context' => 'date_order_reverse')),
  2290. '-4' => t('Fourth from last', array(), array('context' => 'date_order_reverse')),
  2291. '-5' => t('Fifth from last', array(), array('context' => 'date_order_reverse')),
  2292. );
  2293. }
  2294. /**
  2295. * Creates an array of ordered strings, using English text when possible.
  2296. */
  2297. function date_order() {
  2298. return array(
  2299. '+1' => 'First',
  2300. '+2' => 'Second',
  2301. '+3' => 'Third',
  2302. '+4' => 'Fourth',
  2303. '+5' => 'Fifth',
  2304. '-1' => 'Last',
  2305. '-2' => '-2',
  2306. '-3' => '-3',
  2307. '-4' => '-4',
  2308. '-5' => '-5',
  2309. );
  2310. }
  2311. /**
  2312. * Tests validity of a date range string.
  2313. *
  2314. * @param string $string
  2315. * A min and max year string like '-3:+1'a.
  2316. *
  2317. * @return bool
  2318. * TRUE if the date range is valid, FALSE otherwise.
  2319. */
  2320. function date_range_valid($string) {
  2321. $matches = preg_match('@^(\-[0-9]+|[0-9]{4}):([\+|\-][0-9]+|[0-9]{4})$@', $string);
  2322. return $matches < 1 ? FALSE : TRUE;
  2323. }
  2324. /**
  2325. * Splits a string like -3:+3 or 2001:2010 into an array of min and max years.
  2326. *
  2327. * Center the range around the current year, if any, but expand it far
  2328. * enough so it will pick up the year value in the field in case
  2329. * the value in the field is outside the initial range.
  2330. *
  2331. * @param string $string
  2332. * A min and max year string like '-3:+1'.
  2333. * @param object $date
  2334. * (optional) A date object. Defaults to NULL.
  2335. *
  2336. * @return array
  2337. * A numerically indexed array, containing a minimum and maximum year.
  2338. */
  2339. function date_range_years($string, $date = NULL) {
  2340. $this_year = date_format(date_now(), 'Y');
  2341. list($min_year, $max_year) = explode(':', $string);
  2342. // Valid patterns would be -5:+5, 0:+1, 2008:2010.
  2343. $plus_pattern = '@[\+|\-][0-9]{1,4}@';
  2344. $year_pattern = '@^[0-9]{4}@';
  2345. if (!preg_match($year_pattern, $min_year, $matches)) {
  2346. if (preg_match($plus_pattern, $min_year, $matches)) {
  2347. $min_year = $this_year + $matches[0];
  2348. }
  2349. else {
  2350. $min_year = $this_year;
  2351. }
  2352. }
  2353. if (!preg_match($year_pattern, $max_year, $matches)) {
  2354. if (preg_match($plus_pattern, $max_year, $matches)) {
  2355. $max_year = $this_year + $matches[0];
  2356. }
  2357. else {
  2358. $max_year = $this_year;
  2359. }
  2360. }
  2361. // We expect the $min year to be less than the $max year.
  2362. // Some custom values for -99:+99 might not obey that.
  2363. if ($min_year > $max_year) {
  2364. $temp = $max_year;
  2365. $max_year = $min_year;
  2366. $min_year = $temp;
  2367. }
  2368. // If there is a current value, stretch the range to include it.
  2369. $value_year = is_object($date) ? $date->format('Y') : '';
  2370. if (!empty($value_year)) {
  2371. $min_year = min($value_year, $min_year);
  2372. $max_year = max($value_year, $max_year);
  2373. }
  2374. return array($min_year, $max_year);
  2375. }
  2376. /**
  2377. * Converts a min and max year into a string like '-3:+1'.
  2378. *
  2379. * @param array $years
  2380. * A numerically indexed array, containing a minimum and maximum year.
  2381. *
  2382. * @return string
  2383. * A min and max year string like '-3:+1'.
  2384. */
  2385. function date_range_string($years) {
  2386. $this_year = date_format(date_now(), 'Y');
  2387. if ($years[0] < $this_year) {
  2388. $min = '-' . ($this_year - $years[0]);
  2389. }
  2390. else {
  2391. $min = '+' . ($years[0] - $this_year);
  2392. }
  2393. if ($years[1] < $this_year) {
  2394. $max = '-' . ($this_year - $years[1]);
  2395. }
  2396. else {
  2397. $max = '+' . ($years[1] - $this_year);
  2398. }
  2399. return $min . ':' . $max;
  2400. }
  2401. /**
  2402. * Temporary helper to re-create equivalent of content_database_info().
  2403. */
  2404. function date_api_database_info($field, $revision = FIELD_LOAD_CURRENT) {
  2405. return array(
  2406. 'columns' => $field['storage']['details']['sql'][$revision],
  2407. 'table' => _field_sql_storage_tablename($field),
  2408. );
  2409. }
  2410. /**
  2411. * Implements hook_form_FORM_ID_alter() for system_regional_settings().
  2412. *
  2413. * Add a form element to configure whether or not week numbers are ISO-8601, the
  2414. * default is FALSE (US/UK/AUS norm).
  2415. */
  2416. function date_api_form_system_regional_settings_alter(&$form, &$form_state, $form_id) {
  2417. $form['locale']['date_api_use_iso8601'] = array(
  2418. '#type' => 'checkbox',
  2419. '#title' => t('Use ISO-8601 week numbers'),
  2420. '#default_value' => variable_get('date_api_use_iso8601', FALSE),
  2421. '#description' => t('IMPORTANT! If checked, First day of week MUST be set to Monday'),
  2422. );
  2423. $form['#validate'][] = 'date_api_form_system_settings_validate';
  2424. }
  2425. /**
  2426. * Validate that the option to use ISO weeks matches first day of week choice.
  2427. */
  2428. function date_api_form_system_settings_validate(&$form, &$form_state) {
  2429. $form_values = $form_state['values'];
  2430. if ($form_values['date_api_use_iso8601'] && $form_values['date_first_day'] != 1) {
  2431. form_set_error('date_first_day', t('When using ISO-8601 week numbers, the first day of the week must be set to Monday.'));
  2432. }
  2433. }
  2434. /**
  2435. * Creates an array of date format types for use as an options list.
  2436. */
  2437. function date_format_type_options() {
  2438. $options = array();
  2439. $format_types = system_get_date_types();
  2440. if (!empty($format_types)) {
  2441. foreach ($format_types as $type => $type_info) {
  2442. $options[$type] = $type_info['title'] . ' (' . date_format_date(date_example_date(), $type) . ')';
  2443. }
  2444. }
  2445. return $options;
  2446. }
  2447. /**
  2448. * Creates an example date.
  2449. *
  2450. * This ensures a clear difference between month and day, and 12 and 24 hours.
  2451. */
  2452. function date_example_date() {
  2453. $now = date_now();
  2454. if (date_format($now, 'M') == date_format($now, 'F')) {
  2455. date_modify($now, '+1 month');
  2456. }
  2457. if (date_format($now, 'm') == date_format($now, 'd')) {
  2458. date_modify($now, '+1 day');
  2459. }
  2460. if (date_format($now, 'H') == date_format($now, 'h')) {
  2461. date_modify($now, '+12 hours');
  2462. }
  2463. return $now;
  2464. }
  2465. /**
  2466. * Determine if a start/end date combination qualify as 'All day'.
  2467. *
  2468. * @param string $string1
  2469. * A string date in datetime format for the 'start' date.
  2470. * @param string $string2
  2471. * A string date in datetime format for the 'end' date.
  2472. * @param string $granularity
  2473. * (optional) The granularity of the date. Defaults to 'second'.
  2474. * @param int $increment
  2475. * (optional) The increment of the date. Defaults to 1.
  2476. *
  2477. * @return bool
  2478. * TRUE if the date is all day, FALSE otherwise.
  2479. */
  2480. function date_is_all_day($string1, $string2, $granularity = 'second', $increment = 1) {
  2481. if (empty($string1) || empty($string2)) {
  2482. return FALSE;
  2483. }
  2484. elseif (!in_array($granularity, array('hour', 'minute', 'second'))) {
  2485. return FALSE;
  2486. }
  2487. preg_match('/([0-9]{4}-[0-9]{2}-[0-9]{2}) (([0-9]{2}):([0-9]{2}):([0-9]{2}))/', $string1, $matches);
  2488. $count = count($matches);
  2489. $date1 = $count > 1 ? $matches[1] : '';
  2490. $time1 = $count > 2 ? $matches[2] : '';
  2491. $hour1 = $count > 3 ? intval($matches[3]) : 0;
  2492. $min1 = $count > 4 ? intval($matches[4]) : 0;
  2493. $sec1 = $count > 5 ? intval($matches[5]) : 0;
  2494. preg_match('/([0-9]{4}-[0-9]{2}-[0-9]{2}) (([0-9]{2}):([0-9]{2}):([0-9]{2}))/', $string2, $matches);
  2495. $count = count($matches);
  2496. $date2 = $count > 1 ? $matches[1] : '';
  2497. $time2 = $count > 2 ? $matches[2] : '';
  2498. $hour2 = $count > 3 ? intval($matches[3]) : 0;
  2499. $min2 = $count > 4 ? intval($matches[4]) : 0;
  2500. $sec2 = $count > 5 ? intval($matches[5]) : 0;
  2501. if (empty($date1) || empty($date2)) {
  2502. return FALSE;
  2503. }
  2504. if (empty($time1) || empty($time2)) {
  2505. return FALSE;
  2506. }
  2507. $tmp = date_seconds('s', TRUE, $increment);
  2508. $max_seconds = intval(array_pop($tmp));
  2509. $tmp = date_minutes('i', TRUE, $increment);
  2510. $max_minutes = intval(array_pop($tmp));
  2511. // See if minutes and seconds are the maximum allowed for an increment or the
  2512. // maximum possible (59), or 0.
  2513. switch ($granularity) {
  2514. case 'second':
  2515. $min_match = $time1 == '00:00:00'
  2516. || ($hour1 == 0 && $min1 == 0 && $sec1 == 0);
  2517. $max_match = $time2 == '00:00:00'
  2518. || ($hour2 == 23 && in_array($min2, array($max_minutes, 59)) && in_array($sec2, array($max_seconds, 59)))
  2519. || ($hour1 == 0 && $hour2 == 0 && $min1 == 0 && $min2 == 0 && $sec1 == 0 && $sec2 == 0);
  2520. break;
  2521. case 'minute':
  2522. $min_match = $time1 == '00:00:00'
  2523. || ($hour1 == 0 && $min1 == 0);
  2524. $max_match = $time2 == '00:00:00'
  2525. || ($hour2 == 23 && in_array($min2, array($max_minutes, 59)))
  2526. || ($hour1 == 0 && $hour2 == 0 && $min1 == 0 && $min2 == 0);
  2527. break;
  2528. case 'hour':
  2529. $min_match = $time1 == '00:00:00'
  2530. || ($hour1 == 0);
  2531. $max_match = $time2 == '00:00:00'
  2532. || ($hour2 == 23)
  2533. || ($hour1 == 0 && $hour2 == 0);
  2534. break;
  2535. default:
  2536. $min_match = TRUE;
  2537. $max_match = FALSE;
  2538. }
  2539. if ($min_match && $max_match) {
  2540. return TRUE;
  2541. }
  2542. return FALSE;
  2543. }
  2544. /**
  2545. * Helper function to round minutes and seconds to requested value.
  2546. */
  2547. function date_increment_round(&$date, $increment) {
  2548. // Round minutes and seconds, if necessary.
  2549. if (is_object($date) && $increment > 1) {
  2550. $day = intval(date_format($date, 'j'));
  2551. $hour = intval(date_format($date, 'H'));
  2552. $second = intval(round(intval(date_format($date, 's')) / $increment) * $increment);
  2553. $minute = intval(date_format($date, 'i'));
  2554. if ($second == 60) {
  2555. $minute += 1;
  2556. $second = 0;
  2557. }
  2558. $minute = intval(round($minute / $increment) * $increment);
  2559. if ($minute == 60) {
  2560. $hour += 1;
  2561. $minute = 0;
  2562. }
  2563. date_time_set($date, $hour, $minute, $second);
  2564. if ($hour == 24) {
  2565. $day += 1;
  2566. $hour = 0;
  2567. $year = date_format($date, 'Y');
  2568. $month = date_format($date, 'n');
  2569. date_date_set($date, $year, $month, $day);
  2570. }
  2571. }
  2572. return $date;
  2573. }
  2574. /**
  2575. * Determines if a date object is valid.
  2576. *
  2577. * @param object $date
  2578. * The date object to check.
  2579. *
  2580. * @return bool
  2581. * TRUE if the date is a valid date object, FALSE otherwise.
  2582. */
  2583. function date_is_date($date) {
  2584. if (empty($date) || !is_object($date) || !empty($date->errors)) {
  2585. return FALSE;
  2586. }
  2587. return TRUE;
  2588. }
  2589. /**
  2590. * This function will replace ISO values that have the pattern 9999-00-00T00:00:00
  2591. * with a pattern like 9999-01-01T00:00:00, to match the behavior of non-ISO
  2592. * dates and ensure that date objects created from this value contain a valid month
  2593. * and day. Without this fix, the ISO date '2020-00-00T00:00:00' would be created as
  2594. * November 30, 2019 (the previous day in the previous month).
  2595. *
  2596. * @param string $iso_string
  2597. * An ISO string that needs to be made into a complete, valid date.
  2598. *
  2599. * @TODO Expand on this to work with all sorts of partial ISO dates.
  2600. */
  2601. function date_make_iso_valid($iso_string) {
  2602. // If this isn't a value that uses an ISO pattern, there is nothing to do.
  2603. if (is_numeric($iso_string) || !preg_match(DATE_REGEX_ISO, $iso_string)) {
  2604. return $iso_string;
  2605. }
  2606. // First see if month and day parts are '-00-00'.
  2607. if (substr($iso_string, 4, 6) == '-00-00') {
  2608. return preg_replace('/([\d]{4}-)(00-00)(T[\d]{2}:[\d]{2}:[\d]{2})/', '${1}01-01${3}', $iso_string);
  2609. }
  2610. // Then see if the day part is '-00'.
  2611. elseif (substr($iso_string, 7, 3) == '-00') {
  2612. return preg_replace('/([\d]{4}-[\d]{2}-)(00)(T[\d]{2}:[\d]{2}:[\d]{2})/', '${1}01${3}', $iso_string);
  2613. }
  2614. // Fall through, no changes required.
  2615. return $iso_string;
  2616. }