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