array ( * 'X' => 'name', * ) * 'X' should be an increment of 1 * 'name' should be the EXACT name of your function * * Your function should not be passed any parameters * Always return a Boolean. If it does not the Job will not terminate itself * after completion, and the webserver will be forced to time-out that Job instance. * DO NOT USE sugar_cleanup(); in your function flow or includes. this will * break Schedulers. That function is called at the foot of cron.php */ /** * This array provides the Schedulers admin interface with values for its "Job" * dropdown menu. */ $job_strings = array ( 0 => 'refreshJobs', 1 => 'pollMonitoredInboxes', 2 => 'runMassEmailCampaign', 5 => 'pollMonitoredInboxesForBouncedCampaignEmails', 3 => 'pruneDatabase', 4 => 'trimTracker', 6 => 'checkEDISales', 7 => 'mailingsE5' ) ; /** * Job 0 refreshes all job schedulers at midnight * DEPRECATED */ function refreshJobs() { return true; } function mailingsE5(){ require_once ('modules/Schedulers/MailingCron.php'); $mailingCron = new MailingCron (); $mailingCron->getMalingToSend (); return true; } /** * Job 1 */ function pollMonitoredInboxes() { $GLOBALS ['log']->info ( '----->Scheduler fired job of type pollMonitoredInboxes()' ); global $dictionary; global $app_strings; require_once ('modules/Emails/EmailUI.php'); $ie = new InboundEmail (); $emailUI = new EmailUI (); $r = $ie->db->query ( 'SELECT id, name FROM inbound_email WHERE is_personal = 0 AND deleted=0 AND status=\'Active\' AND mailbox_type != \'bounce\'' ); $GLOBALS ['log']->debug ( 'Just got Result from get all Inbounds of Inbound Emails' ); while ( $a = $ie->db->fetchByAssoc ( $r ) ) { $GLOBALS ['log']->debug ( 'In while loop of Inbound Emails' ); $ieX = new InboundEmail (); $ieX->retrieve ( $a ['id'] ); $mailboxes = $ieX->mailboxarray; foreach ( $mailboxes as $mbox ) { $ieX->mailbox = $mbox; $newMsgs = array (); $msgNoToUIDL = array (); $connectToMailServer = false; if ($ieX->isPop3Protocol ()) { $msgNoToUIDL = $ieX->getPop3NewMessagesToDownloadForCron (); // get all the keys which are msgnos; $newMsgs = array_keys ( $msgNoToUIDL ); } if ($ieX->connectMailserver () == 'true') { $connectToMailServer = true; } // if $GLOBALS ['log']->debug ( 'Trying to connect to mailserver for [ ' . $a ['name'] . ' ]' ); if ($connectToMailServer) { $GLOBALS ['log']->debug ( 'Connected to mailserver' ); if (! $ieX->isPop3Protocol ()) { $newMsgs = $ieX->getNewMessageIds (); } if (is_array ( $newMsgs )) { $current = 1; $total = count ( $newMsgs ); require_once ("include/SugarFolders/SugarFolders.php"); $sugarFolder = new SugarFolder (); $groupFolderId = $ieX->groupfolder_id; $isGroupFolderExists = false; $users = array (); if ($groupFolderId != null && $groupFolderId != "") { $sugarFolder->retrieve ( $groupFolderId ); $isGroupFolderExists = true; } // if $messagesToDelete = array (); if ($ieX->isMailBoxTypeCreateCase ()) { $users [] = $sugarFolder->assign_to_id; $distributionMethod = $ieX->get_stored_options ( "distrib_method", "" ); if ($distributionMethod != 'roundRobin') { $counts = $emailUI->getAssignedEmailsCountForUsers ( $users ); } else { $lastRobin = $emailUI->getLastRobin ( $ieX ); } $GLOBALS ['log']->debug ( 'distribution method id [ ' . $distributionMethod . ' ]' ); } foreach ( $newMsgs as $k => $msgNo ) { $uid = $msgNo; if ($ieX->isPop3Protocol ()) { $uid = $msgNoToUIDL [$msgNo]; } else { $uid = imap_uid ( $ieX->conn, $msgNo ); } // else if ($isGroupFolderExists) { if ($ieX->importOneEmail ( $msgNo, $uid )) { // add to folder $sugarFolder->addBean ( $ieX->email ); if ($ieX->isPop3Protocol ()) { $messagesToDelete [] = $msgNo; } else { $messagesToDelete [] = $uid; } if ($ieX->isMailBoxTypeCreateCase ()) { $userId = ""; if ($distributionMethod == 'roundRobin') { if (sizeof ( $users ) == 1) { $userId = $users [0]; $lastRobin = $users [0]; } else { $userIdsKeys = array_flip ( $users ); // now keys are values $thisRobinKey = $userIdsKeys [$lastRobin] + 1; if (! empty ( $users [$thisRobinKey] )) { $userId = $users [$thisRobinKey]; $lastRobin = $users [$thisRobinKey]; } else { $userId = $users [0]; $lastRobin = $users [0]; } } // else } else { if (sizeof ( $users ) == 1) { foreach ( $users as $k => $value ) { $userId = $value; } // foreach } else { asort ( $counts ); // lowest to highest $countsKeys = array_flip ( $counts ); // keys now the 'count of items' $leastBusy = array_shift ( $countsKeys ); // user id of lowest item count $userId = $leastBusy; $counts [$leastBusy] = $counts [$leastBusy] + 1; } } // else $GLOBALS ['log']->debug ( 'userId [ ' . $userId . ' ]' ); $ieX->handleCreateCase ( $ieX->email, $userId ); } // if } // if } else { if ($ieX->isAutoImport ()) { $ieX->importOneEmail ( $msgNo, $uid ); } else { /* * If the group folder doesn't exist then download only those messages * which has caseid in message */ $ieX->getMessagesInEmailCache ( $msgNo, $uid ); $email = new Email (); $header = imap_headerinfo ( $ieX->conn, $msgNo ); $email->name = $ieX->handleMimeHeaderDecode ( $header->subject ); $email->from_addr = $ieX->convertImapToSugarEmailAddress ( $header->from ); $email->reply_to_email = $ieX->convertImapToSugarEmailAddress ( $header->reply_to ); if (! empty ( $email->reply_to_email )) { $contactAddr = $email->reply_to_email; } else { $contactAddr = $email->from_addr; } $mailBoxType = $ieX->mailbox_type; $ieX->handleAutoresponse ( $email, $contactAddr ); } // else } // else $GLOBALS ['log']->debug ( '***** On message [ ' . $current . ' of ' . $total . ' ] *****' ); $current ++; } // foreach // update Inbound Account with last robin if ($ieX->isMailBoxTypeCreateCase () && $distributionMethod == 'roundRobin') { $emailUI->setLastRobin ( $ieX, $lastRobin ); } // if } // if if ($isGroupFolderExists) { $leaveMessagesOnMailServer = $ieX->get_stored_options ( "leaveMessagesOnMailServer", 0 ); if (! $leaveMessagesOnMailServer) { if ($ieX->isPop3Protocol ()) { $ieX->deleteMessageOnMailServerForPop3 ( implode ( ",", $messagesToDelete ) ); } else { $ieX->deleteMessageOnMailServer ( implode ( $app_strings ['LBL_EMAIL_DELIMITER'], $messagesToDelete ) ); } } } } else { $GLOBALS ['log']->fatal ( "SCHEDULERS: could not get an IMAP connection resource for ID [ {$a['id']} ]. Skipping mailbox [ {$a['name']} ]." ); // cn: bug 9171 - continue while } // else } // foreach imap_expunge ( $ieX->conn ); imap_close ( $ieX->conn, CL_EXPUNGE ); } // while return true; } /** * Job 2 */ function runMassEmailCampaign() { if (! class_exists ( 'LoggerManager' )) { } $GLOBALS ['log'] = LoggerManager::getLogger ( 'emailmandelivery' ); $GLOBALS ['log']->debug ( 'Called:runMassEmailCampaign' ); if (! class_exists ( 'DBManagerFactory' )) { require ('include/database/DBManagerFactory.php'); } global $beanList; global $beanFiles; require ("config.php"); require ('include/modules.php'); if (! class_exists ( 'AclController' )) { require ('modules/ACL/ACLController.php'); } require ('modules/EmailMan/EmailManDelivery.php'); return true; } /** * Job 3 */ function pruneDatabase() { $GLOBALS ['log']->info ( '----->Scheduler fired job of type pruneDatabase()' ); $backupDir = $GLOBALS ['sugar_config'] ['cache_dir'] . 'backups'; $backupFile = 'backup-pruneDatabase-GMT0_' . gmdate ( 'Y_m_d-H_i_s', strtotime ( 'now' ) ) . '.php'; $db = DBManagerFactory::getInstance (); $tables = $db->getTablesArray (); // _ppd($tables); if (! empty ( $tables )) { foreach ( $tables as $kTable => $table ) { // find tables with deleted=1 $qDel = 'SELECT * FROM ' . $table . ' WHERE deleted = 1'; $rDel = $db->query ( $qDel ); // OR continue; // continue if no 'deleted' column // make a backup INSERT query if we are deleting. while ( $aDel = $db->fetchByAssoc ( $rDel ) ) { // build column names $rCols = $db->query ( 'SHOW COLUMNS FROM ' . $table ); $colName = array (); while ( $aCols = $db->fetchByAssoc ( $rCols ) ) { $colName [] = $aCols ['Field']; } $query = 'INSERT INTO ' . $table . ' ('; $values = ''; foreach ( $colName as $kC => $column ) { $query .= $column . ', '; $values .= '"' . $aDel [$column] . '", '; } $query = substr ( $query, 0, (strlen ( $query ) - 2) ); $values = substr ( $values, 0, (strlen ( $values ) - 2) ); $query .= ') VALUES (' . str_replace ( "'", "'", $values ) . ');'; $queryString [] = $query; if (empty ( $colName )) { $GLOBALS ['log']->fatal ( 'pruneDatabase() could not get the columns for table (' . $table . ')' ); } } // end aDel while() // now do the actual delete $db->query ( 'DELETE FROM ' . $table . ' WHERE deleted = 1' ); } // foreach() tables // now output file with SQL if (! function_exists ( 'mkdir_recursive' )) { } if (! function_exists ( 'write_array_to_file' )) { } if (! file_exists ( $backupDir ) || ! file_exists ( $backupDir . '/' . $backupFile )) { // create directory if not existent mkdir_recursive ( $backupDir, false ); } // write cache file write_array_to_file ( 'pruneDatabase', $queryString, $backupDir . '/' . $backupFile ); return true; } return false; } // /** // * Job 4 // */ // function securityAudit() { // // do something // return true; // } function trimTracker() { global $sugar_config; $GLOBALS ['log']->info ( '----->Scheduler fired job of type trimTracker()' ); $db = DBManagerFactory::getInstance (); $admin = new Administration (); $admin->retrieveSettings ( 'tracker' ); require ('modules/Trackers/config.php'); $trackerConfig = $tracker_config; require_once ('include/utils/db_utils.php'); $prune_interval = ! empty ( $admin->settings ['tracker_prune_interval'] ) ? $admin->settings ['tracker_prune_interval'] : 30; foreach ( $trackerConfig as $tableName => $tableConfig ) { // Skip if table does not exist if (! $db->tableExists ( $tableName )) { continue; } $timeStamp = db_convert ( "'" . gmdate ( $GLOBALS ['timedate']->get_db_date_time_format (), time () + (86400 * - $prune_interval) ) . "'", "datetime" ); if ($tableName == 'tracker_sessions') { $query = "DELETE FROM $tableName WHERE date_end < $timeStamp"; } else { $query = "DELETE FROM $tableName WHERE date_modified < $timeStamp"; } $GLOBALS ['log']->info ( "----->Scheduler is about to trim the $tableName table by running the query $query" ); $db->query ( $query ); } // foreach return true; } /* * Job 5 * */ function pollMonitoredInboxesForBouncedCampaignEmails() { $GLOBALS ['log']->info ( '----->Scheduler job of type pollMonitoredInboxesForBouncedCampaignEmails()' ); global $dictionary; $ie = new InboundEmail (); $r = $ie->db->query ( 'SELECT id FROM inbound_email WHERE deleted=0 AND status=\'Active\' AND mailbox_type=\'bounce\'' ); while ( $a = $ie->db->fetchByAssoc ( $r ) ) { $ieX = new InboundEmail (); $ieX->retrieve ( $a ['id'] ); $ieX->connectMailserver (); $newMsgs = array (); if ($ieX->isPop3Protocol ()) { $newMsgs = $ieX->getPop3NewMessagesToDownload (); } else { $newMsgs = $ieX->getNewMessageIds (); } // $newMsgs = $ieX->getNewMessageIds(); if (is_array ( $newMsgs )) { foreach ( $newMsgs as $k => $msgNo ) { $uid = $msgNo; if ($ieX->isPop3Protocol ()) { $uid = $ieX->getUIDLForMessage ( $msgNo ); } else { $uid = imap_uid ( $ieX->conn, $msgNo ); } // else $ieX->importOneEmail ( $msgNo, $uid, false, false ); } } imap_expunge ( $ieX->conn ); imap_close ( $ieX->conn ); } return true; } function checkEDISales() { require_once ('modules/EcmSales/EcmSale.php'); require_once ('modules/EcmSales/readXML.php'); require_once 'include/phpMailer2/class.phpmailer.php'; require_once 'include/phpMailer2/class.smtp.php'; $path = '/var/edi/e5/orders'; $folders = array ( 'archive', 'temp', 'confirm' ); // do not read this folders $orders = array (); if (is_dir ( $path )) { if ($dh = opendir ( $path )) { while ( ($file = readdir ( $dh )) !== false ) { if (! is_dir ( $file ) && ! in_array ( $file, $folders )) { $orders [] = $file; } } } } // add orders $mail_msg = array (); foreach ( $orders as $order ) { $s = new EcmSale (); $reader = new readXML (); $reader->loadXMLFile ( $order ); $reader->loader ( $s ); $s->position_list = $reader->getPositionList ( true ); $missedProducts = $reader->checkProducts($s->position_list); $number = $s->generateNumber (); $s->number = $number; $s->document_no = $s->formatNumber ( $number ); $s->edi_file = $order; $s->type = 'sales_order'; $s->status = 's30'; $s->ecmlanguage = 'pl_pl'; $a = new Account (); $a->retrieve ( $s->parent_id ); $s->assigned_user_id = $a->assigned_user_id; $s->assigned_user_name = $a->assigned_user_name; // calculate totals $sum_netto = 0; $sum_brutto = 0; foreach ( $s->position_list as $p ) { $sum_netto += $p ['total_netto']; $sum_brutto += $p ['total_brutto']; } $s->total_netto = $sum_netto; if($s->parent_id==134 || $s->parent_id=='134'){ $s->shop_number = null; } $s->total_brutto = $sum_brutto; $s->save (); $s->sendSoap($s->id); if (!is_array($mail_msg [$a->assigned_user_id])) $mail_msg [$a->assigned_user_id] = array (); if (!$s->parent_name || $s->parent_name=="") $s->parent_name = 'Błąd! Brak kontrahenta!'; $msg = 'Plik: '.$order.'
'.$s->document_no.', '.$s->parent_document_no.', '. $s->parent_name.'
'; if (count($missedProducts) == 0) { $msg.='Status produktów: OK'; } else { $msg.='Zamówienie niekompletne: '.implode(', ', $missedProducts); } $msg.='


'; $mail_msg [$a->assigned_user_id][] = $msg; unset($a); // move files rename ( $path . '/' . $order, $path . '/archive/' . $order ); } //send messages // require_once 'modules/Schedulers/phpMailer.php'; foreach ( $mail_msg as $user=>$msg ) { $u = new User(); $u->retrieve($user); $message = $date = date('Y-m-d H:i:s').' dodano zamówienie(a):
'; foreach ($msg as $m) { $message .= $m.'
'; } $mail = new PHPMailer2 (); $mail->isSMTP(); $mail->setFrom('system@e5.pl', 'Usługa importu EDI'); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'system@e5.pl'; $mail->Password = 'eT4U>hyJe'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $mail->CharSet = 'UTF-8'; $mail->addAddress('mz@bim-it.pl', 'Michał Zieliński'); $mail->addAddress('rl@e5.pl', 'Ryszard Lisiecki'); $mail->addAddress('mf@e5.pl', 'Małgorzata Franiewska'); $mail->isHTML(true); $mail->Subject = "Import zamówienia EDI - E5" ; $mail->Body = $message; $mail->send(); unset ( $mS ); // cleaning } return true; } if (file_exists ( 'custom/modules/Schedulers/_AddJobsHere.php' )) { require ('custom/modules/Schedulers/_AddJobsHere.php'); } ?>