CronSchedule.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. <?php
  2. namespace Encore\Admin\Scheduling;
  3. /*
  4. * Plugin: StreamlineFoundation
  5. *
  6. * Class: Schedule
  7. *
  8. * Description: Provides scheduling mechanics including creating a schedule, testing if a specific moment is part of the schedule, moving back
  9. * and forth between scheduled moments in time and translating the created schedule back to a human readable form.
  10. *
  11. * Usage: ::fromCronString() creates a new Schedule class and requires a string in the cron ('* * * * *', $language) format.
  12. *
  13. * ->next(<datetime>) returns the first scheduled datetime after <datetime> in array format.
  14. * ->nextAsString(<datetime>) does the same with an ISO string as the result.
  15. * ->nextAsTime(<datetime>) does the same with a UNIX timestamp as the result.
  16. *
  17. * ->previous(<datetime>) returns the first scheduled datetime before <datetime> in array format.
  18. * ->previousAsString(<datetime>) does the same with an ISO string as the result.
  19. * ->previousAsTime(<datetime>) does the same with a UNIX timestamp as the result.
  20. *
  21. * ->asNaturalLanguage() returns the entire schedule in natural language form.
  22. *
  23. * In the next and previous functions, <datetime> can be a UNIX timestamp, an ISO string or an array format such as returned by
  24. * next() and previous().
  25. *
  26. * Copyright: 2012 Joost Brugman (joost@brugmanholding.com, joost@joostbrugman.com)
  27. *
  28. * This file is part of the Streamline plugin "StreamlineFoundation" and referenced in the next paragraphs inside this comment block as "this
  29. * plugin". It is based on the Streamline application framework.
  30. *
  31. * This plugin is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as
  32. * published by the Free Software Foundation, either version 3 of the License, or any later version. This plugin is distributed in the
  33. * hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  34. * PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public
  35. * License along with Streamline. If not, see <http://www.gnu.org/licenses/>.
  36. */
  37. class CronSchedule
  38. {
  39. // The actual minutes, hours, daysOfMonth, months, daysOfWeek and years selected by the provided cron specification.
  40. private $_minutes = [];
  41. private $_hours = [];
  42. private $_daysOfMonth = [];
  43. private $_months = [];
  44. private $_daysOfWeek = [];
  45. private $_years = [];
  46. // The original cron specification in compiled form.
  47. private $_cronMinutes = [];
  48. private $_cronHours = [];
  49. private $_cronDaysOfMonth = [];
  50. private $_cronMonths = [];
  51. private $_cronDaysOfWeek = [];
  52. private $_cronYears = [];
  53. // The language table
  54. private $_lang = false;
  55. /**
  56. * Minimum and maximum years to cope with the Year 2038 problem in UNIX. We run PHP which most likely runs on a UNIX environment so we
  57. * must assume vulnerability.
  58. */
  59. protected $RANGE_YEARS_MIN = 1970; // Must match date range supported by date(). See also: http://en.wikipedia.org/wiki/Year_2038_problem
  60. protected $RANGE_YEARS_MAX = 2037; // Must match date range supported by date(). See also: http://en.wikipedia.org/wiki/Year_2038_problem
  61. /**
  62. * Function: __construct.
  63. *
  64. * Description: Performs only base initialization, including language initialization.
  65. *
  66. * Parameters: $language The languagecode of the chosen language.
  67. */
  68. public function __construct($language = 'en')
  69. {
  70. $this->initLang($language);
  71. }
  72. //
  73. // Function: fromCronString
  74. //
  75. // Description: Creates a new Schedule object based on a Cron specification.
  76. //
  77. // Parameters: $cronSpec A string containing a cron specification.
  78. // $language The language to use to create a natural language representation of the string
  79. //
  80. // Result: A new Schedule object. An \Exception is thrown if the specification is invalid.
  81. //
  82. final public static function fromCronString($cronSpec = '* * * * * *', $language = 'en')
  83. {
  84. // Split input liberal. Single or multiple Spaces, Tabs and Newlines are all allowed as separators.
  85. if (count($elements = preg_split('/\s+/', $cronSpec)) < 5) {
  86. throw new Exception('Invalid specification.');
  87. }
  88. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  89. // Named ranges in cron entries
  90. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  91. $arrMonths = ['JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12];
  92. $arrDaysOfWeek = ['SUN' => 0, 'MON' => 1, 'TUE' => 2, 'WED' => 3, 'THU' => 4, 'FRI' => 5, 'SAT' => 6];
  93. // Translate the cron specification into arrays that hold specifications of the actual dates
  94. $newCron = new self($language);
  95. $newCron->_cronMinutes = $newCron->cronInterpret($elements[0], 0, 59, [], 'minutes');
  96. $newCron->_cronHours = $newCron->cronInterpret($elements[1], 0, 23, [], 'hours');
  97. $newCron->_cronDaysOfMonth = $newCron->cronInterpret($elements[2], 1, 31, [], 'daysOfMonth');
  98. $newCron->_cronMonths = $newCron->cronInterpret($elements[3], 1, 12, $arrMonths, 'months');
  99. $newCron->_cronDaysOfWeek = $newCron->cronInterpret($elements[4], 0, 6, $arrDaysOfWeek, 'daysOfWeek');
  100. $newCron->_minutes = $newCron->cronCreateItems($newCron->_cronMinutes);
  101. $newCron->_hours = $newCron->cronCreateItems($newCron->_cronHours);
  102. $newCron->_daysOfMonth = $newCron->cronCreateItems($newCron->_cronDaysOfMonth);
  103. $newCron->_months = $newCron->cronCreateItems($newCron->_cronMonths);
  104. $newCron->_daysOfWeek = $newCron->cronCreateItems($newCron->_cronDaysOfWeek);
  105. if (isset($elements[5])) {
  106. $newCron->_cronYears = $newCron->cronInterpret($elements[5], $newCron->RANGE_YEARS_MIN, $newCron->RANGE_YEARS_MAX, [], 'years');
  107. $newCron->_years = $newCron->cronCreateItems($newCron->_cronYears);
  108. }
  109. return $newCron;
  110. }
  111. /*
  112. * Function: cronInterpret
  113. *
  114. * Description: Interprets a single field from a cron specification. Throws an \Exception if the specification is in some way invalid.
  115. *
  116. * Parameters: $specification The actual text from the spefication, such as 12-38/3
  117. * $rangeMin The lowest value for specification.
  118. * $rangeMax The highest value for specification
  119. * $namesItems A key/value pair where value is a value between $rangeMin and $rangeMax and key is the name for that value.
  120. * $errorName The name of the category to use in case of an error.
  121. *
  122. * Result: An array with entries, each of which is an array with the following fields:
  123. * 'number1' The first number of the range or the number specified
  124. * 'number2' The second number of the range if a range is specified
  125. * 'hasInterval' TRUE if a range is specified. FALSE otherwise
  126. * 'interval' The interval if a range is specified.
  127. */
  128. final private function cronInterpret($specification, $rangeMin, $rangeMax, $namedItems, $errorName)
  129. {
  130. if ((!is_string($specification)) && (!(is_int($specification)))) {
  131. throw new Exception('Invalid specification.');
  132. }
  133. // Multiple values, separated by comma
  134. $specs = [];
  135. $specs['rangeMin'] = $rangeMin;
  136. $specs['rangeMax'] = $rangeMax;
  137. $specs['elements'] = [];
  138. $arrSegments = explode(',', $specification);
  139. foreach ($arrSegments as $segment) {
  140. $hasRange = (($posRange = strpos($segment, '-')) !== false);
  141. $hasInterval = (($posIncrement = strpos($segment, '/')) !== false);
  142. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  143. // Check: Increment without range is invalid
  144. //if(!$hasRange && $hasInterval) throw new \Exception("Invalid Range ($errorName).");
  145. // Check: Increment must be final specification
  146. if ($hasRange && $hasInterval) {
  147. if ($posIncrement < $posRange) {
  148. throw new \Exception("Invalid order ($errorName).");
  149. }
  150. }
  151. // GetSegments
  152. $segmentNumber1 = $segment;
  153. $segmentNumber2 = '';
  154. $segmentIncrement = '';
  155. $intIncrement = 1;
  156. if ($hasInterval) {
  157. $segmentNumber1 = substr($segment, 0, $posIncrement);
  158. $segmentIncrement = substr($segment, $posIncrement + 1);
  159. }
  160. if ($hasRange) {
  161. $segmentNumber2 = substr($segmentNumber1, $posRange + 1);
  162. $segmentNumber1 = substr($segmentNumber1, 0, $posRange);
  163. }
  164. // Get and validate first value in range
  165. if ($segmentNumber1 == '*') {
  166. $intNumber1 = $rangeMin;
  167. $intNumber2 = $rangeMax;
  168. $hasRange = true;
  169. } else {
  170. if (array_key_exists(strtoupper($segmentNumber1), $namedItems)) {
  171. $segmentNumber1 = $namedItems[strtoupper($segmentNumber1)];
  172. }
  173. if (((string) ($intNumber1 = (int) $segmentNumber1)) != $segmentNumber1) {
  174. throw new \Exception("Invalid symbol ($errorName).");
  175. }
  176. if (($intNumber1 < $rangeMin) || ($intNumber1 > $rangeMax)) {
  177. throw new \Exception("Out of bounds ($errorName).");
  178. }
  179. // Get and validate second value in range
  180. if ($hasRange) {
  181. if (array_key_exists(strtoupper($segmentNumber2), $namedItems)) {
  182. $segmentNumber2 = $namedItems[strtoupper($segmentNumber2)];
  183. }
  184. if (((string) ($intNumber2 = (int) $segmentNumber2)) != $segmentNumber2) {
  185. throw new \Exception("Invalid symbol ($errorName).");
  186. }
  187. if (($intNumber2 < $rangeMin) || ($intNumber2 > $rangeMax)) {
  188. throw new \Exception("Out of bounds ($errorName).");
  189. }
  190. if ($intNumber1 > $intNumber2) {
  191. throw new \Exception("Invalid range ($errorName).");
  192. }
  193. }
  194. }
  195. // Get and validate increment
  196. if ($hasInterval) {
  197. if (($intIncrement = (int) $segmentIncrement) != $segmentIncrement) {
  198. throw new \Exception("Invalid symbol ($errorName).");
  199. }
  200. if ($intIncrement < 1) {
  201. throw new \Exception("Out of bounds ($errorName).");
  202. }
  203. }
  204. // Apply range and increment
  205. $elem = [];
  206. $elem['number1'] = $intNumber1;
  207. $elem['hasInterval'] = $hasRange;
  208. if ($hasRange) {
  209. $elem['number2'] = $intNumber2;
  210. $elem['interval'] = $intIncrement;
  211. }
  212. $specs['elements'][] = $elem;
  213. }
  214. return $specs;
  215. }
  216. //
  217. // Function: cronCreateItems
  218. //
  219. // Description: Uses the interpreted cron specification of a single item from a cron specification to create an array with keys that match the
  220. // selected items.
  221. //
  222. // Parameters: $cronInterpreted The interpreted specification
  223. //
  224. // Result: An array where each key identifies a matching entry. E.g. the cron specification */10 for minutes will yield an array
  225. // [0] => 1
  226. // [10] => 1
  227. // [20] => 1
  228. // [30] => 1
  229. // [40] => 1
  230. // [50] => 1
  231. //
  232. final private function cronCreateItems($cronInterpreted)
  233. {
  234. $items = [];
  235. foreach ($cronInterpreted['elements'] as $elem) {
  236. if (!$elem['hasInterval']) {
  237. $items[$elem['number1']] = true;
  238. } else {
  239. for ($number = $elem['number1']; $number <= $elem['number2']; $number += $elem['interval']) {
  240. $items[$number] = true;
  241. }
  242. }
  243. }
  244. ksort($items);
  245. return $items;
  246. }
  247. //
  248. // Function: dtFromParameters
  249. //
  250. // Description: Transforms a flexible parameter passing of a datetime specification into an internally used array.
  251. //
  252. // Parameters: $time If a string interpreted as a datetime string in the YYYY-MM-DD HH:II format and other parameters ignored.
  253. // If an array $minute, $hour, $day, $month and $year are passed as keys 0-4 and other parameters ignored.
  254. // If a string, interpreted as unix time.
  255. // If omitted or specified FALSE, defaults to the current time.
  256. //
  257. // Result: An array with indices 0-4 holding the actual interpreted values for $minute, $hour, $day, $month and $year.
  258. //
  259. final private function dtFromParameters($time = false)
  260. {
  261. if ($time === false) {
  262. $arrTime = getdate();
  263. return [$arrTime['minutes'], $arrTime['hours'], $arrTime['mday'], $arrTime['mon'], $arrTime['year']];
  264. } elseif (is_array($time)) {
  265. return $time;
  266. } elseif (is_string($time)) {
  267. $arrTime = getdate(strtotime($time));
  268. return [$arrTime['minutes'], $arrTime['hours'], $arrTime['mday'], $arrTime['mon'], $arrTime['year']];
  269. } elseif (is_int($time)) {
  270. $arrTime = getdate($time);
  271. return [$arrTime['minutes'], $arrTime['hours'], $arrTime['mday'], $arrTime['mon'], $arrTime['year']];
  272. }
  273. }
  274. final private function dtAsString($arrDt)
  275. {
  276. if ($arrDt === false) {
  277. return false;
  278. }
  279. return $arrDt[4].'-'.(strlen($arrDt[3]) == 1 ? '0' : '').$arrDt[3].'-'.(strlen($arrDt[2]) == 1 ? '0' : '').$arrDt[2].' '.(strlen($arrDt[1]) == 1 ? '0' : '').$arrDt[1].':'.(strlen($arrDt[0]) == 1 ? '0' : '').$arrDt[0].':00';
  280. }
  281. //
  282. // Function: match
  283. //
  284. // Description: Returns TRUE if the specified date and time corresponds to a scheduled point in time. FALSE otherwise.
  285. //
  286. // Parameters: $time If a string interpreted as a datetime string in the YYYY-MM-DD HH:II format and other parameters ignored.
  287. // If an array $minute, $hour, $day, $month and $year are passed as keys 0-4 and other parameters ignored.
  288. // If a string, interpreted as unix time.
  289. // If omitted or specified FALSE, defaults to the current time.
  290. //
  291. // Result: TRUE if the schedule matches the specified datetime. FALSE otherwise.
  292. //
  293. final public function match($time = false)
  294. {
  295. // Convert parameters to array datetime
  296. $arrDT = $this->dtFromParameters($time);
  297. // Verify match
  298. // Years
  299. if (!array_key_exists($arrDT[4], $this->_years)) {
  300. return false;
  301. }
  302. // Day of week
  303. if (!array_key_exists(date('w', strtotime($arrDT[4].'-'.$arrDT[3].'-'.$arrDT[2])), $this->_daysOfWeek)) {
  304. return false;
  305. }
  306. // Month
  307. if (!array_key_exists($arrDT[3], $this->_months)) {
  308. return false;
  309. }
  310. // Day of month
  311. if (!array_key_exists($arrDT[2], $this->_daysOfMonth)) {
  312. return false;
  313. }
  314. // Hours
  315. if (!array_key_exists($arrDT[1], $this->_hours)) {
  316. return false;
  317. }
  318. // Minutes
  319. if (!array_key_exists($arrDT[0], $this->_minutes)) {
  320. return false;
  321. }
  322. return true;
  323. }
  324. //
  325. // Function: next
  326. //
  327. // Description: Acquires the first scheduled datetime beyond the provided one.
  328. //
  329. // Parameters: $time If a string interpreted as a datetime string in the YYYY-MM-DD HH:II format and other parameters ignored.
  330. // If an array $minute, $hour, $day, $month and $year are passed as keys 0-4 and other parameters ignored.
  331. // If a string, interpreted as unix time.
  332. // If omitted or specified FALSE, defaults to the current time.
  333. //
  334. // Result: An array with the following keys:
  335. // 0 Next scheduled minute
  336. // 1 Next scheduled hour
  337. // 2 Next scheduled date
  338. // 3 Next scheduled month
  339. // 4 Next scheduled year
  340. //
  341. final public function next($time = false)
  342. {
  343. // Convert parameters to array datetime
  344. $arrDT = $this->dtFromParameters($time);
  345. while (1) {
  346. // Verify the current date is in range. If not, move into range and consider this the next position
  347. if (!array_key_exists($arrDT[4], $this->_years)) {
  348. if (($arrDT[4] = $this->getEarliestItem($this->_years, $arrDT[4], false)) === false) {
  349. return false;
  350. }
  351. $arrDT[3] = $this->getEarliestItem($this->_months);
  352. $arrDT[2] = $this->getEarliestItem($this->_daysOfMonth);
  353. $arrDT[1] = $this->getEarliestItem($this->_hours);
  354. $arrDT[0] = $this->getEarliestItem($this->_minutes);
  355. break;
  356. } elseif (!array_key_exists($arrDT[3], $this->_months)) {
  357. $arrDT[3] = $this->getEarliestItem($this->_months, $arrDT[3]);
  358. $arrDT[2] = $this->getEarliestItem($this->_daysOfMonth);
  359. $arrDT[1] = $this->getEarliestItem($this->_hours);
  360. $arrDT[0] = $this->getEarliestItem($this->_minutes);
  361. break;
  362. } elseif (!array_key_exists($arrDT[2], $this->_daysOfMonth)) {
  363. $arrDT[2] = $this->getEarliestItem($this->_daysOfMonth, $arrDT[2]);
  364. $arrDT[1] = $this->getEarliestItem($this->_hours);
  365. $arrDT[0] = $this->getEarliestItem($this->_minutes);
  366. break;
  367. } elseif (!array_key_exists($arrDT[1], $this->_hours)) {
  368. $arrDT[1] = $this->getEarliestItem($this->_hours, $arrDT[1]);
  369. $arrDT[0] = $this->getEarliestItem($this->_minutes);
  370. break;
  371. } elseif (!array_key_exists($arrDT[1], $this->_hours)) {
  372. $arrDT[0] = $this->getEarliestItem($this->_minutes, $arrDT[0]);
  373. break;
  374. }
  375. // Advance minute, hour, date, month and year while overflowing.
  376. $daysInThisMonth = date('t', strtotime($arrDT[4].'-'.$arrDT[3]));
  377. if ($this->advanceItem($this->_minutes, 0, 59, $arrDT[0])) {
  378. if ($this->advanceItem($this->_hours, 0, 23, $arrDT[1])) {
  379. if ($this->advanceItem($this->_daysOfMonth, 0, $daysInThisMonth, $arrDT[2])) {
  380. if ($this->advanceItem($this->_months, 1, 12, $arrDT[3])) {
  381. if ($this->advanceItem($this->_years, $this->RANGE_YEARS_MIN, $this->RANGE_YEARS_MAX, $arrDT[4])) {
  382. return false;
  383. }
  384. }
  385. }
  386. }
  387. }
  388. break;
  389. }
  390. // If Datetime now points to a day that is schedule then return.
  391. $dayOfWeek = date('w', strtotime($this->dtAsString($arrDT)));
  392. if (array_key_exists($dayOfWeek, $this->_daysOfWeek)) {
  393. return $arrDT;
  394. }
  395. // Otherwise move to next scheduled date
  396. return $this->next($arrDT);
  397. }
  398. final public function nextAsString($time = false)
  399. {
  400. return $this->dtAsString($this->next($time));
  401. }
  402. final public function nextAsTime($time = false)
  403. {
  404. return strtotime($this->dtAsString($this->next($time)));
  405. }
  406. //
  407. // Function: advanceItem
  408. //
  409. // Description: Advances the current item to the next one (the next minute, the next hour, etc.).
  410. //
  411. // Parameters: $arrItems A reference to the collection in which to advance.
  412. // $rangeMin The lowest possible value for $current.
  413. // $rangeMax The highest possible value for $current
  414. // $current The index that is being incremented.
  415. //
  416. // Result: FALSE if current did not overflow (reset back to the earliest possible value). TRUE if it did.
  417. //
  418. final private function advanceItem($arrItems, $rangeMin, $rangeMax, &$current)
  419. {
  420. // Advance pointer
  421. $current++;
  422. // If still before start, move to earliest
  423. if ($current < $rangeMin) {
  424. $current = $this->getEarliestItem($arrItems);
  425. }
  426. // Parse items until found or overflow
  427. for (; $current <= $rangeMax; $current++) {
  428. if (array_key_exists($current, $arrItems)) {
  429. return false;
  430. }
  431. } // We did not overflow
  432. // Or overflow
  433. $current = $this->getEarliestItem($arrItems);
  434. return true;
  435. }
  436. //
  437. // Function: getEarliestItem
  438. //
  439. // Description: Retrieves the earliest item in a collection, e.g. the earliest minute or the earliest month.
  440. //
  441. // Parameters: $arrItems A reference to the collection in which to search.
  442. // $afterItem The highest index that is to be skipped.
  443. //
  444. final private function getEarliestItem($arrItems, $afterItem = false, $allowOverflow = true)
  445. {
  446. // If no filter is specified, return the earliest listed item.
  447. if ($afterItem === false) {
  448. reset($arrItems);
  449. return key($arrItems);
  450. }
  451. // Or parse until we passed $afterItem
  452. foreach ($arrItems as $key => $value) {
  453. if ($key > $afterItem) {
  454. return $key;
  455. }
  456. }
  457. // If still nothing found, we may have exhausted our options.
  458. if (!$allowOverflow) {
  459. return false;
  460. }
  461. reset($arrItems);
  462. return key($arrItems);
  463. }
  464. //
  465. // Function: previous
  466. //
  467. // Description: Acquires the first scheduled datetime before the provided one.
  468. //
  469. // Parameters: $time If a string interpreted as a datetime string in the YYYY-MM-DD HH:II format and other parameters ignored.
  470. // If an array $minute, $hour, $day, $month and $year are passed as keys 0-4 and other parameters ignored.
  471. // If a string, interpreted as unix time.
  472. // If omitted or specified FALSE, defaults to the current time.
  473. //
  474. // Result: An array with the following keys:
  475. // 0 Previous scheduled minute
  476. // 1 Previous scheduled hour
  477. // 2 Previous scheduled date
  478. // 3 Previous scheduled month
  479. // 4 Previous scheduled year
  480. //
  481. final public function previous($time = false)
  482. {
  483. // Convert parameters to array datetime
  484. $arrDT = $this->dtFromParameters($time);
  485. while (1) {
  486. // Verify the current date is in range. If not, move into range and consider this the previous position
  487. if (!array_key_exists($arrDT[4], $this->_years)) {
  488. if (($arrDT[4] = $this->getLatestItem($this->_years, $arrDT[4], false)) === false) {
  489. return false;
  490. }
  491. $arrDT[3] = $this->getLatestItem($this->_months);
  492. $arrDT[2] = $this->getLatestItem($this->_daysOfMonth);
  493. $arrDT[1] = $this->getLatestItem($this->_hours);
  494. $arrDT[0] = $this->getLatestItem($this->_minutes);
  495. break;
  496. } elseif (!array_key_exists($arrDT[3], $this->_months)) {
  497. $arrDT[3] = $this->getLatestItem($this->_months, $arrDT[3]);
  498. $arrDT[2] = $this->getLatestItem($this->_daysOfMonth);
  499. $arrDT[1] = $this->getLatestItem($this->_hours);
  500. $arrDT[0] = $this->getLatestItem($this->_minutes);
  501. break;
  502. } elseif (!array_key_exists($arrDT[2], $this->_daysOfMonth)) {
  503. $arrDT[2] = $this->getLatestItem($this->_daysOfMonth, $arrDT[2]);
  504. $arrDT[1] = $this->getLatestItem($this->_hours);
  505. $arrDT[0] = $this->getLatestItem($this->_minutes);
  506. break;
  507. } elseif (!array_key_exists($arrDT[1], $this->_hours)) {
  508. $arrDT[1] = $this->getLatestItem($this->_hours, $arrDT[1]);
  509. $arrDT[0] = $this->getLatestItem($this->_minutes);
  510. break;
  511. } elseif (!array_key_exists($arrDT[1], $this->_hours)) {
  512. $arrDT[0] = $this->getLatestItem($this->_minutes, $arrDT[0]);
  513. break;
  514. }
  515. // Recede minute, hour, date, month and year while overflowing.
  516. $daysInPreviousMonth = date('t', strtotime('-1 month', strtotime($arrDT[4].'-'.$arrDT[3])));
  517. if ($this->recedeItem($this->_minutes, 0, 59, $arrDT[0])) {
  518. if ($this->recedeItem($this->_hours, 0, 23, $arrDT[1])) {
  519. if ($this->recedeItem($this->_daysOfMonth, 0, $daysInPreviousMonth, $arrDT[2])) {
  520. if ($this->recedeItem($this->_months, 1, 12, $arrDT[3])) {
  521. if ($this->recedeItem($this->_years, $this->RANGE_YEARS_MIN, $this->RANGE_YEARS_MAX, $arrDT[4])) {
  522. return false;
  523. }
  524. }
  525. }
  526. }
  527. }
  528. break;
  529. }
  530. // If Datetime now points to a day that is schedule then return.
  531. $dayOfWeek = date('w', strtotime($this->dtAsString($arrDT)));
  532. if (array_key_exists($dayOfWeek, $this->_daysOfWeek)) {
  533. return $arrDT;
  534. }
  535. // Otherwise move to next scheduled date
  536. return $this->previous($arrDT);
  537. }
  538. final public function previousAsString($time = false)
  539. {
  540. return $this->dtAsString($this->previous($time));
  541. }
  542. final public function previousAsTime($time = false)
  543. {
  544. return strtotime($this->dtAsString($this->previous($time)));
  545. }
  546. //
  547. // Function: recedeItem
  548. //
  549. // Description: Recedes the current item to the previous one (the previous minute, the previous hour, etc.).
  550. //
  551. // Parameters: $arrItems A reference to the collection in which to recede.
  552. // $rangeMin The lowest possible value for $current.
  553. // $rangeMax The highest possible value for $current
  554. // $current The index that is being decremented.
  555. //
  556. // Result: FALSE if current did not overflow (reset back to the highest possible value). TRUE if it did.
  557. //
  558. final private function recedeItem($arrItems, $rangeMin, $rangeMax, &$current)
  559. {
  560. // Recede pointer
  561. $current--;
  562. // If still above highest, move to highest
  563. if ($current > $rangeMax) {
  564. $current = $this->getLatestItem($arrItems, $rangeMax + 1);
  565. }
  566. // Parse items until found or overflow
  567. for (; $current >= $rangeMin; $current--) {
  568. if (array_key_exists($current, $arrItems)) {
  569. return false;
  570. }
  571. } // We did not overflow
  572. // Or overflow
  573. $current = $this->getLatestItem($arrItems, $rangeMax + 1);
  574. return true;
  575. }
  576. //
  577. // Function: getLatestItem
  578. //
  579. // Description: Retrieves the latest item in a collection, e.g. the latest minute or the latest month.
  580. //
  581. // Parameters: $arrItems A reference to the collection in which to search.
  582. // $beforeItem The lowest index that is to be skipped.
  583. //
  584. final private function getLatestItem($arrItems, $beforeItem = false, $allowOverflow = true)
  585. {
  586. // If no filter is specified, return the latestlisted item.
  587. if ($beforeItem === false) {
  588. end($arrItems);
  589. return key($arrItems);
  590. }
  591. // Or parse until we passed $beforeItem
  592. end($arrItems);
  593. do {
  594. if (($key = key($arrItems)) < $beforeItem) {
  595. return $key;
  596. }
  597. } while (prev($arrItems));
  598. // If still nothing found, we may have exhausted our options.
  599. if (!$allowOverflow) {
  600. return false;
  601. }
  602. end($arrItems);
  603. return key($arrItems);
  604. }
  605. //
  606. // Function:
  607. //
  608. // Description:
  609. //
  610. // Parameters:
  611. //
  612. // Result:
  613. //
  614. final private function getClass($spec)
  615. {
  616. if (!$this->classIsSpecified($spec)) {
  617. return '0';
  618. }
  619. if ($this->classIsSingleFixed($spec)) {
  620. return '1';
  621. }
  622. return '2';
  623. }
  624. //
  625. // Function:
  626. //
  627. // Description: Returns TRUE if the Cron Specification is specified. FALSE otherwise. This is true if the specification has more than one entry
  628. // or is anything than the entire approved range ("*").
  629. //
  630. // Parameters:
  631. //
  632. // Result:
  633. //
  634. final private function classIsSpecified($spec)
  635. {
  636. if ($spec['elements'][0]['hasInterval'] == false) {
  637. return true;
  638. }
  639. if ($spec['elements'][0]['number1'] != $spec['rangeMin']) {
  640. return true;
  641. }
  642. if ($spec['elements'][0]['number2'] != $spec['rangeMax']) {
  643. return true;
  644. }
  645. if ($spec['elements'][0]['interval'] != 1) {
  646. return true;
  647. }
  648. return false;
  649. }
  650. //
  651. // Function:
  652. //
  653. // Description: Returns TRUE if the Cron Specification is specified as a single value. FALSE otherwise. This is true only if there is only
  654. // one entry and the entry is only a single number (e.g. "10")
  655. //
  656. // Parameters:
  657. //
  658. // Result:
  659. //
  660. final private function classIsSingleFixed($spec)
  661. {
  662. return (count($spec['elements']) == 1) && (!$spec['elements'][0]['hasInterval']);
  663. }
  664. final private function initLang($language = 'en')
  665. {
  666. switch ($language) {
  667. case 'en':
  668. $this->_lang['elemMin: at_the_hour'] = 'at the hour';
  669. $this->_lang['elemMin: after_the_hour_every_X_minute'] = 'every minute';
  670. $this->_lang['elemMin: after_the_hour_every_X_minute_plural'] = 'every @1 minutes';
  671. $this->_lang['elemMin: every_consecutive_minute'] = 'every consecutive minute';
  672. $this->_lang['elemMin: every_consecutive_minute_plural'] = 'every consecutive @1 minutes';
  673. $this->_lang['elemMin: every_minute'] = 'every minute';
  674. $this->_lang['elemMin: between_X_and_Y'] = 'from the @1 to the @2';
  675. $this->_lang['elemMin: at_X:Y'] = 'At @1:@2';
  676. $this->_lang['elemHour: past_X:00'] = 'past @1:00';
  677. $this->_lang['elemHour: between_X:00_and_Y:59'] = 'between @1:00 and @2:59';
  678. $this->_lang['elemHour: in_the_60_minutes_past_'] = 'in the 60 minutes past every consecutive hour';
  679. $this->_lang['elemHour: in_the_60_minutes_past__plural'] = 'in the 60 minutes past every consecutive @1 hours';
  680. $this->_lang['elemHour: past_every_consecutive_'] = 'past every consecutive hour';
  681. $this->_lang['elemHour: past_every_consecutive__plural'] = 'past every consecutive @1 hours';
  682. $this->_lang['elemHour: past_every_hour'] = 'past every hour';
  683. $this->_lang['elemDOM: the_X'] = 'the @1';
  684. $this->_lang['elemDOM: every_consecutive_day'] = 'every consecutive day';
  685. $this->_lang['elemDOM: every_consecutive_day_plural'] = 'every consecutive @1 days';
  686. $this->_lang['elemDOM: on_every_day'] = 'on every day';
  687. $this->_lang['elemDOM: between_the_Xth_and_Yth'] = 'between the @1 and the @2';
  688. $this->_lang['elemDOM: on_the_X'] = 'on the @1';
  689. $this->_lang['elemDOM: on_X'] = 'on @1';
  690. $this->_lang['elemMonth: every_X'] = 'every @1';
  691. $this->_lang['elemMonth: every_consecutive_month'] = 'every consecutive month';
  692. $this->_lang['elemMonth: every_consecutive_month_plural'] = 'every consecutive @1 months';
  693. $this->_lang['elemMonth: between_X_and_Y'] = 'from @1 to @2';
  694. $this->_lang['elemMonth: of_every_month'] = 'of every month';
  695. $this->_lang['elemMonth: during_every_X'] = 'during every @1';
  696. $this->_lang['elemMonth: during_X'] = 'during @1';
  697. $this->_lang['elemYear: in_X'] = 'in @1';
  698. $this->_lang['elemYear: every_consecutive_year'] = 'every consecutive year';
  699. $this->_lang['elemYear: every_consecutive_year_plural'] = 'every consecutive @1 years';
  700. $this->_lang['elemYear: from_X_through_Y'] = 'from @1 through @2';
  701. $this->_lang['elemDOW: on_every_day'] = 'on every day';
  702. $this->_lang['elemDOW: on_X'] = 'on @1';
  703. $this->_lang['elemDOW: but_only_on_X'] = 'but only if the event takes place on @1';
  704. $this->_lang['separator_and'] = 'and';
  705. $this->_lang['separator_or'] = 'or';
  706. $this->_lang['day: 0_plural'] = 'Sundays';
  707. $this->_lang['day: 1_plural'] = 'Mondays';
  708. $this->_lang['day: 2_plural'] = 'Tuesdays';
  709. $this->_lang['day: 3_plural'] = 'Wednesdays';
  710. $this->_lang['day: 4_plural'] = 'Thursdays';
  711. $this->_lang['day: 5_plural'] = 'Fridays';
  712. $this->_lang['day: 6_plural'] = 'Saturdays';
  713. $this->_lang['month: 1'] = 'January';
  714. $this->_lang['month: 2'] = 'February';
  715. $this->_lang['month: 3'] = 'March';
  716. $this->_lang['month: 4'] = 'April';
  717. $this->_lang['month: 5'] = 'May';
  718. $this->_lang['month: 6'] = 'June';
  719. $this->_lang['month: 7'] = 'July';
  720. $this->_lang['month: 8'] = 'Augustus';
  721. $this->_lang['month: 9'] = 'September';
  722. $this->_lang['month: 10'] = 'October';
  723. $this->_lang['month: 11'] = 'November';
  724. $this->_lang['month: 12'] = 'December';
  725. $this->_lang['ordinal: 1'] = '1st';
  726. $this->_lang['ordinal: 2'] = '2nd';
  727. $this->_lang['ordinal: 3'] = '3rd';
  728. $this->_lang['ordinal: 4'] = '4th';
  729. $this->_lang['ordinal: 5'] = '5th';
  730. $this->_lang['ordinal: 6'] = '6th';
  731. $this->_lang['ordinal: 7'] = '7th';
  732. $this->_lang['ordinal: 8'] = '8th';
  733. $this->_lang['ordinal: 9'] = '9th';
  734. $this->_lang['ordinal: 10'] = '10th';
  735. $this->_lang['ordinal: 11'] = '11th';
  736. $this->_lang['ordinal: 12'] = '12th';
  737. $this->_lang['ordinal: 13'] = '13th';
  738. $this->_lang['ordinal: 14'] = '14th';
  739. $this->_lang['ordinal: 15'] = '15th';
  740. $this->_lang['ordinal: 16'] = '16th';
  741. $this->_lang['ordinal: 17'] = '17th';
  742. $this->_lang['ordinal: 18'] = '18th';
  743. $this->_lang['ordinal: 19'] = '19th';
  744. $this->_lang['ordinal: 20'] = '20th';
  745. $this->_lang['ordinal: 21'] = '21st';
  746. $this->_lang['ordinal: 22'] = '22nd';
  747. $this->_lang['ordinal: 23'] = '23rd';
  748. $this->_lang['ordinal: 24'] = '24th';
  749. $this->_lang['ordinal: 25'] = '25th';
  750. $this->_lang['ordinal: 26'] = '26th';
  751. $this->_lang['ordinal: 27'] = '27th';
  752. $this->_lang['ordinal: 28'] = '28th';
  753. $this->_lang['ordinal: 29'] = '29th';
  754. $this->_lang['ordinal: 30'] = '30th';
  755. $this->_lang['ordinal: 31'] = '31st';
  756. $this->_lang['ordinal: 32'] = '32nd';
  757. $this->_lang['ordinal: 33'] = '33rd';
  758. $this->_lang['ordinal: 34'] = '34th';
  759. $this->_lang['ordinal: 35'] = '35th';
  760. $this->_lang['ordinal: 36'] = '36th';
  761. $this->_lang['ordinal: 37'] = '37th';
  762. $this->_lang['ordinal: 38'] = '38th';
  763. $this->_lang['ordinal: 39'] = '39th';
  764. $this->_lang['ordinal: 40'] = '40th';
  765. $this->_lang['ordinal: 41'] = '41st';
  766. $this->_lang['ordinal: 42'] = '42nd';
  767. $this->_lang['ordinal: 43'] = '43rd';
  768. $this->_lang['ordinal: 44'] = '44th';
  769. $this->_lang['ordinal: 45'] = '45th';
  770. $this->_lang['ordinal: 46'] = '46th';
  771. $this->_lang['ordinal: 47'] = '47th';
  772. $this->_lang['ordinal: 48'] = '48th';
  773. $this->_lang['ordinal: 49'] = '49th';
  774. $this->_lang['ordinal: 50'] = '50th';
  775. $this->_lang['ordinal: 51'] = '51st';
  776. $this->_lang['ordinal: 52'] = '52nd';
  777. $this->_lang['ordinal: 53'] = '53rd';
  778. $this->_lang['ordinal: 54'] = '54th';
  779. $this->_lang['ordinal: 55'] = '55th';
  780. $this->_lang['ordinal: 56'] = '56th';
  781. $this->_lang['ordinal: 57'] = '57th';
  782. $this->_lang['ordinal: 58'] = '58th';
  783. $this->_lang['ordinal: 59'] = '59th';
  784. break;
  785. case 'nl':
  786. $this->_lang['elemMin: at_the_hour'] = 'op het hele uur';
  787. $this->_lang['elemMin: after_the_hour_every_X_minute'] = 'elke minuut';
  788. $this->_lang['elemMin: after_the_hour_every_X_minute_plural'] = 'elke @1 minuten';
  789. $this->_lang['elemMin: every_consecutive_minute'] = 'elke opeenvolgende minuut';
  790. $this->_lang['elemMin: every_consecutive_minute_plural'] = 'elke opeenvolgende @1 minuten';
  791. $this->_lang['elemMin: every_minute'] = 'elke minuut';
  792. $this->_lang['elemMin: between_X_and_Y'] = 'van de @1 tot en met de @2';
  793. $this->_lang['elemMin: at_X:Y'] = 'Om @1:@2';
  794. $this->_lang['elemHour: past_X:00'] = 'na @1:00';
  795. $this->_lang['elemHour: between_X:00_and_Y:59'] = 'tussen @1:00 en @2:59';
  796. $this->_lang['elemHour: in_the_60_minutes_past_'] = 'in de 60 minuten na elk opeenvolgend uur';
  797. $this->_lang['elemHour: in_the_60_minutes_past__plural'] = 'in de 60 minuten na elke opeenvolgende @1 uren';
  798. $this->_lang['elemHour: past_every_consecutive_'] = 'na elk opeenvolgend uur';
  799. $this->_lang['elemHour: past_every_consecutive__plural'] = 'na elke opeenvolgende @1 uren';
  800. $this->_lang['elemHour: past_every_hour'] = 'na elk uur';
  801. $this->_lang['elemDOM: the_X'] = 'de @1';
  802. $this->_lang['elemDOM: every_consecutive_day'] = 'elke opeenvolgende dag';
  803. $this->_lang['elemDOM: every_consecutive_day_plural'] = 'elke opeenvolgende @1 dagen';
  804. $this->_lang['elemDOM: on_every_day'] = 'op elke dag';
  805. $this->_lang['elemDOM: between_the_Xth_and_Yth'] = 'tussen de @1 en de @2';
  806. $this->_lang['elemDOM: on_the_X'] = 'op de @1';
  807. $this->_lang['elemDOM: on_X'] = 'op @1';
  808. $this->_lang['elemMonth: every_X'] = 'elke @1';
  809. $this->_lang['elemMonth: every_consecutive_month'] = 'elke opeenvolgende maand';
  810. $this->_lang['elemMonth: every_consecutive_month_plural'] = 'elke opeenvolgende @1 maanden';
  811. $this->_lang['elemMonth: between_X_and_Y'] = 'van @1 tot @2';
  812. $this->_lang['elemMonth: of_every_month'] = 'van elke maand';
  813. $this->_lang['elemMonth: during_every_X'] = 'tijdens elke @1';
  814. $this->_lang['elemMonth: during_X'] = 'tijdens @1';
  815. $this->_lang['elemYear: in_X'] = 'in @1';
  816. $this->_lang['elemYear: every_consecutive_year'] = 'elk opeenvolgend jaar';
  817. $this->_lang['elemYear: every_consecutive_year_plural'] = 'elke opeenvolgende @1 jaren';
  818. $this->_lang['elemYear: from_X_through_Y'] = 'van @1 tot en met @2';
  819. $this->_lang['elemDOW: on_every_day'] = 'op elke dag';
  820. $this->_lang['elemDOW: on_X'] = 'op @1';
  821. $this->_lang['elemDOW: but_only_on_X'] = 'maar alleen als het plaatsvindt op @1';
  822. $this->_lang['separator_and'] = 'en';
  823. $this->_lang['separator_of'] = 'of';
  824. $this->_lang['day: 0_plural'] = 'zondagen';
  825. $this->_lang['day: 1_plural'] = 'maandagen';
  826. $this->_lang['day: 2_plural'] = 'dinsdagen';
  827. $this->_lang['day: 3_plural'] = 'woensdagen';
  828. $this->_lang['day: 4_plural'] = 'donderdagen';
  829. $this->_lang['day: 5_plural'] = 'vrijdagen';
  830. $this->_lang['day: 6_plural'] = 'zaterdagen';
  831. $this->_lang['month: 1'] = 'januari';
  832. $this->_lang['month: 2'] = 'februari';
  833. $this->_lang['month: 3'] = 'maart';
  834. $this->_lang['month: 4'] = 'april';
  835. $this->_lang['month: 5'] = 'mei';
  836. $this->_lang['month: 6'] = 'juni';
  837. $this->_lang['month: 7'] = 'juli';
  838. $this->_lang['month: 8'] = 'augustus';
  839. $this->_lang['month: 9'] = 'september';
  840. $this->_lang['month: 10'] = 'october';
  841. $this->_lang['month: 11'] = 'november';
  842. $this->_lang['month: 12'] = 'december';
  843. $this->_lang['ordinal: 1'] = '1e';
  844. $this->_lang['ordinal: 2'] = '2e';
  845. $this->_lang['ordinal: 3'] = '3e';
  846. $this->_lang['ordinal: 4'] = '4e';
  847. $this->_lang['ordinal: 5'] = '5e';
  848. $this->_lang['ordinal: 6'] = '6e';
  849. $this->_lang['ordinal: 7'] = '7e';
  850. $this->_lang['ordinal: 8'] = '8e';
  851. $this->_lang['ordinal: 9'] = '9e';
  852. $this->_lang['ordinal: 10'] = '10e';
  853. $this->_lang['ordinal: 11'] = '11e';
  854. $this->_lang['ordinal: 12'] = '12e';
  855. $this->_lang['ordinal: 13'] = '13e';
  856. $this->_lang['ordinal: 14'] = '14e';
  857. $this->_lang['ordinal: 15'] = '15e';
  858. $this->_lang['ordinal: 16'] = '16e';
  859. $this->_lang['ordinal: 17'] = '17e';
  860. $this->_lang['ordinal: 18'] = '18e';
  861. $this->_lang['ordinal: 19'] = '19e';
  862. $this->_lang['ordinal: 20'] = '20e';
  863. $this->_lang['ordinal: 21'] = '21e';
  864. $this->_lang['ordinal: 22'] = '22e';
  865. $this->_lang['ordinal: 23'] = '23e';
  866. $this->_lang['ordinal: 24'] = '24e';
  867. $this->_lang['ordinal: 25'] = '25e';
  868. $this->_lang['ordinal: 26'] = '26e';
  869. $this->_lang['ordinal: 27'] = '27e';
  870. $this->_lang['ordinal: 28'] = '28e';
  871. $this->_lang['ordinal: 29'] = '29e';
  872. $this->_lang['ordinal: 30'] = '30e';
  873. $this->_lang['ordinal: 31'] = '31e';
  874. $this->_lang['ordinal: 32'] = '32e';
  875. $this->_lang['ordinal: 33'] = '33e';
  876. $this->_lang['ordinal: 34'] = '34e';
  877. $this->_lang['ordinal: 35'] = '35e';
  878. $this->_lang['ordinal: 36'] = '36e';
  879. $this->_lang['ordinal: 37'] = '37e';
  880. $this->_lang['ordinal: 38'] = '38e';
  881. $this->_lang['ordinal: 39'] = '39e';
  882. $this->_lang['ordinal: 40'] = '40e';
  883. $this->_lang['ordinal: 41'] = '41e';
  884. $this->_lang['ordinal: 42'] = '42e';
  885. $this->_lang['ordinal: 43'] = '43e';
  886. $this->_lang['ordinal: 44'] = '44e';
  887. $this->_lang['ordinal: 45'] = '45e';
  888. $this->_lang['ordinal: 46'] = '46e';
  889. $this->_lang['ordinal: 47'] = '47e';
  890. $this->_lang['ordinal: 48'] = '48e';
  891. $this->_lang['ordinal: 49'] = '49e';
  892. $this->_lang['ordinal: 50'] = '50e';
  893. $this->_lang['ordinal: 51'] = '51e';
  894. $this->_lang['ordinal: 52'] = '52e';
  895. $this->_lang['ordinal: 53'] = '53e';
  896. $this->_lang['ordinal: 54'] = '54e';
  897. $this->_lang['ordinal: 55'] = '55e';
  898. $this->_lang['ordinal: 56'] = '56e';
  899. $this->_lang['ordinal: 57'] = '57e';
  900. $this->_lang['ordinal: 58'] = '58e';
  901. $this->_lang['ordinal: 59'] = '59e';
  902. break;
  903. }
  904. }
  905. final private function natlangPad2($number)
  906. {
  907. return (strlen($number) == 1 ? '0' : '').$number;
  908. }
  909. final private function natlangApply($id, $p1 = false, $p2 = false, $p3 = false, $p4 = false, $p5 = false, $p6 = false)
  910. {
  911. $txt = $this->_lang[$id];
  912. if ($p1 !== false) {
  913. $txt = str_replace('@1', $p1, $txt);
  914. }
  915. if ($p2 !== false) {
  916. $txt = str_replace('@2', $p2, $txt);
  917. }
  918. if ($p3 !== false) {
  919. $txt = str_replace('@3', $p3, $txt);
  920. }
  921. if ($p4 !== false) {
  922. $txt = str_replace('@4', $p4, $txt);
  923. }
  924. if ($p5 !== false) {
  925. $txt = str_replace('@5', $p5, $txt);
  926. }
  927. if ($p6 !== false) {
  928. $txt = str_replace('@6', $p6, $txt);
  929. }
  930. return $txt;
  931. }
  932. //
  933. // Function: natlangRange
  934. //
  935. // Description: Converts a range into natural language
  936. //
  937. // Parameters:
  938. //
  939. // Result:
  940. //
  941. final private function natlangRange($spec, $entryFunction, $p1 = false)
  942. {
  943. $arrIntervals = [];
  944. foreach ($spec['elements'] as $elem) {
  945. $arrIntervals[] = call_user_func($entryFunction, $elem, $p1);
  946. }
  947. $txt = '';
  948. for ($index = 0; $index < count($arrIntervals); $index++) {
  949. $txt .= ($index == 0 ? '' : ($index == (count($arrIntervals) - 1) ? ' '.$this->natlangApply('separator_and').' ' : ', ')).$arrIntervals[$index];
  950. }
  951. return $txt;
  952. }
  953. //
  954. // Function: natlangElementMinute
  955. //
  956. // Description: Converts an entry from the minute specification to natural language.
  957. //
  958. final private function natlangElementMinute($elem)
  959. {
  960. if (!$elem['hasInterval']) {
  961. if ($elem['number1'] == 0) {
  962. return $this->natlangApply('elemMin: at_the_hour');
  963. } else {
  964. return $this->natlangApply('elemMin: after_the_hour_every_X_minute'.($elem['number1'] == 1 ? '' : '_plural'), $elem['number1']);
  965. }
  966. }
  967. $txt = $this->natlangApply('elemMin: every_consecutive_minute'.($elem['interval'] == 1 ? '' : '_plural'), $elem['interval']);
  968. if (($elem['number1'] != $this->_cronMinutes['rangeMin']) || ($elem['number2'] != $this->_cronMinutes['rangeMax'])) {
  969. $txt .= ' ('.$this->natlangApply('elemMin: between_X_and_Y', $this->natlangApply('ordinal: '.$elem['number1']), $this->natlangApply('ordinal: '.$elem['number2'])).')';
  970. }
  971. return $txt;
  972. }
  973. //
  974. // Function: natlangElementHour
  975. //
  976. // Description: Converts an entry from the hour specification to natural language.
  977. //
  978. final private function natlangElementHour($elem, $asBetween)
  979. {
  980. if (!$elem['hasInterval']) {
  981. if ($asBetween) {
  982. return $this->natlangApply('elemHour: between_X:00_and_Y:59', $this->natlangPad2($elem['number1']), $this->natlangPad2($elem['number1']));
  983. } else {
  984. return $this->natlangApply('elemHour: past_X:00', $this->natlangPad2($elem['number1']));
  985. }
  986. }
  987. if ($asBetween) {
  988. $txt = $this->natlangApply('elemHour: in_the_60_minutes_past_'.($elem['interval'] == 1 ? '' : '_plural'), $elem['interval']);
  989. } else {
  990. $txt = $this->natlangApply('elemHour: past_every_consecutive_'.($elem['interval'] == 1 ? '' : '_plural'), $elem['interval']);
  991. }
  992. if (($elem['number1'] != $this->_cronHours['rangeMin']) || ($elem['number2'] != $this->_cronHours['rangeMax'])) {
  993. $txt .= ' ('.$this->natlangApply('elemHour: between_X:00_and_Y:59', $elem['number1'], $elem['number2']).')';
  994. }
  995. return $txt;
  996. }
  997. //
  998. // Function: natlangElementDayOfMonth
  999. //
  1000. // Description: Converts an entry from the day of month specification to natural language.
  1001. //
  1002. final private function natlangElementDayOfMonth($elem)
  1003. {
  1004. if (!$elem['hasInterval']) {
  1005. return $this->natlangApply('elemDOM: the_X', $this->natlangApply('ordinal: '.$elem['number1']));
  1006. }
  1007. $txt = $this->natlangApply('elemDOM: every_consecutive_day'.($elem['interval'] == 1 ? '' : '_plural'), $elem['interval']);
  1008. if (($elem['number1'] != $this->_cronHours['rangeMin']) || ($elem['number2'] != $this->_cronHours['rangeMax'])) {
  1009. $txt .= ' ('.$this->natlangApply('elemDOM: between_the_Xth_and_Yth', $this->natlangApply('ordinal: '.$elem['number1']), $this->natlangApply('ordinal: '.$elem['number2'])).')';
  1010. }
  1011. return $txt;
  1012. }
  1013. //
  1014. // Function: natlangElementDayOfMonth
  1015. //
  1016. // Description: Converts an entry from the month specification to natural language.
  1017. //
  1018. final private function natlangElementMonth($elem)
  1019. {
  1020. if (!$elem['hasInterval']) {
  1021. return $this->natlangApply('elemMonth: every_X', $this->natlangApply('month: '.$elem['number1']));
  1022. }
  1023. $txt = $this->natlangApply('elemMonth: every_consecutive_month'.($elem['interval'] == 1 ? '' : '_plural'), $elem['interval']);
  1024. if (($elem['number1'] != $this->_cronMonths['rangeMin']) || ($elem['number2'] != $this->_cronMonths['rangeMax'])) {
  1025. $txt .= ' ('.$this->natlangApply('elemMonth: between_X_and_Y', $this->natlangApply('month: '.$elem['number1']), $this->natlangApply('month: '.$elem['number2'])).')';
  1026. }
  1027. return $txt;
  1028. }
  1029. //
  1030. // Function: natlangElementYear
  1031. //
  1032. // Description: Converts an entry from the year specification to natural language.
  1033. //
  1034. final private function natlangElementYear($elem)
  1035. {
  1036. if (!$elem['hasInterval']) {
  1037. return $elem['number1'];
  1038. }
  1039. $txt = $this->natlangApply('elemYear: every_consecutive_year'.($elem['interval'] == 1 ? '' : '_plural'), $elem['interval']);
  1040. if (($elem['number1'] != $this->_cronMonths['rangeMin']) || ($elem['number2'] != $this->_cronMonths['rangeMax'])) {
  1041. $txt .= ' ('.$this->natlangApply('elemYear: from_X_through_Y', $elem['number1'], $elem['number2']).')';
  1042. }
  1043. return $txt;
  1044. }
  1045. //
  1046. // Function: asNaturalLanguage
  1047. //
  1048. // Description: Returns the current cron specification in natural language.
  1049. //
  1050. // Parameters: None
  1051. //
  1052. // Result: A string containing a natural language text.
  1053. //
  1054. final public function asNaturalLanguage()
  1055. {
  1056. $switchForceDateExplaination = false;
  1057. $switchDaysOfWeekAreExcluding = true;
  1058. // Generate Time String
  1059. $txtMinutes = [];
  1060. $txtMinutes[0] = $this->natlangApply('elemMin: every_minute');
  1061. $txtMinutes[1] = $this->natlangElementMinute($this->_cronMinutes['elements'][0]);
  1062. $txtMinutes[2] = $this->natlangRange($this->_cronMinutes, [$this, 'natlangElementMinute']);
  1063. $txtHours = [];
  1064. $txtHours[0] = $this->natlangApply('elemHour: past_every_hour');
  1065. $txtHours[1] = [];
  1066. $txtHours[1]['between'] = $this->natlangRange($this->_cronHours, [$this, 'natlangElementHour'], true);
  1067. $txtHours[1]['past'] = $this->natlangRange($this->_cronHours, [$this, 'natlangElementHour'], false);
  1068. $txtHours[2] = [];
  1069. $txtHours[2]['between'] = $this->natlangRange($this->_cronHours, [$this, 'natlangElementHour'], true);
  1070. $txtHours[2]['past'] = $this->natlangRange($this->_cronHours, [$this, 'natlangElementHour'], false);
  1071. $classMinutes = $this->getClass($this->_cronMinutes);
  1072. $classHours = $this->getClass($this->_cronHours);
  1073. switch ($classMinutes.$classHours) {
  1074. // Special case: Unspecified date + Unspecified month
  1075. //
  1076. // Rule: The language for unspecified fields is omitted if a more detailed field has already been explained.
  1077. //
  1078. // The minutes field always yields an explaination, at the very least in the form of 'every minute'. This rule states that if the
  1079. // hour is not specified, it can be omitted because 'every minute' is already sufficiently clear.
  1080. //
  1081. case '00':
  1082. $txtTime = $txtMinutes[0];
  1083. break;
  1084. // Special case: Fixed minutes and fixed hours
  1085. //
  1086. // The default writing would be something like 'every 20 minutes past 04:00', but the more common phrasing would be: At 04:20.
  1087. //
  1088. // We will switch ForceDateExplaination on, so that even a non-specified date yields an explaination (e.g. 'every day')
  1089. //
  1090. case '11':
  1091. $txtTime = $this->natlangApply('elemMin: at_X:Y', $this->natlangPad2($this->_cronHours['elements'][0]['number1']), $this->natlangPad2($this->_cronMinutes['elements'][0]['number1']));
  1092. $switchForceDateExplaination = true;
  1093. break;
  1094. // Special case: Between :00 and :59
  1095. //
  1096. // If hours are specified, but minutes are not, then the minutes string will yield something like 'every minute'. We must the
  1097. // differentiate the hour specification because the minutes specification does not relate to all minutes past the hour, but only to
  1098. // those minutes between :00 and :59
  1099. //
  1100. // We will switch ForceDateExplaination on, so that even a non-specified date yields an explaination (e.g. 'every day')
  1101. //
  1102. case '01':
  1103. case '02':
  1104. $txtTime = $txtMinutes[$classMinutes].' '.$txtHours[$classHours]['between'];
  1105. $switchForceDateExplaination = true;
  1106. break;
  1107. // Special case: Past the hour
  1108. //
  1109. // If minutes are specified and hours are specified, then the specification of minutes is always limited to a maximum of 60 minutes
  1110. // and always applies to the minutes 'past the hour'.
  1111. //
  1112. // We will switch ForceDateExplaination on, so that even a non-specified date yields an explaination (e.g. 'every day')
  1113. //
  1114. case '12':
  1115. case '22':
  1116. case '21':
  1117. $txtTime = $txtMinutes[$classMinutes].' '.$txtHours[$classHours]['past'];
  1118. $switchForceDateExplaination = true;
  1119. break;
  1120. default:
  1121. $txtTime = $txtMinutes[$classMinutes].' '.$txtHours[$classHours];
  1122. break;
  1123. }
  1124. // Generate Date String
  1125. $txtDaysOfMonth = [];
  1126. $txtDaysOfMonth[0] = '';
  1127. $txtDaysOfMonth[1] = $this->natlangApply('elemDOM: on_the_X', $this->natlangApply('ordinal: '.$this->_cronDaysOfMonth['elements'][0]['number1']));
  1128. $txtDaysOfMonth[2] = $this->natlangApply('elemDOM: on_X', $this->natlangRange($this->_cronDaysOfMonth, [$this, 'natlangElementDayOfMonth']));
  1129. $txtMonths = [];
  1130. $txtMonths[0] = $this->natlangApply('elemMonth: of_every_month');
  1131. $txtMonths[1] = $this->natlangApply('elemMonth: during_every_X', $this->natlangApply('month: '.$this->_cronMonths['elements'][0]['number1']));
  1132. $txtMonths[2] = $this->natlangApply('elemMonth: during_X', $this->natlangRange($this->_cronMonths, [$this, 'natlangElementMonth']));
  1133. $classDaysOfMonth = $this->getClass($this->_cronDaysOfMonth);
  1134. $classMonths = $this->getClass($this->_cronMonths);
  1135. if ($classDaysOfMonth == '0') {
  1136. $switchDaysOfWeekAreExcluding = false;
  1137. }
  1138. switch ($classDaysOfMonth.$classMonths) {
  1139. // Special case: Unspecified date + Unspecified month
  1140. //
  1141. // Rule: The language for unspecified fields is omitted if a more detailed field has already been explained.
  1142. //
  1143. // The time fields always yield an explaination, at the very least in the form of 'every minute'. This rule states that if the date
  1144. // is not specified, it can be omitted because 'every minute' is already sufficiently clear.
  1145. //
  1146. // There are some time specifications that do not contain an 'every' reference, but reference a specific time of day. In those cases
  1147. // the date explaination is enforced.
  1148. //
  1149. case '00':
  1150. $txtDate = '';
  1151. break;
  1152. default:
  1153. $txtDate = ' '.$txtDaysOfMonth[$classDaysOfMonth].' '.$txtMonths[$classMonths];
  1154. break;
  1155. }
  1156. // Generate Year String
  1157. if ($this->_cronYears) {
  1158. $txtYears = [];
  1159. $txtYears[0] = '';
  1160. $txtYears[1] = ' '.$this->natlangApply('elemYear: in_X', $this->_cronYears['elements'][0]['number1']);
  1161. $txtYears[2] = ' '.$this->natlangApply('elemYear: in_X', $this->natlangRange($this->_cronYears, [$this, 'natlangElementYear']));
  1162. $classYears = $this->getClass($this->_cronYears);
  1163. $txtYear = $txtYears[$classYears];
  1164. }
  1165. // Generate DaysOfWeek String
  1166. $collectDays = 0;
  1167. foreach ($this->_cronDaysOfWeek['elements'] as $elem) {
  1168. if ($elem['hasInterval']) {
  1169. for ($x = $elem['number1']; $x <= $elem['number2']; $x += $elem['interval']) {
  1170. $collectDays |= pow(2, $x);
  1171. }
  1172. } else {
  1173. $collectDays |= pow(2, $elem['number1']);
  1174. }
  1175. }
  1176. if ($collectDays == 127) { // * all days
  1177. if (!$switchDaysOfWeekAreExcluding) {
  1178. $txtDays = ' '.$this->natlangApply('elemDOM: on_every_day');
  1179. } else {
  1180. $txtDays = '';
  1181. }
  1182. } else {
  1183. $arrDays = [];
  1184. for ($x = 0; $x <= 6; $x++) {
  1185. if ($collectDays & pow(2, $x)) {
  1186. $arrDays[] = $x;
  1187. }
  1188. }
  1189. $txtDays = '';
  1190. for ($index = 0; $index < count($arrDays); $index++) {
  1191. $txtDays .= ($index == 0 ? '' : ($index == (count($arrDays) - 1) ? ' '.$this->natlangApply($switchDaysOfWeekAreExcluding ? 'separator_or' : 'separator_and').' ' : ', ')).$this->natlangApply('day: '.$arrDays[$index].'_plural');
  1192. }
  1193. if ($switchDaysOfWeekAreExcluding) {
  1194. $txtDays = ' '.$this->natlangApply('elemDOW: but_only_on_X', $txtDays);
  1195. } else {
  1196. $txtDays = ' '.$this->natlangApply('elemDOW: on_X', $txtDays);
  1197. }
  1198. }
  1199. $txtResult = ucfirst($txtTime).$txtDate.$txtDays;
  1200. if (isset($txtYear)) {
  1201. if ($switchDaysOfWeekAreExcluding) {
  1202. $txtResult = ucfirst($txtTime).$txtDate.$txtYear.$txtDays;
  1203. } else {
  1204. $txtResult = ucfirst($txtTime).$txtDate.$txtDays.$txtYear;
  1205. }
  1206. }
  1207. return $txtResult.'.';
  1208. }
  1209. }