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