]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Schedulers/_AddJobsHere.php
Release 6.5.3
[Github/sugarcrm.git] / modules / Schedulers / _AddJobsHere.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
39 /**
40  * Set up an array of Jobs with the appropriate metadata
41  * 'jobName' => array (
42  *              'X' => 'name',
43  * )
44  * 'X' should be an increment of 1
45  * 'name' should be the EXACT name of your function
46  *
47  * Your function should not be passed any parameters
48  * Always  return a Boolean. If it does not the Job will not terminate itself
49  * after completion, and the webserver will be forced to time-out that Job instance.
50  * DO NOT USE sugar_cleanup(); in your function flow or includes.  this will
51  * break Schedulers.  That function is called at the foot of cron.php
52  */
53
54 /**
55  * This array provides the Schedulers admin interface with values for its "Job"
56  * dropdown menu.
57  */
58 $job_strings = array (
59         0 => 'refreshJobs',
60         1 => 'pollMonitoredInboxes',
61         2 => 'runMassEmailCampaign',
62     5 => 'pollMonitoredInboxesForBouncedCampaignEmails',
63         3 => 'pruneDatabase',
64         4 => 'trimTracker',
65         /*4 => 'securityAudit()',*/
66     12 => 'sendEmailReminders',
67     14 => 'cleanJobQueue',
68
69 );
70
71 /**
72  * Job 0 refreshes all job schedulers at midnight
73  * DEPRECATED
74  */
75 function refreshJobs() {
76         return true;
77 }
78
79
80 /**
81  * Job 1
82  */
83 function pollMonitoredInboxes() {
84
85     $_bck_up = array('team_id' => $GLOBALS['current_user']->team_id, 'team_set_id' => $GLOBALS['current_user']->team_set_id);
86         $GLOBALS['log']->info('----->Scheduler fired job of type pollMonitoredInboxes()');
87         global $dictionary;
88         global $app_strings;
89
90
91         require_once('modules/Emails/EmailUI.php');
92
93         $ie = new InboundEmail();
94         $emailUI = new EmailUI();
95         $r = $ie->db->query('SELECT id, name FROM inbound_email WHERE is_personal = 0 AND deleted=0 AND status=\'Active\' AND mailbox_type != \'bounce\'');
96         $GLOBALS['log']->debug('Just got Result from get all Inbounds of Inbound Emails');
97
98         while($a = $ie->db->fetchByAssoc($r)) {
99                 $GLOBALS['log']->debug('In while loop of Inbound Emails');
100                 $ieX = new InboundEmail();
101                 $ieX->retrieve($a['id']);
102         $GLOBALS['current_user']->team_id = $ieX->team_id;
103         $GLOBALS['current_user']->team_set_id = $ieX->team_set_id;
104                 $mailboxes = $ieX->mailboxarray;
105                 foreach($mailboxes as $mbox) {
106                         $ieX->mailbox = $mbox;
107                         $newMsgs = array();
108                         $msgNoToUIDL = array();
109                         $connectToMailServer = false;
110                         if ($ieX->isPop3Protocol()) {
111                                 $msgNoToUIDL = $ieX->getPop3NewMessagesToDownloadForCron();
112                                 // get all the keys which are msgnos;
113                                 $newMsgs = array_keys($msgNoToUIDL);
114                         }
115                         if($ieX->connectMailserver() == 'true') {
116                                 $connectToMailServer = true;
117                         } // if
118
119                         $GLOBALS['log']->debug('Trying to connect to mailserver for [ '.$a['name'].' ]');
120                         if($connectToMailServer) {
121                                 $GLOBALS['log']->debug('Connected to mailserver');
122                                 if (!$ieX->isPop3Protocol()) {
123                                         $newMsgs = $ieX->getNewMessageIds();
124                                 }
125                                 if(is_array($newMsgs)) {
126                                         $current = 1;
127                                         $total = count($newMsgs);
128                                         require_once("include/SugarFolders/SugarFolders.php");
129                                         $sugarFolder = new SugarFolder();
130                                         $groupFolderId = $ieX->groupfolder_id;
131                                         $isGroupFolderExists = false;
132                                         $users = array();
133                                         if ($groupFolderId != null && $groupFolderId != "") {
134                                                 $sugarFolder->retrieve($groupFolderId);
135                                                 $isGroupFolderExists = true;
136                                         } // if
137                                         $messagesToDelete = array();
138                                         if ($ieX->isMailBoxTypeCreateCase()) {
139                                                 $users[] = $sugarFolder->assign_to_id;
140                                                 $distributionMethod = $ieX->get_stored_options("distrib_method", "");
141                                                 if ($distributionMethod != 'roundRobin') {
142                                                         $counts = $emailUI->getAssignedEmailsCountForUsers($users);
143                                                 } else {
144                                                         $lastRobin = $emailUI->getLastRobin($ieX);
145                                                 }
146                                                 $GLOBALS['log']->debug('distribution method id [ '.$distributionMethod.' ]');
147                                         }
148                                         foreach($newMsgs as $k => $msgNo) {
149                                                 $uid = $msgNo;
150                                                 if ($ieX->isPop3Protocol()) {
151                                                         $uid = $msgNoToUIDL[$msgNo];
152                                                 } else {
153                                                         $uid = imap_uid($ieX->conn, $msgNo);
154                                                 } // else
155                                                 if ($isGroupFolderExists) {
156                                                         if ($ieX->importOneEmail($msgNo, $uid)) {
157                                                                 // add to folder
158                                                                 $sugarFolder->addBean($ieX->email);
159                                                                 if ($ieX->isPop3Protocol()) {
160                                                                         $messagesToDelete[] = $msgNo;
161                                                                 } else {
162                                                                         $messagesToDelete[] = $uid;
163                                                                 }
164                                                                 if ($ieX->isMailBoxTypeCreateCase()) {
165                                                                         $userId = "";
166                                                                         if ($distributionMethod == 'roundRobin') {
167                                                                                 if (sizeof($users) == 1) {
168                                                                                         $userId = $users[0];
169                                                                                         $lastRobin = $users[0];
170                                                                                 } else {
171                                                                                         $userIdsKeys = array_flip($users); // now keys are values
172                                                                                         $thisRobinKey = $userIdsKeys[$lastRobin] + 1;
173                                                                                         if(!empty($users[$thisRobinKey])) {
174                                                                                                 $userId = $users[$thisRobinKey];
175                                                                                                 $lastRobin = $users[$thisRobinKey];
176                                                                                         } else {
177                                                                                                 $userId = $users[0];
178                                                                                                 $lastRobin = $users[0];
179                                                                                         }
180                                                                                 } // else
181                                                                         } else {
182                                                                                 if (sizeof($users) == 1) {
183                                                                                         foreach($users as $k => $value) {
184                                                                                                 $userId = $value;
185                                                                                         } // foreach
186                                                                                 } else {
187                                                                                         asort($counts); // lowest to highest
188                                                                                         $countsKeys = array_flip($counts); // keys now the 'count of items'
189                                                                                         $leastBusy = array_shift($countsKeys); // user id of lowest item count
190                                                                                         $userId = $leastBusy;
191                                                                                         $counts[$leastBusy] = $counts[$leastBusy] + 1;
192                                                                                 }
193                                                                         } // else
194                                                                         $GLOBALS['log']->debug('userId [ '.$userId.' ]');
195                                                                         $ieX->handleCreateCase($ieX->email, $userId);
196                                                                 } // if
197                                                         } // if
198                                                 } else {
199                                                                 if($ieX->isAutoImport()) {
200                                                                         $ieX->importOneEmail($msgNo, $uid);
201                                                                 } else {
202                                                                         /*If the group folder doesn't exist then download only those messages
203                                                                          which has caseid in message*/
204                                                                         $ieX->getMessagesInEmailCache($msgNo, $uid);
205                                                                         $email = new Email();
206                                                                         $header = imap_headerinfo($ieX->conn, $msgNo);
207                                                                         $email->name = $ieX->handleMimeHeaderDecode($header->subject);
208                                                                         $email->from_addr = $ieX->convertImapToSugarEmailAddress($header->from);
209                                                                         $email->reply_to_email  = $ieX->convertImapToSugarEmailAddress($header->reply_to);
210                                                                         if(!empty($email->reply_to_email)) {
211                                                                                 $contactAddr = $email->reply_to_email;
212                                                                         } else {
213                                                                                 $contactAddr = $email->from_addr;
214                                                                         }
215                                                                         $mailBoxType = $ieX->mailbox_type;
216                                                                                 $ieX->handleAutoresponse($email, $contactAddr);
217                                                                 } // else
218                                                 } // else
219                                                 $GLOBALS['log']->debug('***** On message [ '.$current.' of '.$total.' ] *****');
220                                                 $current++;
221                                         } // foreach
222                                         // update Inbound Account with last robin
223                                         if ($ieX->isMailBoxTypeCreateCase() && $distributionMethod == 'roundRobin') {
224                                                 $emailUI->setLastRobin($ieX, $lastRobin);
225                                         } // if
226
227                                 } // if
228                                 if ($isGroupFolderExists)        {
229                                         $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0);
230                                         if (!$leaveMessagesOnMailServer) {
231                                                 if ($ieX->isPop3Protocol()) {
232                                                         $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete));
233                                                 } else {
234                                                         $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete));
235                                                 }
236                                         }
237                                 }
238                         } else {
239                                 $GLOBALS['log']->fatal("SCHEDULERS: could not get an IMAP connection resource for ID [ {$a['id']} ]. Skipping mailbox [ {$a['name']} ].");
240                                 // cn: bug 9171 - continue while
241                         } // else
242                 } // foreach
243                 imap_expunge($ieX->conn);
244                 imap_close($ieX->conn, CL_EXPUNGE);
245         } // while
246     $GLOBALS['current_user']->team_id = $_bck_up['team_id'];
247     $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id'];
248         return true;
249 }
250
251 /**
252  * Job 2
253  */
254 function runMassEmailCampaign() {
255         if (!class_exists('LoggerManager')){
256
257         }
258         $GLOBALS['log'] = LoggerManager::getLogger('emailmandelivery');
259         $GLOBALS['log']->debug('Called:runMassEmailCampaign');
260
261         if (!class_exists('DBManagerFactory')){
262                 require('include/database/DBManagerFactory.php');
263         }
264
265         global $beanList;
266         global $beanFiles;
267         require("config.php");
268         require('include/modules.php');
269         if(!class_exists('AclController')) {
270                 require('modules/ACL/ACLController.php');
271         }
272
273         require('modules/EmailMan/EmailManDelivery.php');
274         return true;
275 }
276
277 /**
278  *  Job 3
279  */
280 function pruneDatabase() {
281         $GLOBALS['log']->info('----->Scheduler fired job of type pruneDatabase()');
282         $backupDir      = sugar_cached('backups');
283         $backupFile     = 'backup-pruneDatabase-GMT0_'.gmdate('Y_m_d-H_i_s', strtotime('now')).'.php';
284
285         $db = DBManagerFactory::getInstance();
286         $tables = $db->getTablesArray();
287
288 //_ppd($tables);
289         if(!empty($tables)) {
290                 foreach($tables as $kTable => $table) {
291                         // find tables with deleted=1
292                         $columns = $db->get_columns($table);
293                         // no deleted - won't delete
294                         if(empty($columns['deleted'])) continue;
295
296                         $custom_columns = array();
297                         if(array_search($table.'_cstm', $tables)) {
298                             $custom_columns = $db->get_columns($table.'_cstm');
299                             if(empty($custom_columns['id_c'])) {
300                                 $custom_columns = array();
301                             }
302                         }
303
304                         $qDel = "SELECT * FROM $table WHERE deleted = 1";
305                         $rDel = $db->query($qDel);
306                         $queryString = array();
307                         // make a backup INSERT query if we are deleting.
308                         while($aDel = $db->fetchByAssoc($rDel, false)) {
309                                 // build column names
310
311                                 $queryString[] = $db->insertParams($table, $columns, $aDel, null, false);
312
313                                 if(!empty($custom_columns) && !empty($aDel['id'])) {
314                     $qDelCstm = 'SELECT * FROM '.$table.'_cstm WHERE id_c = '.$db->quoted($aDel['id']);
315                     $rDelCstm = $db->query($qDelCstm);
316
317                     // make a backup INSERT query if we are deleting.
318                     while($aDelCstm = $db->fetchByAssoc($rDelCstm)) {
319                         $queryString[] = $db->insertParams($table, $custom_columns, $aDelCstm, null, false);
320                     } // end aDel while()
321
322                     $db->query('DELETE FROM '.$table.'_cstm WHERE id_c = '.$db->quoted($aDel['id']));
323                 }
324                         } // end aDel while()
325                         // now do the actual delete
326                         $db->query('DELETE FROM '.$table.' WHERE deleted = 1');
327                 } // foreach() tables
328
329                 if(!file_exists($backupDir) || !file_exists($backupDir.'/'.$backupFile)) {
330                         // create directory if not existent
331                         mkdir_recursive($backupDir, false);
332                 }
333                 // write cache file
334
335                 write_array_to_file('pruneDatabase', $queryString, $backupDir.'/'.$backupFile);
336                 return true;
337         }
338         return false;
339 }
340
341
342 ///**
343 // * Job 4
344 // */
345
346 //function securityAudit() {
347 //      // do something
348 //      return true;
349 //}
350
351 function trimTracker()
352 {
353     global $sugar_config, $timedate;
354         $GLOBALS['log']->info('----->Scheduler fired job of type trimTracker()');
355         $db = DBManagerFactory::getInstance();
356
357         $admin = new Administration();
358         $admin->retrieveSettings('tracker');
359         require('modules/Trackers/config.php');
360         $trackerConfig = $tracker_config;
361
362     require_once('include/utils/db_utils.php');
363     $prune_interval = !empty($admin->settings['tracker_prune_interval']) ? $admin->settings['tracker_prune_interval'] : 30;
364         foreach($trackerConfig as $tableName=>$tableConfig) {
365
366                 //Skip if table does not exist
367                 if(!$db->tableExists($tableName)) {
368                    continue;
369                 }
370
371             $timeStamp = db_convert("'". $timedate->asDb($timedate->getNow()->get("-".$prune_interval." days")) ."'" ,"datetime");
372                 if($tableName == 'tracker_sessions') {
373                    $query = "DELETE FROM $tableName WHERE date_end < $timeStamp";
374                 } else {
375                    $query = "DELETE FROM $tableName WHERE date_modified < $timeStamp";
376                 }
377
378             $GLOBALS['log']->info("----->Scheduler is about to trim the $tableName table by running the query $query");
379                 $db->query($query);
380         } //foreach
381     return true;
382 }
383
384 /* Job 5
385  *
386  */
387 function pollMonitoredInboxesForBouncedCampaignEmails() {
388         $GLOBALS['log']->info('----->Scheduler job of type pollMonitoredInboxesForBouncedCampaignEmails()');
389         global $dictionary;
390
391
392         $ie = new InboundEmail();
393         $r = $ie->db->query('SELECT id FROM inbound_email WHERE deleted=0 AND status=\'Active\' AND mailbox_type=\'bounce\'');
394
395         while($a = $ie->db->fetchByAssoc($r)) {
396                 $ieX = new InboundEmail();
397                 $ieX->retrieve($a['id']);
398                 $ieX->connectMailserver();
399         $GLOBALS['log']->info("Bounced campaign scheduler connected to mail server id: {$a['id']} ");
400                 $newMsgs = array();
401                 if ($ieX->isPop3Protocol()) {
402                         $newMsgs = $ieX->getPop3NewMessagesToDownload();
403                 } else {
404                         $newMsgs = $ieX->getNewMessageIds();
405                 }
406
407                 //$newMsgs = $ieX->getNewMessageIds();
408                 if(is_array($newMsgs)) {
409                         foreach($newMsgs as $k => $msgNo) {
410                                 $uid = $msgNo;
411                                 if ($ieX->isPop3Protocol()) {
412                                         $uid = $ieX->getUIDLForMessage($msgNo);
413                                 } else {
414                                         $uid = imap_uid($ieX->conn, $msgNo);
415                                 } // else
416                  $GLOBALS['log']->info("Bounced campaign scheduler will import message no: $msgNo");
417                                 $ieX->importOneEmail($msgNo, $uid, false,false);
418                         }
419                 }
420                 imap_expunge($ieX->conn);
421                 imap_close($ieX->conn);
422         }
423
424         return true;
425 }
426
427
428
429
430 /**
431  * Job 12
432  */
433 function sendEmailReminders(){
434         $GLOBALS['log']->info('----->Scheduler fired job of type sendEmailReminders()');
435         require_once("modules/Activities/EmailReminder.php");
436         $reminder = new EmailReminder();
437         return $reminder->process();
438 }
439
440
441
442 function cleanJobQueue($job)
443 {
444     $td = TimeDate::getInstance();
445     // soft delete all jobs that are older than cutoff
446     $soft_cutoff = 7;
447     if(isset($GLOBALS['sugar_config']['jobs']['soft_lifetime'])) {
448         $soft_cutoff = $GLOBALS['sugar_config']['jobs']['soft_lifetime'];
449     }
450     $soft_cutoff_date = $job->db->quoted($td->getNow()->modify("- $soft_cutoff days")->asDb());
451     $job->db->query("UPDATE {$job->table_name} SET deleted=1 WHERE status='done' AND date_modified < ".$job->db->convert($soft_cutoff_date, 'datetime'));
452     // hard delete all jobs that are older than hard cutoff
453     $hard_cutoff = 21;
454     if(isset($GLOBALS['sugar_config']['jobs']['hard_lifetime'])) {
455         $hard_cutoff = $GLOBALS['sugar_config']['jobs']['hard_lifetime'];
456     }
457     $hard_cutoff_date = $job->db->quoted($td->getNow()->modify("- $hard_cutoff days")->asDb());
458     $job->db->query("DELETE FROM {$job->table_name} WHERE status='done' AND date_modified < ".$job->db->convert($hard_cutoff_date, 'datetime'));
459     return true;
460 }
461
462 if (file_exists('custom/modules/Schedulers/_AddJobsHere.php')) {
463         require('custom/modules/Schedulers/_AddJobsHere.php');
464 }
465
466 if (file_exists('custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php'))
467 {
468         require('custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php');
469 }
470 ?>