2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
41 class SchedulerDaemon extends Scheduler {
49 // replicated SugarBean attributes
52 var $object_name = 'SchedulerDaemon';
53 var $table_name = 'schedulers_times';
55 var $watch_name; // this object's watch name
56 var $sleepInterval = 5; // how long to sleep before checking on jobs
57 var $lifespan = 45; // 2 mins to kill off this object
58 var $sessId; // admin PHPSESSID
59 var $runAsUserName; // admin user
60 var $runAsUserPassword; // admin pword
63 var $shutdown = false;
69 function SchedulerDaemon () {
70 if(empty($this->db)) {
72 $this->db = DBManagerFactory::getInstance();
75 $GLOBALS['log']->debug('New Scheduler Instantiated.....................................');
85 * This function takes a look at the schedulers_times table and pulls the
86 * jobs to be run at this moment in time (anything not run and with a run
87 * time or earlier than right now)
88 * @return $successful Boolean flag whether a job(s) is found
90 function checkPendingJobs() {
94 $GLOBALS['log']->debug('');
95 $GLOBALS['log']->debug('----->Scheduler checking for qualified jobs to run.');
96 if(empty($this->db)) {
97 $this->db = DBManagerFactory::getInstance();
100 $fireTimeMinus = $timedate->asDb($timedate->getNow()->get('-1 minute'));
101 $fireTimePlus = $timedate->asDb($timedate->getNow()->get('+1 minute'));
103 // collapse list of schedulers where "catch_up" is 0 and status is "ready" (not "in progress, completed, etc.");
104 $q = 'UPDATE schedulers_times st
105 SET st.status = \'not run\'
106 WHERE st.execute_time < '.$this->db->convert($this->db->quoted($fireTimeMinus), 'datetime').'
107 AND st.status = \'ready\'
108 AND st.scheduler_id IN (SELECT s.id FROM schedulers s WHERE st.scheduler_id = s.id AND s.catch_up = 0)';
109 $this->db->query($q);
111 $q = 'SELECT DISTINCT st.id, st.scheduler_id, st.status, s.name, s.job FROM schedulers_times st
112 LEFT JOIN schedulers s ON st.scheduler_id = s.id WHERE st.execute_time < '.$this->db->convert($this->db->quoted($fireTimeMinus), 'datetime').
113 ' AND st.deleted=0 AND s.deleted=0 AND st.status=\'ready\' AND s.status=\'Active\' ORDER BY s.name';
114 $r = $this->db->query($q);
117 while($a = $this->db->fetchByAssoc($r)) {
119 $job = new SchedulersJob();
121 $paramJob = $a['scheduler_id'];
122 $job->fire($sugar_config['site_url'].'/index.php?entryPoint=schedulers&type=job&job_id='.$paramJob.'&record='.$a['id']);
128 $GLOBALS['log']->debug('----->Scheduler has found 0 Jobs to fire');
133 * This function takes a Scheduler object and uses its job_interval
134 * attribute to derive DB-standard datetime strings, as many as are
135 * qualified by its ranges. The times are from the time of calling the
138 * @param $focus Scheduler object
139 * @return $dateTimes array loaded with DB datetime strings derived from
140 * the job_interval attribute
141 * @return false If we the Scheduler is not in scope, return false.
143 function deriveDBDateTimes($focus) {
145 $GLOBALS['log']->debug('deriveDBDateTimes got an object of type: '.$focus->object_name);
146 /* [min][hr][dates][mon][days] */
147 $dateTimes = array();
148 $ints = explode('::', str_replace(' ','',$focus->job_interval));
154 $today = getdate($timedate->getNow()->ts);
159 $GLOBALS['log']->debug('got * day');
161 } elseif(strstr($days, '*/')) {
162 // the "*/x" format is nonsensical for this field
163 // do basically nothing.
164 $theDay = str_replace('*/','',$days);
165 $dayName[] = str_replace($focus->dayInt, $focus->dayLabel, $theDay);
166 } elseif($days != '*') { // got particular day(s)
167 if(strstr($days, ',')) {
168 $exDays = explode(',',$days);
169 foreach($exDays as $k1 => $dayGroup) {
170 if(strstr($dayGroup,'-')) {
171 $exDayGroup = explode('-', $dayGroup); // build up range and iterate through
172 for($i=$exDayGroup[0];$i<=$exDayGroup[1];$i++) {
173 $dayName[] = str_replace($focus->dayInt, $focus->dayLabel, $i);
175 } else { // individuals
176 $dayName[] = str_replace($focus->dayInt, $focus->dayLabel, $dayGroup);
179 } elseif(strstr($days, '-')) {
180 $exDayGroup = explode('-', $days); // build up range and iterate through
181 for($i=$exDayGroup[0];$i<=$exDayGroup[1];$i++) {
182 $dayName[] = str_replace($focus->dayInt, $focus->dayLabel, $i);
185 $dayName[] = str_replace($focus->dayInt, $focus->dayLabel, $days);
188 // check the day to be in scope:
189 if(!in_array($today['weekday'], $dayName)) {
197 // derive months part
199 $GLOBALS['log']->debug('got * months');
200 } elseif(strstr($mons, '*/')) {
201 $mult = str_replace('*/','',$mons);
202 $startMon = $timedate->fromTimestamp($focus->date_time_start)->month;
203 $startFrom = ($startMon % $mult);
205 for($i=$startFrom;$i<=12;$i+$mult) {
206 $compMons[] = $i+$mult;
209 // this month is not in one of the multiplier months
210 if(!in_array($today['mon'],$compMons)) {
213 } elseif($mons != '*') {
214 if(strstr($mons,',')) { // we have particular (groups) of months
215 $exMons = explode(',',$mons);
216 foreach($exMons as $k1 => $monGroup) {
217 if(strstr($monGroup, '-')) { // we have a range of months
218 $exMonGroup = explode('-',$monGroup);
219 for($i=$exMonGroup[0];$i<=$exMonGroup[1];$i++) {
223 $monName[] = $monGroup;
226 } elseif(strstr($mons, '-')) {
227 $exMonGroup = explode('-', $mons);
228 for($i=$exMonGroup[0];$i<=$exMonGroup[1];$i++) {
231 } else { // one particular month
235 // check that particular months are in scope
236 if(!in_array($today['mon'], $monName)) {
243 $GLOBALS['log']->debug('got * dates');
244 } elseif(strstr($dates, '*/')) {
245 $mult = str_replace('*/','',$dates);
246 $startDate = $timedate->fromTimestamp($focus->date_time_start)->day;
247 $startFrom = ($startDate % $mult);
249 for($i=$startFrom; $i<=31; $i+$mult) {
250 $dateName[] = str_pad(($i+$mult),2,'0',STR_PAD_LEFT);
254 if(!in_array($today['mday'], $dateName)) {
257 } elseif($dates != '*') {
258 if(strstr($dates, ',')) {
259 $exDates = explode(',', $dates);
260 foreach($exDates as $k1 => $dateGroup) {
261 if(strstr($dateGroup, '-')) {
262 $exDateGroup = explode('-', $dateGroup);
263 for($i=$exDateGroup[0];$i<=$exDateGroup[1];$i++) {
267 $dateName[] = $dateGroup;
270 } elseif(strstr($dates, '-')) {
271 $exDateGroup = explode('-', $dates);
272 for($i=$exDateGroup[0];$i<=$exDateGroup[1];$i++) {
276 $dateName[] = $dates;
279 // check that dates are in scope
280 if(!in_array($today['mday'], $dateName)) {
286 //$startHour = date('G', strtotime($focus->date_time_start));
287 //$currentHour = ($startHour < 1) ? 23 : date('G', strtotime($focus->date_time_start));
288 $currentHour = $timedate->getNow()->hour;
290 $GLOBALS['log']->debug('got * hours');
291 for($i=0;$i<=24; $i++) {
292 if($currentHour + $i > 23) {
293 $hrName[] = $currentHour + $i - 24;
295 $hrName[] = $currentHour + $i;
298 } elseif(strstr($hrs, '*/')) {
299 $mult = str_replace('*/','',$hrs);
300 for($i=0; $i<24; $i) { // weird, i know
301 if($currentHour + $i > 23) {
302 $hrName[] = $currentHour + $i - 24;
304 $hrName[] = $currentHour + $i;
308 } elseif($hrs != '*') {
309 if(strstr($hrs, ',')) {
310 $exHrs = explode(',',$hrs);
311 foreach($exHrs as $k1 => $hrGroup) {
312 if(strstr($hrGroup, '-')) {
313 $exHrGroup = explode('-', $hrGroup);
314 for($i=$exHrGroup[0];$i<=$exHrGroup[1];$i++) {
318 $hrName[] = $hrGroup;
321 } elseif(strstr($hrs, '-')) {
322 $exHrs = explode('-', $hrs);
323 for($i=$exHrs[0];$i<=$exHrs[1];$i++) {
331 $currentMin = $timedate->getNow()->minute;
332 if(substr($currentMin, 0, 1) == '0') {
333 $currentMin = substr($currentMin, 1, 1);
336 $GLOBALS['log']->debug('got * mins');
337 for($i=0; $i<60; $i++) {
338 if(($currentMin + $i) > 59) {
339 $minName[] = ($i + $currentMin - 60);
341 $minName[] = ($i+$currentMin);
344 } elseif(strstr($mins,'*/')) {
345 $mult = str_replace('*/','',$mins);
346 $startMin = $timedate->fromTimestmp($focus->date_time_start)->minute;
347 $startFrom = ($startMin % $mult);
349 for($i=$startFrom; $i<=59; $i+$mult) {
350 if(($currentMin + $i) > 59) {
351 $minName[] = ($i + $currentMin - 60);
353 $minName[] = ($i+$currentMin);
357 } elseif($mins != '*') {
358 if(strstr($mins, ',')) {
359 $exMins = explode(',',$mins);
360 foreach($exMins as $k1 => $minGroup) {
361 if(strstr($minGroup, '-')) {
362 $exMinGroup = explode('-', $minGroup);
363 for($i=$exMinGroup[0]; $i<=$exMinGroup[1]; $i++) {
367 $minName[] = $minGroup;
370 } elseif(strstr($mins, '-')) {
371 $exMinGroup = explode('-', $mins);
372 for($i=$exMinGroup[0]; $i<=$exMinGroup[1]; $i++) {
380 // prep some boundaries - these are not in GMT b/c gmt is a 24hour period, possibly bridging 2 local days
381 if(empty($focus->time_from) && empty($focus->time_to) ) {
383 $timeToTs = strtotime('+1 day');
385 $timeFromTs = strtotime($focus->time_from); // these are now GMT (timestamps are all GMT)
386 $timeToTs = strtotime($focus->time_to); // see above
387 if($timeFromTs > $timeToTs) { // we've crossed into the next day
388 $timeToTs = strtotime('+1 day '. $focus->time_to); // also in GMT
393 if(empty($focus->last_run)) {
396 $lastRunTs = strtotime($focus->last_run);
400 // now smush the arrays together =)
401 $validJobTime = array();
403 $dts = explode(' ',$focus->date_time_start); // split up datetime field into date & time
405 $dts2 = $timedate->to_db_date_time($dts[0],$dts[1]); // get date/time into DB times (GMT)
406 $dateTimeStart = $dts2[0]." ".$dts2[1];
407 $timeStartTs = strtotime($dateTimeStart);
408 if(!empty($focus->date_time_end) && !$focus->date_time_end == '2021-01-01 07:59:00') { // do the same for date_time_end if not empty
409 $dte = explode(' ', $focus->date_time_end);
410 $dte2 = $timedate->to_db_date_time($dte[0],$dte[1]);
411 $dateTimeEnd = $dte2[0]." ".$dte2[1];
413 $dateTimeEnd = $timedate->getNow()->get('+1 day')->asDb();
414 // $dateTimeEnd = '2020-12-31 23:59:59'; // if empty, set it to something ridiculous
416 $timeEndTs = strtotime($dateTimeEnd); // GMT end timestamp if necessary
418 /*_pp('hours:'); _pp($hrName);_pp('mins:'); _pp($minName);*/
419 $nowTs = $timedate->getNow()->ts;
421 // _pp('currentHour: '. $currentHour);
422 // _pp('timeStartTs: '.date('r',$timeStartTs));
423 // _pp('timeFromTs: '.date('r',$timeFromTs));
424 // _pp('timeEndTs: '.date('r',$timeEndTs));
425 // _pp('timeToTs: '.date('r',$timeToTs));
426 // _pp('mktime: '.date('r',mktime()));
427 // _pp('timeLastRun: '.date('r',$lastRunTs));
434 foreach($hrName as $kHr=>$hr) {
436 foreach($minName as $kMin=>$min) {
437 if($hr < $currentHour || $hourSeen == 25) {
438 $theDate = $timedate->asDbDate($timedate->getNow()->get('+1 day'));
440 $theDate = $timedate->nowDbDate();
442 $tsGmt = strtotime($theDate.' '.str_pad($hr,2,'0',STR_PAD_LEFT).":".str_pad($min,2,'0',STR_PAD_LEFT).":00"); // this is LOCAL
443 // _pp(date('Y-m-d H:i:s',$tsGmt));
445 if( $tsGmt >= $timeStartTs ) { // start is greater than the date specified by admin
446 if( $tsGmt >= $timeFromTs ) { // start is greater than the time_to spec'd by admin
447 if( $tsGmt <= $timeEndTs ) { // this is taken care of by the initial query - start is less than the date spec'd by admin
448 if( $tsGmt <= $timeToTs ) { // start is less than the time_to
449 if( $tsGmt >= $nowTs ) { // we only want to add jobs that are in the future
450 if( $tsGmt > $lastRunTs ) { //TODO figure if this is better than the above check
451 $validJobTime[] = $timedate->fromTimestamp($tsGmt)->asDb(); //_pp("Job Qualified for: ".date('Y-m-d H:i:s', $tsGmt));
453 //_pp('Job Time is NOT greater than Last Run');
456 //_pp('Job Time is NOT larger than NOW'); _pp(date('Y-m-d H:i:s', $nowTs));
459 //_pp('Job Time is NOT smaller that TimeTO: '.$tsGmt .'<='. $timeToTs);
462 //_pp('Job Time is NOT smaller that DateTimeEnd: '.date('Y-m-d H:i:s',$tsGmt) .'<='. $dateTimeEnd); _pp( $tsGmt .'<='. $timeEndTs );
465 //_pp('Job Time is NOT bigger that TimeFrom: '.$tsGmt .'>='. $timeFromTs);
468 //_pp('Job Time is NOT Bigger than DateTimeStart: '.date('Y-m-d H:i',$tsGmt) .'>='. $dateTimeStart);
473 // _ppd($validJobTime);
474 return $validJobTime;
479 * This function takes an array of jobs build up by retrieveSchedulers and
480 * puts them into the schedulers_times table
482 function insertSchedules() {
483 $GLOBALS['log']->info('----->Scheduler retrieving scheduled items and adding them to Job queue.');
484 $jobsArr = $this->retrieveSchedulers();
485 if(is_array($jobsArr['ids']) && !empty($jobsArr['ids']) && is_array($jobsArr['times']) && !empty($jobsArr['times'])) {
486 foreach($jobsArr['ids'] as $k => $ids) {
487 foreach($jobsArr['times'][$k] as $j => $time) {
488 $guid = create_guid();
489 $q = "INSERT INTO schedulers_times
490 (id, deleted, date_entered, date_modified, scheduler_id, execute_time, status)
494 ".db_convert("'".TimeDate::getInstance()->nowDb()."'", 'datetime').",
495 ".db_convert("'".TimeDate::getInstance()->nowDb()."'", 'datetime').",
496 '".$jobsArr['ids'][$k]."',
497 ".db_convert("'".$time."'", 'datetime').",
500 $this->db->query($q);
501 $GLOBALS['log']->info('Query: '.$q);
508 * This function drops all rows in the schedulers_times table.
510 function dropSchedules($truncate=false) {
511 global $sugar_config;
513 if(empty($this->db)) {
514 $this->db = DBManagerFactory::getInstance();
518 $query = $this->db->truncateTableSQL('schedulers_times');
519 $this->db->query($query);
520 $GLOBALS['log']->debug('----->Scheduler TRUNCATED ALL Jobs: '.$query);
522 $query = 'UPDATE schedulers_times SET deleted = 1';
523 $this->db->query($query);
524 $GLOBALS['log']->debug('----->Scheduler soft deleting all Jobs: '.$query);
526 //TODO make sure this will fail gracefully
530 * This function retrieves valid jobs, parses the cron format, then returns
531 * an array of [JOB_ID][EXEC_TIME][JOB]
533 * @return $executeJobs multi-dimensional array
534 * [job_id][execute_time]
536 function retrieveSchedulers() {
537 $GLOBALS['log']->info('Gathering Schedulers');
538 $executeJobs = array();
539 $query = "SELECT id " .
542 "AND status = 'Active' " .
543 "AND date_time_start < ".db_convert("'".TimeDate::getInstance()->nowDb()."'",'datetime')." " .
544 "AND (date_time_end > ".db_convert("'".TimeDate::getInstance()->nowDb()."'",'datetime')." OR date_time_end IS NULL)";
546 $result = $this->db->query($query);
548 $executeTimes = array();
549 $executeIds = array();
550 $executeJobTimes = array();
551 while(($arr = $this->db->fetchByAssoc($result)) != null) {
552 $focus = new Scheduler();
553 $focus->retrieve($arr['id']);
554 $executeTimes[$rows] = $this->deriveDBDateTimes($focus);
555 if(count($executeTimes) > 0) {
556 foreach($executeTimes as $k => $time) {
557 $executeIds[$rows] = $focus->id;
558 $executeJobTimes[$rows] = $time;
563 $executeJobs['ids'] = $executeIds;
564 $executeJobs['times'] = $executeJobTimes;
568 } // end SchedulerDaemon class desc.