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.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
40 * Set up an array of Jobs with the appropriate metadata
41 * 'jobName' => array (
44 * 'X' should be an increment of 1
45 * 'name' should be the EXACT name of your function
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
55 * This array provides the Schedulers admin interface with values for its "Job"
58 $job_strings = array (
60 1 => 'pollMonitoredInboxes',
61 2 => 'runMassEmailCampaign',
62 5 => 'pollMonitoredInboxesForBouncedCampaignEmails',
65 /*4 => 'securityAudit()',*/
66 12 => 'sendEmailReminders',
71 * Job 0 refreshes all job schedulers at midnight
74 function refreshJobs() {
82 function pollMonitoredInboxes() {
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()');
90 require_once('modules/Emails/EmailUI.php');
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');
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;
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);
114 if($ieX->connectMailserver() == 'true') {
115 $connectToMailServer = true;
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();
124 if(is_array($newMsgs)) {
126 $total = count($newMsgs);
127 require_once("include/SugarFolders/SugarFolders.php");
128 $sugarFolder = new SugarFolder();
129 $groupFolderId = $ieX->groupfolder_id;
130 $isGroupFolderExists = false;
132 if ($groupFolderId != null && $groupFolderId != "") {
133 $sugarFolder->retrieve($groupFolderId);
134 $isGroupFolderExists = true;
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);
143 $lastRobin = $emailUI->getLastRobin($ieX);
145 $GLOBALS['log']->debug('distribution method id [ '.$distributionMethod.' ]');
147 foreach($newMsgs as $k => $msgNo) {
149 if ($ieX->isPop3Protocol()) {
150 $uid = $msgNoToUIDL[$msgNo];
152 $uid = imap_uid($ieX->conn, $msgNo);
154 if ($isGroupFolderExists) {
155 if ($ieX->importOneEmail($msgNo, $uid)) {
157 $sugarFolder->addBean($ieX->email);
158 if ($ieX->isPop3Protocol()) {
159 $messagesToDelete[] = $msgNo;
161 $messagesToDelete[] = $uid;
163 if ($ieX->isMailBoxTypeCreateCase()) {
165 if ($distributionMethod == 'roundRobin') {
166 if (sizeof($users) == 1) {
168 $lastRobin = $users[0];
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];
177 $lastRobin = $users[0];
181 if (sizeof($users) == 1) {
182 foreach($users as $k => $value) {
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;
193 $GLOBALS['log']->debug('userId [ '.$userId.' ]');
194 $ieX->handleCreateCase($ieX->email, $userId);
198 if($ieX->isAutoImport()) {
199 $ieX->importOneEmail($msgNo, $uid);
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;
212 $contactAddr = $email->from_addr;
214 $mailBoxType = $ieX->mailbox_type;
215 $ieX->handleAutoresponse($email, $contactAddr);
218 $GLOBALS['log']->debug('***** On message [ '.$current.' of '.$total.' ] *****');
221 // update Inbound Account with last robin
222 if ($ieX->isMailBoxTypeCreateCase() && $distributionMethod == 'roundRobin') {
223 $emailUI->setLastRobin($ieX, $lastRobin);
227 if ($isGroupFolderExists) {
228 $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0);
229 if (!$leaveMessagesOnMailServer) {
230 if ($ieX->isPop3Protocol()) {
231 $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete));
233 $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete));
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
242 imap_expunge($ieX->conn);
243 imap_close($ieX->conn, CL_EXPUNGE);
245 $GLOBALS['current_user']->team_id = $_bck_up['team_id'];
246 $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id'];
253 function runMassEmailCampaign() {
254 if (!class_exists('LoggerManager')){
257 $GLOBALS['log'] = LoggerManager::getLogger('emailmandelivery');
258 $GLOBALS['log']->debug('Called:runMassEmailCampaign');
260 if (!class_exists('DBManagerFactory')){
261 require('include/database/DBManagerFactory.php');
266 require("config.php");
267 require('include/modules.php');
268 if(!class_exists('AclController')) {
269 require('modules/ACL/ACLController.php');
272 require('modules/EmailMan/EmailManDelivery.php');
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';
284 $db = DBManagerFactory::getInstance();
285 $tables = $db->getTablesArray();
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;
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();
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
310 $queryString[] = $db->insertParams($table, $columns, $rDel, null, false);
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);
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()
321 $db->query('DELETE FROM '.$table.'_cstm WHERE id_c = '.$db->quoted($aDel['id']));
323 } // end aDel while()
324 // now do the actual delete
325 $db->query('DELETE FROM '.$table.' WHERE deleted = 1');
326 } // foreach() tables
328 if(!file_exists($backupDir) || !file_exists($backupDir.'/'.$backupFile)) {
329 // create directory if not existent
330 mkdir_recursive($backupDir, false);
334 write_array_to_file('pruneDatabase', $queryString, $backupDir.'/'.$backupFile);
345 //function securityAudit() {
350 function trimTracker()
352 global $sugar_config, $timedate;
353 $GLOBALS['log']->info('----->Scheduler fired job of type trimTracker()');
354 $db = DBManagerFactory::getInstance();
356 $admin = new Administration();
357 $admin->retrieveSettings('tracker');
358 require('modules/Trackers/config.php');
359 $trackerConfig = $tracker_config;
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) {
365 //Skip if table does not exist
366 if(!$db->tableExists($tableName)) {
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";
374 $query = "DELETE FROM $tableName WHERE date_modified < $timeStamp";
377 $GLOBALS['log']->info("----->Scheduler is about to trim the $tableName table by running the query $query");
386 function pollMonitoredInboxesForBouncedCampaignEmails() {
387 $GLOBALS['log']->info('----->Scheduler job of type pollMonitoredInboxesForBouncedCampaignEmails()');
391 $ie = new InboundEmail();
392 $r = $ie->db->query('SELECT id FROM inbound_email WHERE deleted=0 AND status=\'Active\' AND mailbox_type=\'bounce\'');
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']} ");
400 if ($ieX->isPop3Protocol()) {
401 $newMsgs = $ieX->getPop3NewMessagesToDownload();
403 $newMsgs = $ieX->getNewMessageIds();
406 //$newMsgs = $ieX->getNewMessageIds();
407 if(is_array($newMsgs)) {
408 foreach($newMsgs as $k => $msgNo) {
410 if ($ieX->isPop3Protocol()) {
411 $uid = $ieX->getUIDLForMessage($msgNo);
413 $uid = imap_uid($ieX->conn, $msgNo);
415 $GLOBALS['log']->info("Bounced campaign scheduler will import message no: $msgNo");
416 $ieX->importOneEmail($msgNo, $uid, false,false);
419 imap_expunge($ieX->conn);
420 imap_close($ieX->conn);
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();
441 if (file_exists('custom/modules/Schedulers/_AddJobsHere.php')) {
442 require('custom/modules/Schedulers/_AddJobsHere.php');
445 if (file_exists('custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php'))
447 require('custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php');