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-2013 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',
67 14 => 'cleanJobQueue',
72 * Job 0 refreshes all job schedulers at midnight
75 function refreshJobs() {
83 function pollMonitoredInboxes() {
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()');
91 require_once('modules/Emails/EmailUI.php');
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');
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;
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);
115 if($ieX->connectMailserver() == 'true') {
116 $connectToMailServer = true;
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();
125 if(is_array($newMsgs)) {
127 $total = count($newMsgs);
128 require_once("include/SugarFolders/SugarFolders.php");
129 $sugarFolder = new SugarFolder();
130 $groupFolderId = $ieX->groupfolder_id;
131 $isGroupFolderExists = false;
133 if ($groupFolderId != null && $groupFolderId != "") {
134 $sugarFolder->retrieve($groupFolderId);
135 $isGroupFolderExists = true;
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);
144 $lastRobin = $emailUI->getLastRobin($ieX);
146 $GLOBALS['log']->debug('distribution method id [ '.$distributionMethod.' ]');
148 foreach($newMsgs as $k => $msgNo) {
150 if ($ieX->isPop3Protocol()) {
151 $uid = $msgNoToUIDL[$msgNo];
153 $uid = imap_uid($ieX->conn, $msgNo);
155 if ($isGroupFolderExists) {
156 if ($ieX->importOneEmail($msgNo, $uid)) {
158 $sugarFolder->addBean($ieX->email);
159 if ($ieX->isPop3Protocol()) {
160 $messagesToDelete[] = $msgNo;
162 $messagesToDelete[] = $uid;
164 if ($ieX->isMailBoxTypeCreateCase()) {
166 if ($distributionMethod == 'roundRobin') {
167 if (sizeof($users) == 1) {
169 $lastRobin = $users[0];
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];
178 $lastRobin = $users[0];
182 if (sizeof($users) == 1) {
183 foreach($users as $k => $value) {
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;
194 $GLOBALS['log']->debug('userId [ '.$userId.' ]');
195 $ieX->handleCreateCase($ieX->email, $userId);
199 if($ieX->isAutoImport()) {
200 $ieX->importOneEmail($msgNo, $uid);
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;
213 $contactAddr = $email->from_addr;
215 $mailBoxType = $ieX->mailbox_type;
216 $ieX->handleAutoresponse($email, $contactAddr);
219 $GLOBALS['log']->debug('***** On message [ '.$current.' of '.$total.' ] *****');
222 // update Inbound Account with last robin
223 if ($ieX->isMailBoxTypeCreateCase() && $distributionMethod == 'roundRobin') {
224 $emailUI->setLastRobin($ieX, $lastRobin);
228 if ($isGroupFolderExists) {
229 $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0);
230 if (!$leaveMessagesOnMailServer) {
231 if ($ieX->isPop3Protocol()) {
232 $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete));
234 $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete));
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
243 imap_expunge($ieX->conn);
244 imap_close($ieX->conn, CL_EXPUNGE);
246 $GLOBALS['current_user']->team_id = $_bck_up['team_id'];
247 $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id'];
254 function runMassEmailCampaign() {
255 if (!class_exists('LoggerManager')){
258 $GLOBALS['log'] = LoggerManager::getLogger('emailmandelivery');
259 $GLOBALS['log']->debug('Called:runMassEmailCampaign');
261 if (!class_exists('DBManagerFactory')){
262 require('include/database/DBManagerFactory.php');
267 require("config.php");
268 require('include/modules.php');
269 if(!class_exists('AclController')) {
270 require('modules/ACL/ACLController.php');
273 require('modules/EmailMan/EmailManDelivery.php');
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';
285 $db = DBManagerFactory::getInstance();
286 $tables = $db->getTablesArray();
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;
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();
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
311 $queryString[] = $db->insertParams($table, $columns, $aDel, null, false);
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);
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()
322 $db->query('DELETE FROM '.$table.'_cstm WHERE id_c = '.$db->quoted($aDel['id']));
324 } // end aDel while()
325 // now do the actual delete
326 $db->query('DELETE FROM '.$table.' WHERE deleted = 1');
327 } // foreach() tables
329 if(!file_exists($backupDir) || !file_exists($backupDir.'/'.$backupFile)) {
330 // create directory if not existent
331 mkdir_recursive($backupDir, false);
335 write_array_to_file('pruneDatabase', $queryString, $backupDir.'/'.$backupFile);
346 //function securityAudit() {
351 function trimTracker()
353 global $sugar_config, $timedate;
354 $GLOBALS['log']->info('----->Scheduler fired job of type trimTracker()');
355 $db = DBManagerFactory::getInstance();
357 $admin = new Administration();
358 $admin->retrieveSettings('tracker');
359 require('modules/Trackers/config.php');
360 $trackerConfig = $tracker_config;
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) {
366 //Skip if table does not exist
367 if(!$db->tableExists($tableName)) {
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";
375 $query = "DELETE FROM $tableName WHERE date_modified < $timeStamp";
378 $GLOBALS['log']->info("----->Scheduler is about to trim the $tableName table by running the query $query");
387 function pollMonitoredInboxesForBouncedCampaignEmails() {
388 $GLOBALS['log']->info('----->Scheduler job of type pollMonitoredInboxesForBouncedCampaignEmails()');
392 $ie = new InboundEmail();
393 $r = $ie->db->query('SELECT id FROM inbound_email WHERE deleted=0 AND status=\'Active\' AND mailbox_type=\'bounce\'');
395 while($a = $ie->db->fetchByAssoc($r)) {
396 $ieX = new InboundEmail();
397 $ieX->retrieve($a['id']);
398 $ieX->connectMailserver();
399 $ieX->importMessages();
411 function sendEmailReminders(){
412 $GLOBALS['log']->info('----->Scheduler fired job of type sendEmailReminders()');
413 require_once("modules/Activities/EmailReminder.php");
414 $reminder = new EmailReminder();
415 return $reminder->process();
420 function cleanJobQueue($job)
422 $td = TimeDate::getInstance();
423 // soft delete all jobs that are older than cutoff
425 if(isset($GLOBALS['sugar_config']['jobs']['soft_lifetime'])) {
426 $soft_cutoff = $GLOBALS['sugar_config']['jobs']['soft_lifetime'];
428 $soft_cutoff_date = $job->db->quoted($td->getNow()->modify("- $soft_cutoff days")->asDb());
429 $job->db->query("UPDATE {$job->table_name} SET deleted=1 WHERE status='done' AND date_modified < ".$job->db->convert($soft_cutoff_date, 'datetime'));
430 // hard delete all jobs that are older than hard cutoff
432 if(isset($GLOBALS['sugar_config']['jobs']['hard_lifetime'])) {
433 $hard_cutoff = $GLOBALS['sugar_config']['jobs']['hard_lifetime'];
435 $hard_cutoff_date = $job->db->quoted($td->getNow()->modify("- $hard_cutoff days")->asDb());
436 $job->db->query("DELETE FROM {$job->table_name} WHERE status='done' AND date_modified < ".$job->db->convert($hard_cutoff_date, 'datetime'));
440 if (file_exists('custom/modules/Schedulers/_AddJobsHere.php')) {
441 require('custom/modules/Schedulers/_AddJobsHere.php');
444 if (file_exists('custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php'))
446 require('custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php');