]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Schedulers/Scheduler.php
Release 6.5.0
[Github/sugarcrm.git] / modules / Schedulers / Scheduler.php
1 <?php
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-2012 SugarCRM Inc.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 require_once 'modules/SchedulersJobs/SchedulersJob.php';
39
40 class Scheduler extends SugarBean {
41         // table columns
42         var $id;
43         var $deleted;
44         var $date_entered;
45         var $date_modified;
46         var $modified_user_id;
47         var $created_by;
48         var $created_by_name;
49         var $modified_by_name;
50         var $name;
51         var $job;
52         var $date_time_start;
53         var $date_time_end;
54         var $job_interval;
55         var $time_from;
56         var $time_to;
57         var $last_run;
58         var $status;
59         var $catch_up;
60         // object attributes
61         var $user;
62         var $intervalParsed;
63         var $intervalHumanReadable;
64         var $metricsVar;
65         var $metricsVal;
66         var $dayInt;
67         var $dayLabel;
68         var $monthsInt;
69         var $monthsLabel;
70         var $suffixArray;
71         var $datesArray;
72         var $scheduledJobs;
73         var $timeOutMins = 60;
74         // standard SugarBean attrs
75         var $table_name                         = "schedulers";
76         var $object_name                        = "Scheduler";
77         var $module_dir                         = "Schedulers";
78         var $new_schema                         = true;
79         var $process_save_dates         = true;
80         var $order_by;
81
82         public static $job_strings;
83
84     public function __construct($init=true)
85     {
86         parent::SugarBean();
87         $job = new SchedulersJob();
88         $this->job_queue_table = $job->table_name;
89     }
90
91     protected function getUser()
92     {
93         if(empty($this->user)) {
94             $this->initUser();
95         }
96         return $this->user;
97     }
98
99     protected function initUser()
100     {
101         $user = new User();
102         //check is default admin exists
103         $adminId = $this->db->getOne(
104             'SELECT id FROM users WHERE id='.$this->db->quoted('1').' AND is_admin=1 AND deleted=0 AND status='.$this->db->quoted('Active'),
105             true,
106             'Error retrieving Admin account info'
107         );
108         if (false === $adminId) {//retrive another admin
109             $adminId = $this->db->getOne(
110                 'SELECT id FROM users WHERE is_admin=1 AND deleted=0 AND status='.$this->db->quoted('Active'),
111                 true,
112                 'Error retrieving Admin account info'
113             );
114             if ($adminId) {
115                 $user->retrieve($adminId);
116             } else {
117                 $GLOBALS['log']->fatal('No Admin account found!');
118                 return false;
119             }
120
121         } else {
122             $user->retrieve('1'); // Scheduler jobs run as default Admin
123         }
124         $this->user = $user;
125     }
126
127
128         ///////////////////////////////////////////////////////////////////////////
129         ////    SCHEDULER HELPER FUNCTIONS
130
131         /**
132          * calculates if a job is qualified to run
133          */
134         public function fireQualified()
135         {
136                 if(empty($this->id)) { // execute only if we have an instance
137                         $GLOBALS['log']->fatal('Scheduler called fireQualified() in a non-instance');
138                         return false;
139                 }
140
141                 $now = TimeDate::getInstance()->getNow();
142                 $now = $now->setTime($now->hour, $now->min, "00")->asDb();
143                 $validTimes = $this->deriveDBDateTimes($this);
144
145                 if(is_array($validTimes) && in_array($now, $validTimes)) {
146                         $GLOBALS['log']->debug('----->Scheduler found valid job ('.$this->name.') for time GMT('.$now.')');
147                         return true;
148                 } else {
149                         $GLOBALS['log']->debug('----->Scheduler did NOT find valid job ('.$this->name.') for time GMT('.$now.')');
150                         return false;
151                 }
152         }
153
154         /**
155          * Create a job from this scheduler
156          * @return SchedulersJob
157          */
158         public function createJob()
159         {
160             $job = new SchedulersJob();
161             $job->scheduler_id = $this->id;
162         $job->name = $this->name;
163         $job->execute_time = $GLOBALS['timedate']->nowDb();
164         $job->assigned_user_id = $this->getUser()->id;
165         $job->target = $this->job;
166         return $job;
167         }
168
169         /**
170          * Checks if any jobs qualify to run at this moment
171          * @param SugarJobQueue $queue
172          */
173         public function checkPendingJobs($queue)
174         {
175                 $allSchedulers = $this->get_full_list('', "schedulers.status='Active' AND NOT EXISTS(SELECT id FROM {$this->job_queue_table} WHERE scheduler_id=schedulers.id AND status!='".SchedulersJob::JOB_STATUS_DONE."')");
176
177                 $GLOBALS['log']->info('-----> Scheduler found [ '.count($allSchedulers).' ] ACTIVE jobs');
178
179                 if(!empty($allSchedulers)) {
180                         foreach($allSchedulers as $focus) {
181                                 if($focus->fireQualified()) {
182                                     $job = $focus->createJob();
183                                     $queue->submitJob($job, $this->getUser());
184                                 }
185                         }
186                 } else {
187                         $GLOBALS['log']->debug('----->No Schedulers found');
188                 }
189         }
190
191         /**
192          * This function takes a Scheduler object and uses its job_interval
193          * attribute to derive DB-standard datetime strings, as many as are
194          * qualified by its ranges.  The times are from the time of calling the
195          * script.
196          *
197          * @param       $focus          Scheduler object
198          * @return      $dateTimes      array loaded with DB datetime strings derived from
199          *                                              the      job_interval attribute
200          * @return      false           If we the Scheduler is not in scope, return false.
201          */
202         function deriveDBDateTimes($focus)
203         {
204         global $timedate;
205                 $GLOBALS['log']->debug('----->Schedulers->deriveDBDateTimes() got an object of type: '.$focus->object_name);
206                 /* [min][hr][dates][mon][days] */
207                 $dateTimes = array();
208                 $ints   = explode('::', str_replace(' ','',$focus->job_interval));
209                 $days   = $ints[4];
210                 $mons   = $ints[3];
211                 $dates  = $ints[2];
212                 $hrs    = $ints[1];
213                 $mins   = $ints[0];
214                 $today  = getdate($timedate->getNow()->ts);
215
216                 // derive day part
217                 if($days == '*') {
218                         $GLOBALS['log']->debug('----->got * day');
219
220                 } elseif(strstr($days, '*/')) {
221                         // the "*/x" format is nonsensical for this field
222                         // do basically nothing.
223                         $theDay = str_replace('*/','',$days);
224                         $dayName[] = $theDay;
225                 } elseif($days != '*') { // got particular day(s)
226                         if(strstr($days, ',')) {
227                                 $exDays = explode(',',$days);
228                                 foreach($exDays as $k1 => $dayGroup) {
229                                         if(strstr($dayGroup,'-')) {
230                                                 $exDayGroup = explode('-', $dayGroup); // build up range and iterate through
231                                                 for($i=$exDayGroup[0];$i<=$exDayGroup[1];$i++) {
232                                                         $dayName[] = $i;
233                                                 }
234                                         } else { // individuals
235                                                 $dayName[] = $dayGroup;
236                                         }
237                                 }
238                         } elseif(strstr($days, '-')) {
239                                 $exDayGroup = explode('-', $days); // build up range and iterate through
240                                 for($i=$exDayGroup[0];$i<=$exDayGroup[1];$i++) {
241                                         $dayName[] = $i;
242                                 }
243                         } else {
244                                 $dayName[] = $days;
245                         }
246
247                         // check the day to be in scope:
248                         if(!in_array($today['wday'], $dayName)) {
249                                 return false;
250                         }
251                 } else {
252                         return false;
253                 }
254
255
256                 // derive months part
257                 if($mons == '*') {
258                         $GLOBALS['log']->debug('----->got * months');
259                 } elseif(strstr($mons, '*/')) {
260                         $mult = str_replace('*/','',$mons);
261                         $startMon = $timedate->fromDb(date_time_start)->month;
262                         $startFrom = ($startMon % $mult);
263
264                         for($i=$startFrom;$i<=12;$i+$mult) {
265                                 $compMons[] = $i+$mult;
266                                 $i += $mult;
267                         }
268                         // this month is not in one of the multiplier months
269                         if(!in_array($today['mon'],$compMons)) {
270                                 return false;
271                         }
272                 } elseif($mons != '*') {
273                         if(strstr($mons,',')) { // we have particular (groups) of months
274                                 $exMons = explode(',',$mons);
275                                 foreach($exMons as $k1 => $monGroup) {
276                                         if(strstr($monGroup, '-')) { // we have a range of months
277                                                 $exMonGroup = explode('-',$monGroup);
278                                                 for($i=$exMonGroup[0];$i<=$exMonGroup[1];$i++) {
279                                                         $monName[] = $i;
280                                                 }
281                                         } else {
282                                                 $monName[] = $monGroup;
283                                         }
284                                 }
285                         } elseif(strstr($mons, '-')) {
286                                 $exMonGroup = explode('-', $mons);
287                                 for($i=$exMonGroup[0];$i<=$exMonGroup[1];$i++) {
288                                         $monName[] = $i;
289                                 }
290                         } else { // one particular month
291                                 $monName[] = $mons;
292                         }
293
294                         // check that particular months are in scope
295                         if(!in_array($today['mon'], $monName)) {
296                                 return false;
297                         }
298                 }
299
300                 // derive dates part
301                 if($dates == '*') {
302                         $GLOBALS['log']->debug('----->got * dates');
303                 } elseif(strstr($dates, '*/')) {
304                         $mult = str_replace('*/','',$dates);
305                         $startDate = $timedate->fromDb($focus->date_time_start)->day;
306                         $startFrom = ($startDate % $mult);
307
308                         for($i=$startFrom; $i<=31; $i+$mult) {
309                                 $dateName[] = str_pad(($i+$mult),2,'0',STR_PAD_LEFT);
310                                 $i += $mult;
311                         }
312
313                         if(!in_array($today['mday'], $dateName)) {
314                                 return false;
315                         }
316                 } elseif($dates != '*') {
317                         if(strstr($dates, ',')) {
318                                 $exDates = explode(',', $dates);
319                                 foreach($exDates as $k1 => $dateGroup) {
320                                         if(strstr($dateGroup, '-')) {
321                                                 $exDateGroup = explode('-', $dateGroup);
322                                                 for($i=$exDateGroup[0];$i<=$exDateGroup[1];$i++) {
323                                                         $dateName[] = $i;
324                                                 }
325                                         } else {
326                                                 $dateName[] = $dateGroup;
327                                         }
328                                 }
329                         } elseif(strstr($dates, '-')) {
330                                 $exDateGroup = explode('-', $dates);
331                                 for($i=$exDateGroup[0];$i<=$exDateGroup[1];$i++) {
332                                         $dateName[] = $i;
333                                 }
334                         } else {
335                                 $dateName[] = $dates;
336                         }
337
338                         // check that dates are in scope
339                         if(!in_array($today['mday'], $dateName)) {
340                                 return false;
341                         }
342                 }
343
344                 // derive hours part
345                 //$currentHour = gmdate('G');
346                 //$currentHour = date('G', strtotime('00:00'));
347                 if($hrs == '*') {
348                         $GLOBALS['log']->debug('----->got * hours');
349                         for($i=0;$i<24; $i++) {
350                                 $hrName[]=$i;
351                         }
352                 } elseif(strstr($hrs, '*/')) {
353                         $mult = str_replace('*/','',$hrs);
354                         for($i=0; $i<24; $i) { // weird, i know
355                                 $hrName[]=$i;
356                                 $i += $mult;
357                         }
358                 } elseif($hrs != '*') {
359                         if(strstr($hrs, ',')) {
360                                 $exHrs = explode(',',$hrs);
361                                 foreach($exHrs as $k1 => $hrGroup) {
362                                         if(strstr($hrGroup, '-')) {
363                                                 $exHrGroup = explode('-', $hrGroup);
364                                                 for($i=$exHrGroup[0];$i<=$exHrGroup[1];$i++) {
365                                                         $hrName[] = $i;
366                                                 }
367                                         } else {
368                                                 $hrName[] = $hrGroup;
369                                         }
370                                 }
371                         } elseif(strstr($hrs, '-')) {
372                                 $exHrs = explode('-', $hrs);
373                                 for($i=$exHrs[0];$i<=$exHrs[1];$i++) {
374                                         $hrName[] = $i;
375                                 }
376                         } else {
377                                 $hrName[] = $hrs;
378                         }
379                 }
380                 //_pp($hrName);
381                 // derive minutes
382                 //$currentMin = date('i');
383                 $currentMin = $timedate->getNow()->minute;
384                 if(substr($currentMin, 0, 1) == '0') {
385                         $currentMin = substr($currentMin, 1, 1);
386                 }
387                 if($mins == '*') {
388                         $GLOBALS['log']->debug('----->got * mins');
389                         for($i=0; $i<60; $i++) {
390                                 if(($currentMin + $i) > 59) {
391                                         $minName[] = ($i + $currentMin - 60);
392                                 } else {
393                                         $minName[] = ($i+$currentMin);
394                                 }
395                         }
396                 } elseif(strstr($mins,'*/')) {
397                         $mult = str_replace('*/','',$mins);
398                         $startMin = $timedate->fromDb($focus->date_time_start)->minute;
399                         $startFrom = ($startMin % $mult);
400                         for($i=$startFrom; $i<=59; $i) {
401                                 if(($currentMin + $i) > 59) {
402                                         $minName[] = ($i + $currentMin - 60);
403                                 } else {
404                                         $minName[] = ($i+$currentMin);
405                                 }
406                                 $i += $mult;
407                         }
408
409                 } elseif($mins != '*') {
410                         if(strstr($mins, ',')) {
411                                 $exMins = explode(',',$mins);
412                                 foreach($exMins as $k1 => $minGroup) {
413                                         if(strstr($minGroup, '-')) {
414                                                 $exMinGroup = explode('-', $minGroup);
415                                                 for($i=$exMinGroup[0]; $i<=$exMinGroup[1]; $i++) {
416                                                         $minName[] = $i;
417                                                 }
418                                         } else {
419                                                 $minName[] = $minGroup;
420                                         }
421                                 }
422                         } elseif(strstr($mins, '-')) {
423                                 $exMinGroup = explode('-', $mins);
424                                 for($i=$exMinGroup[0]; $i<=$exMinGroup[1]; $i++) {
425                                         $minName[] = $i;
426                                 }
427                         } else {
428                                 $minName[] = $mins;
429                         }
430                 }
431                 //_pp($minName);
432                 // prep some boundaries - these are not in GMT b/c gmt is a 24hour period, possibly bridging 2 local days
433                 if(empty($focus->time_from)  && empty($focus->time_to) ) {
434                         $timeFromTs = 0;
435                         $timeToTs = $timedate->getNow(true)->get('+1 day')->ts;
436                 } else {
437                     $tfrom = $timedate->fromDbType($focus->time_from, 'time');
438                         $timeFromTs = $timedate->getNow(true)->setTime($tfrom->hour, $tfrom->min)->ts;
439                     $tto = $timedate->fromDbType($focus->time_to, 'time');
440                         $timeToTs = $timedate->getNow(true)->setTime($tto->hour, $tto->min)->ts;
441                 }
442                 $timeToTs++;
443
444                 if(empty($focus->last_run)) {
445                         $lastRunTs = 0;
446                 } else {
447                         $lastRunTs = $timedate->fromDb($focus->last_run)->ts;
448                 }
449
450
451                 /**
452                  * initialize return array
453                  */
454                 $validJobTime = array();
455
456                 global $timedate;
457                 $timeStartTs = $timedate->fromDb($focus->date_time_start)->ts;
458                 if(!empty($focus->date_time_end)) { // do the same for date_time_end if not empty
459                         $timeEndTs = $timedate->fromDb($focus->date_time_end)->ts;
460                 } else {
461                         $timeEndTs = $timedate->getNow(true)->get('+1 day')->ts;
462 //                      $dateTimeEnd = '2020-12-31 23:59:59'; // if empty, set it to something ridiculous
463                 }
464                 $timeEndTs++;
465                 /*_pp('hours:'); _pp($hrName);_pp('mins:'); _pp($minName);*/
466                 $dateobj = $timedate->getNow();
467                 $nowTs = $dateobj->ts;
468         $GLOBALS['log']->debug(sprintf("Constraints: start: %s from: %s end: %s to: %s now: %s",
469             gmdate('Y-m-d H:i:s', $timeStartTs), gmdate('Y-m-d H:i:s', $timeFromTs), gmdate('Y-m-d H:i:s', $timeEndTs),
470             gmdate('Y-m-d H:i:s', $timeToTs), $timedate->nowDb()
471             ));
472 //              _pp('currentHour: '. $currentHour);
473 //              _pp('timeStartTs: '.date('r',$timeStartTs));
474 //              _pp('timeFromTs: '.date('r',$timeFromTs));
475 //              _pp('timeEndTs: '.date('r',$timeEndTs));
476 //              _pp('timeToTs: '.date('r',$timeToTs));
477 //              _pp('mktime: '.date('r',mktime()));
478 //              _pp('timeLastRun: '.date('r',$lastRunTs));
479 //
480 //              _pp('hours: ');
481 //              _pp($hrName);
482 //              _pp('mins: ');
483 //              _ppd($minName);
484                 foreach($hrName as $kHr=>$hr) {
485                         foreach($minName as $kMin=>$min) {
486                             $timedate->tzUser($dateobj);
487                         $dateobj->setTime($hr, $min, 0);
488                         $tsGmt = $dateobj->ts;
489
490                                 if( $tsGmt >= $timeStartTs ) { // start is greater than the date specified by admin
491                                         if( $tsGmt >= $timeFromTs ) { // start is greater than the time_to spec'd by admin
492                         if($tsGmt > $lastRunTs) { // start from last run, last run should not be included
493                             if( $tsGmt <= $timeEndTs ) { // this is taken care of by the initial query - start is less than the date spec'd by admin
494                                 if( $tsGmt <= $timeToTs ) { // start is less than the time_to
495                                     $validJobTime[] = $dateobj->asDb();
496                                 } else {
497                                     //_pp('Job Time is NOT smaller that TimeTO: '.$tsGmt .'<='. $timeToTs);
498                                 }
499                             } else {
500                                 //_pp('Job Time is NOT smaller that DateTimeEnd: '.date('Y-m-d H:i:s',$tsGmt) .'<='. $dateTimeEnd); //_pp( $tsGmt .'<='. $timeEndTs );
501                             }
502                         }
503                                         } else {
504                                                 //_pp('Job Time is NOT bigger that TimeFrom: '.$tsGmt .'>='. $timeFromTs);
505                                         }
506                                 } else {
507                                         //_pp('Job Time is NOT Bigger than DateTimeStart: '.date('Y-m-d H:i',$tsGmt) .'>='. $dateTimeStart);
508                                 }
509                         }
510                 }
511                 //_ppd($validJobTime);
512                 // need ascending order to compare oldest time to last_run
513                 sort($validJobTime);
514                 /**
515                  * If "Execute If Missed bit is set
516                  */
517         $now = TimeDate::getInstance()->getNow();
518                 $now = $now->setTime($now->hour, $now->min, "00")->asDb();
519
520                 if($focus->catch_up == 1) {
521                         if($focus->last_run == null) {
522                                 // always "catch-up"
523                                 $validJobTime[] = $now;
524                         } else {
525                                 // determine what the interval in min/hours is
526                                 // see if last_run is in it
527                                 // if not, add NOW
528                 if(!empty($validJobTime) && ($focus->last_run < $validJobTime[0]) && ($now > $validJobTime[0])) {
529                                 // cn: empty() bug 5914;
530                                 // if(!empty) should be checked, becasue if a scheduler is defined to run every day 4pm, then after 4pm, and it runs as 4pm,
531                                 // the $validJobTime will be empty, and it should not catch up.
532                                 // If $focus->last_run is the the day before yesterday,  it should run yesterday and tomorrow,
533                                 // but it hadn't run yesterday, then it should catch up today.
534                                 // But today is already filtered out when doing date check before. The catch up will not work on this occasion.
535                                 // If the scheduler runs at least one time on each day, I think this bug can be avoided.
536                                         $validJobTime[] = $now;
537                                 }
538                         }
539                 }
540                 return $validJobTime;
541         }
542
543         function handleIntervalType($type, $value, $mins, $hours) {
544                 global $mod_strings;
545                 /* [0]:min [1]:hour [2]:day of month [3]:month [4]:day of week */
546                 $days = array ( 1 => $mod_strings['LBL_MON'],
547                                                 2 => $mod_strings['LBL_TUE'],
548                                                 3 => $mod_strings['LBL_WED'],
549                                                 4 => $mod_strings['LBL_THU'],
550                                                 5 => $mod_strings['LBL_FRI'],
551                                                 6 => $mod_strings['LBL_SAT'],
552                                                 0 => $mod_strings['LBL_SUN'],
553                                                 '*' => $mod_strings['LBL_ALL']);
554                 switch($type) {
555                         case 0: // minutes
556                                 if($value == '0') {
557                                         //return;
558                                         return trim($mod_strings['LBL_ON_THE']).$mod_strings['LBL_HOUR_SING'];
559                                 } elseif(!preg_match('/[^0-9]/', $hours) && !preg_match('/[^0-9]/', $value)) {
560                                         return;
561
562                                 } elseif(preg_match('/\*\//', $value)) {
563                                         $value = str_replace('*/','',$value);
564                                         return $value.$mod_strings['LBL_MINUTES'];
565                                 } elseif(!preg_match('[^0-9]', $value)) {
566                                         return $mod_strings['LBL_ON_THE'].$value.$mod_strings['LBL_MIN_MARK'];
567                                 } else {
568                                         return $value;
569                                 }
570                         case 1: // hours
571                                 global $current_user;
572                                 if(preg_match('/\*\//', $value)) { // every [SOME INTERVAL] hours
573                                         $value = str_replace('*/','',$value);
574                                         return $value.$mod_strings['LBL_HOUR'];
575                                 } elseif(preg_match('/[^0-9]/', $mins)) { // got a range, or multiple of mins, so we return an 'Hours' label
576                                         return $value;
577                                 } else {        // got a "minutes" setting, so it will be at some o'clock.
578                                         $datef = $current_user->getUserDateTimePreferences();
579                                         return date($datef['time'], strtotime($value.':'.str_pad($mins, 2, '0', STR_PAD_LEFT)));
580                                 }
581                         case 2: // day of month
582                                 if(preg_match('/\*/', $value)) {
583                                         return $value;
584                                 } else {
585                                         return date('jS', strtotime('December '.$value));
586                                 }
587
588                         case 3: // months
589                                 return date('F', strtotime('2005-'.$value.'-01'));
590                         case 4: // days of week
591                                 return $days[$value];
592                         default:
593                                 return 'bad'; // no condition to touch this branch
594                 }
595         }
596
597         function setIntervalHumanReadable() {
598                 global $current_user;
599                 global $mod_strings;
600
601                 /* [0]:min [1]:hour [2]:day of month [3]:month [4]:day of week */
602                 $ints = $this->intervalParsed;
603                 $intVal = array('-', ',');
604                 $intSub = array($mod_strings['LBL_RANGE'], $mod_strings['LBL_AND']);
605                 $intInt = array(0 => $mod_strings['LBL_MINS'], 1 => $mod_strings['LBL_HOUR']);
606                 $tempInt = '';
607                 $iteration = '';
608
609                 foreach($ints['raw'] as $key => $interval) {
610                         if($tempInt != $iteration) {
611                                 $tempInt .= '; ';
612                         }
613                         $iteration = $tempInt;
614
615                         if($interval != '*' && $interval != '*/1') {
616                                 if(false !== strpos($interval, ',')) {
617                                         $exIndiv = explode(',', $interval);
618                                         foreach($exIndiv as $val) {
619                                                 if(false !== strpos($val, '-')) {
620                                                         $exRange = explode('-', $val);
621                                                         foreach($exRange as $valRange) {
622                                                                 if($tempInt != '') {
623                                                                         $tempInt .= $mod_strings['LBL_AND'];
624                                                                 }
625                                                                 $tempInt .= $this->handleIntervalType($key, $valRange, $ints['raw'][0], $ints['raw'][1]);
626                                                         }
627                                                 } elseif($tempInt != $iteration) {
628                                                         $tempInt .= $mod_strings['LBL_AND'];
629                                                 }
630                                                 $tempInt .= $this->handleIntervalType($key, $val, $ints['raw'][0], $ints['raw'][1]);
631                                         }
632                                 } elseif(false !== strpos($interval, '-')) {
633                                         $exRange = explode('-', $interval);
634                                         $tempInt .= $mod_strings['LBL_FROM'];
635                                         $check = $tempInt;
636
637                                         foreach($exRange as $val) {
638                                                 if($tempInt == $check) {
639                                                         $tempInt .= $this->handleIntervalType($key, $val, $ints['raw'][0], $ints['raw'][1]);
640                                                         $tempInt .= $mod_strings['LBL_RANGE'];
641
642                                                 } else {
643                                                         $tempInt .= $this->handleIntervalType($key, $val, $ints['raw'][0], $ints['raw'][1]);
644                                                 }
645                                         }
646
647                                 } elseif(false !== strpos($interval, '*/')) {
648                                         $tempInt .= $mod_strings['LBL_EVERY'];
649                                         $tempInt .= $this->handleIntervalType($key, $interval, $ints['raw'][0], $ints['raw'][1]);
650                                 } else {
651                                         $tempInt .= $this->handleIntervalType($key, $interval, $ints['raw'][0], $ints['raw'][1]);
652                                 }
653                         }
654                 } // end foreach()
655
656                 if($tempInt == '') {
657                         $this->intervalHumanReadable = $mod_strings['LBL_OFTEN'];
658                 } else {
659                         $tempInt = trim($tempInt);
660                         if(';' == substr($tempInt, (strlen($tempInt)-1), strlen($tempInt))) {
661                                 $tempInt = substr($tempInt, 0, (strlen($tempInt)-1));
662                         }
663                         $this->intervalHumanReadable = $tempInt;
664                 }
665         }
666
667
668         /* take an integer and return its suffix */
669         function setStandardArraysAttributes() {
670                 global $mod_strings;
671                 global $app_list_strings; // using from month _dom list
672
673                 $suffArr = array('','st','nd','rd');
674                 for($i=1; $i<32; $i++) {
675                         if($i > 3 && $i < 21) {
676                                 $this->suffixArray[$i] = $i."th";
677                         } elseif (substr($i,-1,1) < 4 && substr($i,-1,1) > 0) {
678                                 $this->suffixArray[$i] = $i.$suffArr[substr($i,-1,1)];
679                         } else {
680                                 $this->suffixArray[$i] = $i."th";
681                         }
682                         $this->datesArray[$i] = $i;
683                 }
684
685                 $this->dayInt = array('*',1,2,3,4,5,6,0);
686                 $this->dayLabel = array('*',$mod_strings['LBL_MON'],$mod_strings['LBL_TUE'],$mod_strings['LBL_WED'],$mod_strings['LBL_THU'],$mod_strings['LBL_FRI'],$mod_strings['LBL_SAT'],$mod_strings['LBL_SUN']);
687                 $this->monthsInt = array(0,1,2,3,4,5,6,7,8,9,10,11,12);
688                 $this->monthsLabel = $app_list_strings['dom_cal_month_long'];
689                 $this->metricsVar = array("*", "/", "-", ",");
690                 $this->metricsVal = array(' every ','',' thru ',' and ');
691         }
692
693         /**
694          *  takes the serialized interval string and renders it into an array
695          */
696         function parseInterval() {
697                 global $metricsVar;
698                 $ws = array(' ', '\r','\t');
699                 $blanks = array('','','');
700
701                 $intv = $this->job_interval;
702                 $rawValues = explode('::', $intv);
703                 $rawProcessed = str_replace($ws,$blanks,$rawValues); // strip all whitespace
704
705                 $hours = $rawValues[1].':::'.$rawValues[0];
706                 $months = $rawValues[3].':::'.$rawValues[2];
707
708                 $intA = array ( 'raw' => $rawProcessed,
709                                                 'hours' => $hours,
710                                                 'months' => $months,
711                                                 );
712
713                 $this->intervalParsed = $intA;
714         }
715
716         /**
717          * checks for cURL libraries
718          */
719         function checkCurl() {
720                 global $mod_strings;
721
722                 if(!function_exists('curl_init')) {
723                         echo '
724                         <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
725                                 <tr height="20">
726                                         <th width="25%" colspan="2"><slot>
727                                                 '.$mod_strings['LBL_WARN_CURL_TITLE'].'
728                                         </slot></td>
729                                 </tr>
730                                 <tr class="oddListRowS1" >
731                                         <td scope="row" valign=TOP width="20%"><slot>
732                                                 '.$mod_strings['LBL_WARN_CURL'].'
733                                         <td scope="row" valign=TOP width="80%"><slot>
734                                                 <span class=error>'.$mod_strings['LBL_WARN_NO_CURL'].'</span>
735                                         </slot></td>
736                                 </tr>
737                         </table>
738                         <br>';
739                 }
740         }
741
742         function displayCronInstructions() {
743                 global $mod_strings;
744                 global $sugar_config;
745                 $error = '';
746                 if (!isset($_SERVER['Path'])) {
747             $_SERVER['Path'] = getenv('Path');
748         }
749         if(is_windows()) {
750                         if(isset($_SERVER['Path']) && !empty($_SERVER['Path'])) { // IIS IUSR_xxx may not have access to Path or it is not set
751                                 if(!strpos($_SERVER['Path'], 'php')) {
752 //                                      $error = '<em>'.$mod_strings['LBL_NO_PHP_CLI'].'</em>';
753                                 }
754                         }
755                 } else {
756                         if(isset($_SERVER['Path']) && !empty($_SERVER['Path'])) { // some Linux servers do not make this available
757                                 if(!strpos($_SERVER['PATH'], 'php')) {
758 //                                      $error = '<em>'.$mod_strings['LBL_NO_PHP_CLI'].'</em>';
759                                 }
760                         }
761                 }
762
763
764
765                 if(is_windows()) {
766                         echo '<br>';
767                         echo '
768                                 <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
769                                 <tr height="20">
770                                         <th><slot>
771                                                 '.$mod_strings['LBL_CRON_INSTRUCTIONS_WINDOWS'].'
772                                         </slot></th>
773                                 </tr>
774                                 <tr class="evenListRowS1">
775                                         <td scope="row" valign="top" width="70%"><slot>
776                                                 '.$mod_strings['LBL_CRON_WINDOWS_DESC'].'<br>
777                                                 <b>cd '.realpath('./').'<br>
778                                                 php.exe -f cron.php</b>
779                                         </slot></td>
780                                 </tr>
781                         </table>';
782                 } else {
783                         echo '<br>';
784                         echo '
785                                 <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
786                                 <tr height="20">
787                                         <th><slot>
788                                                 '.$mod_strings['LBL_CRON_INSTRUCTIONS_LINUX'].'
789                                         </slot></th>
790                                 </tr>
791                                 <tr>
792                                         <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="70%"><slot>
793                                                 '.$mod_strings['LBL_CRON_LINUX_DESC'].'<br>
794                                                 <b>*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;
795                                                 cd '.realpath('./').'; php -f cron.php > /dev/null 2>&1</b>
796                                                 <br>'.$error.'
797                                         </slot></td>
798                                 </tr>
799                         </table>';
800                 }
801         }
802
803         /**
804          * Archives schedulers of the same functionality, then instantiates new
805          * ones.
806          */
807         function rebuildDefaultSchedulers() {
808                 global $mod_strings;
809                 // truncate scheduler-related tables
810                 $this->db->query('DELETE FROM schedulers');
811
812
813         $sched3 = new Scheduler();
814         $sched3->name               = $mod_strings['LBL_OOTB_TRACKER'];
815         $sched3->job                = 'function::trimTracker';
816         $sched3->date_time_start    = create_date(2005,1,1) . ' ' . create_time(0,0,1);
817         $sched3->date_time_end      = create_date(2020,12,31) . ' ' . create_time(23,59,59);
818         $sched3->job_interval       = '0::2::1::*::*';
819         $sched3->status             = 'Active';
820         $sched3->created_by         = '1';
821         $sched3->modified_user_id   = '1';
822         $sched3->catch_up           = '1';
823         $sched3->save();
824                 $sched4 = new Scheduler();
825                 $sched4->name                           = $mod_strings['LBL_OOTB_IE'];
826                 $sched4->job                            = 'function::pollMonitoredInboxes';
827                 $sched4->date_time_start        = create_date(2005,1,1) . ' ' . create_time(0,0,1);
828                 $sched4->date_time_end          = create_date(2020,12,31) . ' ' . create_time(23,59,59);
829                 $sched4->job_interval           = '*::*::*::*::*';
830                 $sched4->status                         = 'Active';
831                 $sched4->created_by                     = '1';
832                 $sched4->modified_user_id       = '1';
833                 $sched4->catch_up                       = '0';
834                 $sched4->save();
835
836                 $sched5 = new Scheduler();
837                 $sched5->name                           = $mod_strings['LBL_OOTB_BOUNCE'];
838                 $sched5->job                            = 'function::pollMonitoredInboxesForBouncedCampaignEmails';
839                 $sched5->date_time_start        = create_date(2005,1,1) . ' ' . create_time(0,0,1);
840                 $sched5->date_time_end          = create_date(2020,12,31) . ' ' . create_time(23,59,59);
841                 $sched5->job_interval           = '0::2-6::*::*::*';
842                 $sched5->status                         = 'Active';
843                 $sched5->created_by                     = '1';
844                 $sched5->modified_user_id       = '1';
845                 $sched5->catch_up                       = '1';
846                 $sched5->save();
847
848                 $sched6 = new Scheduler();
849                 $sched6->name                           = $mod_strings['LBL_OOTB_CAMPAIGN'];
850                 $sched6->job                            = 'function::runMassEmailCampaign';
851                 $sched6->date_time_start        = create_date(2005,1,1) . ' ' . create_time(0,0,1);
852                 $sched6->date_time_end          = create_date(2020,12,31) . ' ' . create_time(23,59,59);
853                 $sched6->job_interval           = '0::2-6::*::*::*';
854                 $sched6->status                         = 'Active';
855                 $sched6->created_by                     = '1';
856                 $sched6->modified_user_id       = '1';
857                 $sched6->catch_up                       = '1';
858                 $sched6->save();
859
860
861         $sched7 = new Scheduler();
862         $sched7->name               = $mod_strings['LBL_OOTB_PRUNE'];
863         $sched7->job                = 'function::pruneDatabase';
864         $sched7->date_time_start    = create_date(2005,1,1) . ' ' . create_time(0,0,1);
865         $sched7->date_time_end      = create_date(2020,12,31) . ' ' . create_time(23,59,59);
866         $sched7->job_interval       = '0::4::1::*::*';
867         $sched7->status             = 'Inactive';
868         $sched7->created_by         = '1';
869         $sched7->modified_user_id   = '1';
870         $sched7->catch_up           = '0';
871         $sched7->save();
872
873
874
875
876         $sched12 = new Scheduler();
877         $sched12->name               = $mod_strings['LBL_OOTB_SEND_EMAIL_REMINDERS'];
878         $sched12->job                = 'function::sendEmailReminders';
879         $sched12->date_time_start    = create_date(2008,1,1) . ' ' . create_time(0,0,1);
880         $sched12->date_time_end      = create_date(2020,12,31) . ' ' . create_time(23,59,59);
881         $sched12->job_interval       = '*::*::*::*::*';
882         $sched12->status             = 'Active';
883         $sched12->created_by         = '1';
884         $sched12->modified_user_id   = '1';
885         $sched12->catch_up           = '0';
886         $sched12->save();
887
888         }
889
890         ////    END SCHEDULER HELPER FUNCTIONS
891         ///////////////////////////////////////////////////////////////////////////
892
893
894         ///////////////////////////////////////////////////////////////////////////
895         ////    STANDARD SUGARBEAN OVERRIDES
896         /**
897          * function overrides the one in SugarBean.php
898          */
899         function create_export_query($order_by, $where, $show_deleted = 0) {
900                 return $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted = 0);
901         }
902
903         /**
904          * function overrides the one in SugarBean.php
905          */
906
907         /**
908          * function overrides the one in SugarBean.php
909          */
910         function fill_in_additional_list_fields() {
911                 $this->fill_in_additional_detail_fields();
912         }
913
914         /**
915          * function overrides the one in SugarBean.php
916          */
917         function fill_in_additional_detail_fields() {
918     }
919
920         /**
921          * function overrides the one in SugarBean.php
922          */
923         function get_list_view_data()
924         {
925                 global $mod_strings;
926                 $temp_array = $this->get_list_view_array();
927         $temp_array["ENCODED_NAME"]=$this->name;
928         $this->parseInterval();
929         $this->setIntervalHumanReadable();
930         $temp_array['JOB_INTERVAL'] = $this->intervalHumanReadable;
931         if($this->date_time_end == '2020-12-31 23:59' || $this->date_time_end == '') {
932                 $temp_array['DATE_TIME_END'] = $mod_strings['LBL_PERENNIAL'];
933         }
934         $this->created_by_name = get_assigned_user_name($this->created_by);
935                 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
936         return $temp_array;
937
938         }
939
940         /**
941          * returns the bean name - overrides SugarBean's
942          */
943         function get_summary_text()
944         {
945                 return $this->name;
946         }
947         ////    END STANDARD SUGARBEAN OVERRIDES
948         ///////////////////////////////////////////////////////////////////////////
949         static public function getJobsList()
950         {
951                 if(empty(self::$job_strings)) {
952                         global $mod_strings;
953                         include_once('modules/Schedulers/_AddJobsHere.php');
954
955                         // job functions
956                         self::$job_strings = array('url::' => 'URL');
957                         foreach($job_strings as $k=>$v){
958                                 self::$job_strings['function::' . $v] = $mod_strings['LBL_'.strtoupper($v)];
959                         }
960                 }
961                 return self::$job_strings;
962         }
963 } // end class definition