public function fetch($delete = false) { $oImap = imap_open('{' . $this->mail_server . ':993/imap/ssl/notls/novalidate-cert}', $this->username, $this->password); $oMailboxStatus = imap_check($oImap); $aMessages = imap_fetch_overview($oImap, "1:{$oMailboxStatus->Nmsgs}"); $validMessages = array(); foreach ($aMessages as $oMessage) { print "Trying message '" . $oMessage->subject . "'"; $fileContent = $fileType = ''; $geocoder = factory::create('geocoder'); $postCode = $geocoder->extract_postcode($oMessage->subject); $fromName = null; $fromEmail = null; if (strpos($oMessage->from, '<')) { $split = split('<', $oMessage->from); //name - make sure name not an email address $fromName = trim($split[0]); if (valid_email($fromName)) { $fromName = null; } //email $fromEmail = trim(str_replace('>', '', $split[1])); } else { $fromEmail = $oMessage->from; } $images = array(); $messageStructure = imap_fetchstructure($oImap, $oMessage->msgno); if (isset($messageStructure->parts)) { $partNumber = 0; foreach ($messageStructure->parts as $oPart) { $partNumber++; if ($oPart->subtype == 'PLAIN' && !$postCode) { $messageContent = imap_fetchbody($oImap, $oMessage->msgno, $partNumber); if ($oPart->encoding == 4) { $messageContent = quoted_printable_decode($messageContent); } $postCode = geocoder::extract_postcode($messageContent); } elseif ($oPart->encoding == 3 && in_array($oPart->subtype, array('JPEG', 'PNG'))) { $oImage = null; $encodedBody = imap_fetchbody($oImap, $oMessage->msgno, $partNumber); $fileContent = base64_decode($encodedBody); $oImage = imagecreatefromstring($fileContent); if (imagesx($oImage) > $this->min_import_size && imagesy($oImage) > $this->min_import_size) { array_push($images, $oImage); } $fileType = strtolower($oPart->subtype); } } } //add to the messages array array_push($validMessages, array('postcode' => $postCode, 'images' => $images, 'file_type' => $fileType, 'from_address' => $fromAddress, 'from_email' => $fromEmail, 'from_name' => $fromName)); if ($delete) { imap_delete($oImap, $oMessage->msgno); } } imap_close($oImap, CL_EXPUNGE); $this->messages = $validMessages; }
/** * tokens::bounceprocessing() * * @return void */ function bounceprocessing($iSurveyId) { $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { $clang->eT("No token table."); return; } $thissurvey = getSurveyInfo($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { $clang->eT("We are sorry but you don't have permissions to do this."); return; } if ($thissurvey['bounceprocessing'] != 'N' || $thissurvey['bounceprocessing'] == 'G' && getGlobalSetting('bounceaccounttype') != 'off') { if (!function_exists('imap_open')) { $clang->eT("The imap PHP library is not installed. Please contact your system administrator."); return; } $bouncetotal = 0; $checktotal = 0; if ($thissurvey['bounceprocessing'] == 'G') { $accounttype = strtoupper(getGlobalSetting('bounceaccounttype')); $hostname = getGlobalSetting('bounceaccounthost'); $username = getGlobalSetting('bounceaccountuser'); $pass = getGlobalSetting('bounceaccountpass'); $hostencryption = strtoupper(getGlobalSetting('bounceencryption')); } else { $accounttype = strtoupper($thissurvey['bounceaccounttype']); $hostname = $thissurvey['bounceaccounthost']; $username = $thissurvey['bounceaccountuser']; $pass = $thissurvey['bounceaccountpass']; $hostencryption = strtoupper($thissurvey['bounceaccountencryption']); } @(list($hostname, $port) = split(':', $hostname)); if (empty($port)) { if ($accounttype == "IMAP") { switch ($hostencryption) { case "OFF": $hostname = $hostname . ":143"; break; case "SSL": $hostname = $hostname . ":993"; break; case "TLS": $hostname = $hostname . ":993"; break; } } else { switch ($hostencryption) { case "OFF": $hostname = $hostname . ":110"; break; case "SSL": $hostname = $hostname . ":995"; break; case "TLS": $hostname = $hostname . ":995"; break; } } } else { $hostname = $hostname . ":" . $port; } $flags = ""; switch ($accounttype) { case "IMAP": $flags .= "/imap"; break; case "POP": $flags .= "/pop3"; break; } switch ($hostencryption) { case "OFF": $flags .= "/notls"; // Really Off break; case "SSL": $flags .= "/ssl/novalidate-cert"; break; case "TLS": $flags .= "/tls/novalidate-cert"; break; } if ($mbox = @imap_open('{' . $hostname . $flags . '}INBOX', $username, $pass)) { imap_errors(); $count = imap_num_msg($mbox); if ($count > 0) { $lasthinfo = imap_headerinfo($mbox, $count); $datelcu = strtotime($lasthinfo->date); $datelastbounce = $datelcu; $lastbounce = $thissurvey['bouncetime']; while ($datelcu > $lastbounce) { @($header = explode("\r\n", imap_body($mbox, $count, FT_PEEK))); // Don't mark messages as read foreach ($header as $item) { if (preg_match('/^X-surveyid/', $item)) { $iSurveyIdBounce = explode(": ", $item); } if (preg_match('/^X-tokenid/', $item)) { $tokenBounce = explode(": ", $item); if ($iSurveyId == $iSurveyIdBounce[1]) { $aData = array('emailstatus' => 'bounced'); $condn = array('token' => $tokenBounce[1]); $record = Token::model($iSurveyId)->findByAttributes($condn); if ($record->emailstatus != 'bounced') { $record->emailstatus = 'bounced'; $record->save(); $bouncetotal++; } $readbounce = imap_body($mbox, $count); // Put read if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) { $deletebounce = imap_delete($mbox, $count); // Put delete } } } } $count--; @($lasthinfo = imap_headerinfo($mbox, $count)); @($datelc = $lasthinfo->date); $datelcu = strtotime($datelc); $checktotal++; } } @imap_close($mbox); $condn = array('sid' => $iSurveyId); $survey = Survey::model()->findByAttributes($condn); $survey->bouncetime = $datelastbounce; $survey->save(); if ($bouncetotal > 0) { printf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal, $bouncetotal); } else { printf($clang->gT("%s messages were scanned, none were marked as bounce by the system."), $checktotal); } } else { $clang->eT("Please check your settings"); } } else { $clang->eT("Bounce processing is deactivated either application-wide or for this survey in particular."); return; } exit; // if bounceprocessing : javascript : no more todo }
/** * @param resource $imapConnection * @param array $messages * @param bool $clean * * @return bool Return <em>true</em> if <strong>all</strong> messages exist in the inbox. */ public function checkMessages($imapConnection, array $messages, $clean = true) { $bodies = array_map(function ($message) { return $message->getText() . "\r\n"; }, $messages); $host = $_ENV['AVISOTA_TEST_IMAP_HOST'] ?: getenv('AVISOTA_TEST_IMAP_HOST'); $hits = 0; for ($i = 0; $i < 30 && $hits < count($bodies); $i++) { // wait for the mail server sleep(2); imap_gc($imapConnection, IMAP_GC_ENV); $status = imap_status($imapConnection, '{' . $host . '}', SA_MESSAGES); for ($j = $status->messages; $j > 0; $j--) { $body = imap_body($imapConnection, $j); if (in_array($body, $bodies)) { $hits++; if ($clean) { imap_delete($imapConnection, $j); } } } imap_expunge($imapConnection); } return $hits; }
function emailListener() { $connection = establishConnection(); $dbConn = establishDBConnection(); $messagestatus = "UNSEEN"; $emails = imap_search($connection, $messagestatus); if ($emails) { rsort($emails); foreach ($emails as $email_number) { // echo "in email loop"; $header = imap_headerinfo($connection, $email_number); $message = imap_fetchbody($connection, $email_number, 1.1); if ($message == "") { $message = imap_fetchbody($connection, $email_number, 1); } $emailaddress = substr($header->senderaddress, stripos($header->senderaddress, "<") + 1, stripos($header->senderaddress, ">") - (stripos($header->senderaddress, ">") + 1)); if (!detectOOOmessage($header->subject, $message, $emailaddress)) { detectBIOmessage($header->subject, $emailaddress); } imap_delete($connection, 1); //this might bug out but should delete the top message that was just parsed } } $dbConn->query("DELETE FROM away_mentor WHERE tiStamp <= DATE_ADD(NOW(), INTERVAL -1 DAY) limit 1"); //delete mentors that have been away for more than 24 hours from the away list }
public function delete($token) { if (!$this->box) { return false; } imap_delete($this->box, $token); }
public function delete($msg_index) { // move on server imap_delete($this->conn, $msg_index); imap_expunge($this->conn); // re-read the inbox $this->inbox(); }
function delete($stream, $msg_num, $flags = 0) { // do we force use of msg UID's if ($this->force_msg_uids == True && !($flags & FT_UID)) { $flags |= FT_UID; } return imap_delete($stream, $msg_num, $flags); }
function deleteMessages($messages) { $mbox = getMbox(); $messages = uidToSecuence($mbox, $messages); imap_delete($mbox, $messages); imap_expunge($mbox); imap_close($mbox); }
/** * Deletes the letter from inbox * * @param integet/string $mid The number of letter in mailbox * * @return boolean */ public function deleteMail($mid, $uid = 0) { // TODO: Move this method to the Migur library. // It is not relayed to com_newsletter explicitly if (!empty($this->_mailbox_link)) { return @imap_delete($this->_mailbox_link, $mid, $uid); } return false; }
function deletemsgs($mbox, $first_msg_no, $last_msg_no) { if (imap_delete($mbox, "{$first_msg_no}:{$last_msg_no}")) { return true; } else { print imap_last_error() . "\n"; return false; } }
function delete($stream, $msg_num, $flags = 0) { // do we force use of msg UID's if ($this->force_msg_uids == True && !($flags & FT_UID)) { $flags |= FT_UID; } $retval = imap_delete($stream, $msg_num, $flags); // some lame pop3 servers need this extra call to expunge, but RFC says not necessary imap_expunge($stream); return $retval; }
private function _getMailList() { $mbox = imap_open(sprintf("{%s:%d/imap/ssl}INBOX", $this->_server, $this->_port), $this->_email, $this->_password); $mailList = imap_search($mbox, 'ALL'); $bodyList = array(); if (is_array($mailList)) { foreach ($mailList as $num) { $body = imap_fetchbody($mbox, $num, "1"); array_push($bodyList, $body); imap_delete($mbox, $num); } } return $bodyList; }
function purge_message($mailbox, $message) { if (isset($message['imap_uid'])) { if ($result = $this->open_mailbox($mailbox)) { if ($mailbox->settings['delete_after_read']) { imap_delete($result, $message['imap_uid'], FT_UID); } elseif (!isset($mailbox->settings['flag_after_read']) || $mailbox->settings['flag_after_read']) { imap_setflag_full($result, (string) $message['imap_uid'], '\\Seen', FT_UID); } $this->close_mailbox($result); } else { drupal_set_message(t('Unable to connect to mailbox.')); watchdog('mailhandler', 'Unable to connect to %mail', array('%mail' => $mailbox->mail), WATCHDOG_ERROR); } } }
function emailListener() { //$output = "<script>console.log( 'just got in' );</script>"; //echo $output; $connection = establishConnection(); $dbConn = establishDBConnection(); //$output = "<script>console.log( 'set up connection' );</script>"; //$dbConn->query("INSERT INTO away_mentor (userID, tiStamp) VALUES (99897, NOW())");//test the db connection //echo $output;//develop thread/loop $messagestatus = "UNSEEN"; $countTo24 = 0; while (true) { echo "in check loop"; $emails = imap_search($connection, $messagestatus); if ($emails) { rsort($emails); foreach ($emails as $email_number) { echo "in email loop"; $header = imap_headerinfo($connection, $email_number); $message = imap_fetchbody($connection, $email_number, 1.1); if ($message == "") { $message = imap_fetchbody($connection, $email_number, 1); } $emailaddress = substr($header->senderaddress, stripos($header->senderaddress, "<") + 1, stripos($header->senderaddress, ">") - (stripos($header->senderaddress, ">") + 1)); if (!detectOOOmessage($header->subject, $message, $emailaddress)) { detectB00message($header->subject, $emailaddress); } imap_delete($connection, 1); //this might bug out but should delete the top message that was just parsed } } sleep(600); //do check every 10 minutes $countTo24 = $countTo24 + 1; if ($countTo24 >= 144) { $countTo24 = 0; $dbConn->query("DELETE FROM away_mentor WHERE tiStamp <= DATE_ADD(CURRENT_DATE, INTERVAL -1 DAY)"); //delete mentors that have been away for more than 24 hours from the away list //$command = Yii::app()->db->createCommand(); // $command->delete('away_mentor', 'tiStamp <= DATE_ADD(CURRENT_DATE , INTERVAL -1 DAY )');//this might bug the hell out deletes mentors on the away list that were put on over 24 hours ago } if (!imap_ping($connection)) { $connection = establishConnection(); } } }
static function fetch($options) { if ($mbox = imap_open(sprintf('{%1$s:%2$s/%3$s}INBOX', $options['server'], $options['port'], implode('/', $options['settings'])), $options['user'], $options['pass'])) { $ret = array(); if (($messages = imap_num_msg($mbox)) > 0) { for ($message = 1; $message < $messages + 1; $message++) { $eml = imap_fetchheader($mbox, $message) . imap_body($mbox, $message); $data = array('Task' => array()); $email_data = LilTasksParseEmail::__parseEmailHeader($mbox, $message); $data['Task']['title'] = $email_data['subject']; $data['Task']['happened'] = strftime('%Y-%m-%d', strtotime($email_data['date'])); list($sender, $domain) = explode('@', $email_data['from']); if ($sender == 'today') { $data['Task']['deadline'] = strftime('%Y-%m-%d'); } else { if ($sender == 'tomorrow') { $data['Task']['deadline'] = strftime('%Y-%m-%d', time() + 24 * 60 * 60); } else { if (in_array(strtolower($sender), array('monday', 'tuesday', 'wednesday', 'thursday', 'saturday', 'sunday'))) { $data['Task']['deadline'] = strftime('%Y-%m-%d', strtotime('next ' . ucfirst($sender))); } } } $hash = sha1($data['Task']['happened'] . '_' . $email_data['subject']); $parts = array(); $data['Task']['descript'] = LilTasksParseEmail::__parseEmailBody($mbox, $message, $hash, $parts); file_put_contents(TMP . $hash . '.eml', $eml); $data['Attachment'][0] = array('model' => 'Task', 'filename' => array('name' => $hash . '.eml', 'tmp_name' => TMP . $hash . '.eml'), 'title' => 'SOURCE: ' . $data['Task']['title']); App::uses('Sanitize', 'Utility'); foreach ($parts as $part) { if (!empty($part['attachment'])) { $data['Attachment'][] = array('model' => 'Task', 'filename' => array('name' => Sanitize::paranoid($part['attachment']['filename']), 'tmp_name' => $part['attachment']['tmp']), 'title' => $part['attachment']['filename']); } } $ret[$message] = $data; imap_delete($mbox, $message); } } return $ret; imap_close($mbox, CL_EXPUNGE); } else { var_dump(imap_errors()); } }
public function getMessages($email) { $messages = []; foreach ($this->query(['to' => $email, 'on' => date('d F Y'), 'unseen' => false]) as $messageId) { $structure = imap_fetchstructure($this->connections[$email], $messageId); $encoding = isset($structure->parts) ? reset($structure->parts) : $structure; $message = imap_fetch_overview($this->connections[$email], $messageId); $message = reset($message); $processFunction = $this->detectProcessFunction($encoding->encoding); $message->subject = $processFunction($message->subject); $message->body = $this->getMessageBody($email, $messageId, $processFunction, reset($structure->parameters)); foreach (['from', 'to'] as $direction) { $address = imap_rfc822_parse_adrlist(imap_utf8($message->{$direction}), ''); $address = reset($address); $message->{$direction} = "{$address->mailbox}@{$address->host}"; } $messages[] = (array) $message; imap_delete($this->connections[$email], $messageId); } return $messages; }
function getdata($host, $login, $password, $savedirpath) { $this->savedDirPath = $savedirpath; $this->attachmenttype = array("text", "multipart", "message", "application", "audio", "image", "video", "other"); // create empty array to store message data $this->importedMessageDataArray = array(); // open the mailbox $mailbox = "{" . $host . ":143/imap/notls}INBOX"; $this->mbox = imap_open($mailbox, $login, $password); if ($this->mbox == FALSE) { return null; } $status = imap_status($this->mbox, $mailbox, SA_ALL); echo "Messages: ", $status->messages, "<BR>\n"; echo "Recent: ", $status->recent, "<BR>\n"; echo "Unseen: ", $status->unseen, "<BR>\n"; echo "UIDnext: ", $status->uidnext, "<BR>\n"; echo "UIDvalidity: ", $status->uidvalidity, "<BR>\n"; echo "Flags: ", $status->flags, "<BR>\n"; // now itterate through messages for ($mid = imap_num_msg($this->mbox); $mid >= 1; $mid--) { $header = imap_header($this->mbox, $mid); $this->importedMessageDataArray[$mid]["subject"] = property_exists($header, 'subject') ? $header->subject : ""; $this->importedMessageDataArray[$mid]["fromaddress"] = property_exists($header, 'fromaddress') ? $header->fromaddress : ""; $this->importedMessageDataArray[$mid]["date"] = property_exists($header, 'date') ? $header->date : ""; $this->importedMessageDataArray[$mid]["body"] = ""; $this->structureObject = imap_fetchstructure($this->mbox, $mid); $this->saveAttachments($mid); $this->getBody($mid); imap_delete($this->mbox, $mid); //imap_delete tags a message for deletion } // for multiple messages imap_expunge($this->mbox); // imap_expunge deletes all tagged messages imap_close($this->mbox); // now send the data to the server $this->exportEntries(); return $this->importedMessageDataArray; }
public function delete($Model, $conditions = null) { $query = compact('conditions'); $searchCriteria = $this->_makeSearch($Model, $query); $uids = $this->_uidsByCriteria($searchCriteria); if ($uids === false) { $uids = $Model->find('list', $query); } // Nothing was found if (empty($uids)) { return false; } $success = true; foreach ($uids as $uid) { if (!imap_delete($this->Stream, $uid, FT_UID)) { $this->err($Model, 'Unable to delete email with uid: %s', $uid); $success = false; } } return $success; }
public function del($id) { imap_delete($this->inbox, $id); }
<?php require_once dirname(__FILE__) . '/imap_include.inc'; $stream_id = setup_test_mailbox('', 1); imap_delete($stream_id, 1); var_dump(imap_undelete($stream_id, 1)); imap_close($stream_id); require_once 'clean.inc';
public function undeleteMessage($imap, $email_number) { print_r(imap_delete($imap, $email_number)); }
/** * Move message to another mailbox * * @param integer $msgno Message number to move * @param string $mbox Mailbox to move message to * @return boolean */ function move($msgno, $mbox) { // Only imap supports moving of mesages if ($server_type == "imap") { $list = imap_list($this->conn, $this->server, "*"); if (!in_array($mbox, $list)) { if (!imap_createmailbox($this->conn, imap_utf7_encode($this->server . $mbox))) { // $_ENV['api']['sys']->log("Creation of $mbox mailbox failed!","mailer"); } } return imap_mail_move($this->conn, $msgno, $mbox); } else { return imap_delete($this->conn, $msgno); } }
/** * deletes and expunges emails on server * @param string $uid UID(s), comma delimited, of email(s) on server */ function deleteMessageOnMailServerForPop3($uid) { if (imap_delete($this->conn, $uid)) { if (!imap_expunge($this->conn)) { $GLOBALS['log']->debug("NOOP: could not expunge deleted email."); $return = false; } else { $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]"); } } }
sleep($sleep_after_edit); } $blog_ID = 1; if ($flat < 500) { pingGeoUrl($post_ID); } // HACK HACK HACK this next line is commented out because I don't know what the word-press replacement // is. right now it's undefined and does not work //rss_update($blog_ID); pingWeblogs($blog_ID); // pingCafelog($cafelogID, $post_title, $post_ID); pingBlogs($blog_ID); pingback($content, $post_ID); #delete successful email, mark for deletion actually if ($result > 0) { imap_delete($mbox, $iCount); echo "deleted successfully"; } else { die("error deleting message"); } } echo "\n<p><b>Posted title:</b> {$post_title}<br />"; echo "\n<b>Posted content:</b><br /><pre>" . $content . '</pre></p>'; # Added to make category work # if (!$post_categories) { $post_categories[] = 1; } foreach ($post_categories as $post_category) { // Double check it's not there already $exists = $wpdb->get_row("SELECT * FROM {$tablepost2cat} WHERE post_id = {$post_ID} AND category_id = {$post_category}");
/** * Marks a message for deletion */ function deleteMessage($index) { imap_delete($this->_connection, $index); }
function sifre_degistir() { error_reporting(0); $mail_sunucusu = $this->sistemSabit['mail_sunucusu']; $mail_kull_adi = $this->sistemSabit['mail_kull_adi']; $mail_sifresi = $this->sistemSabit['mail_sifresi']; $imapBag = imap_open('{mail.' . $mail_sunucusu . ':143/notls}INBOX', $mail_kull_adi, $mail_sifresi); $mailler = imap_search($imapBag, 'SUBJECT "Sifre Degistir"'); foreach ($mailler as $mail) { $bilgiler = imap_fetchbody($imapBag, $mail, 1); $bilgi = explode('@*@', $bilgiler); $kullaniciAdi = str_replace(array(' ', "\n", "\r", "\t"), '', $bilgi[0]); $sifre = str_replace(array(' ', "\n", "\r", "\t"), '', $bilgi[1]); $this->load->model('kullanici_model'); $this->kullanici_model->sifre_degistir($kullaniciAdi, $sifre); echo '"' . $kullaniciAdi . '" - "' . $sifre . '"'; imap_delete($imapBag, $mail); } imap_expunge($imapBag); imap_close($imapBag); }
/** * Takes an email object and looks up details for this particular email * Returns the primary body and the mime type * Sets the message for deletion when chosen to do not keep emails * * @param stdObject $email * @return TBGIncomingEmailMessage the message */ public function getMessage($email) { $message = new TBGIncomingEmailMessage($this->_connection, $email->msgno); $is_structure = $message->fetch(); if ($is_structure && !$this->doesKeepEmails()) { imap_delete($this->_connection, $email->msgno); } return $message; }
/** * Delete a message * @param int message number */ public function delete_message($msg_no) { imap_delete($this->imap_stream, $msg_no); }
public function ajaxProcessSyncImap() { if ($this->tabAccess['edit'] != '1') { throw new PrestaShopException(Tools::displayError('You do not have permission to edit this.')); } if (Tools::isSubmit('syncImapMail')) { if (!($url = Configuration::get('PS_SAV_IMAP_URL')) || !($port = Configuration::get('PS_SAV_IMAP_PORT')) || !($user = Configuration::get('PS_SAV_IMAP_USER')) || !($password = Configuration::get('PS_SAV_IMAP_PWD'))) { die('{"hasError" : true, "errors" : ["Configuration is not correct"]}'); } $conf = Configuration::getMultiple(array('PS_SAV_IMAP_OPT_NORSH', 'PS_SAV_IMAP_OPT_SSL', 'PS_SAV_IMAP_OPT_VALIDATE-CERT', 'PS_SAV_IMAP_OPT_NOVALIDATE-CERT', 'PS_SAV_IMAP_OPT_TLS', 'PS_SAV_IMAP_OPT_NOTLS')); $conf_str = ''; if ($conf['PS_SAV_IMAP_OPT_NORSH']) { $conf_str .= '/norsh'; } if ($conf['PS_SAV_IMAP_OPT_SSL']) { $conf_str .= '/ssl'; } if ($conf['PS_SAV_IMAP_OPT_VALIDATE-CERT']) { $conf_str .= '/validate-cert'; } if ($conf['PS_SAV_IMAP_OPT_NOVALIDATE-CERT']) { $conf_str .= '/novalidate-cert'; } if ($conf['PS_SAV_IMAP_OPT_TLS']) { $conf_str .= '/tls'; } if ($conf['PS_SAV_IMAP_OPT_NOTLS']) { $conf_str .= '/notls'; } if (!function_exists('imap_open')) { die('{"hasError" : true, "errors" : ["imap is not installed on this server"]}'); } $mbox = @imap_open('{' . $url . ':' . $port . $conf_str . '}', $user, $password); //checks if there is no error when connecting imap server $errors = array_unique(imap_errors()); $str_errors = ''; $str_error_delete = ''; if (sizeof($errors) && is_array($errors)) { $str_errors = ''; foreach ($errors as $error) { $str_errors .= $error . ', '; } $str_errors = rtrim(trim($str_errors), ','); } //checks if imap connexion is active if (!$mbox) { $array = array('hasError' => true, 'errors' => array('Cannot connect to the mailbox :<br />' . $str_errors)); die(Tools::jsonEncode($array)); } //Returns information about the current mailbox. Returns FALSE on failure. $check = imap_check($mbox); if (!$check) { die('{"hasError" : true, "errors" : ["Fail to get information about the current mailbox"]}'); } if ($check->Nmsgs == 0) { die('{"hasError" : true, "errors" : ["NO message to sync"]}'); } $result = imap_fetch_overview($mbox, "1:{$check->Nmsgs}", 0); foreach ($result as $overview) { //check if message exist in database if (isset($overview->subject)) { $subject = $overview->subject; } else { $subject = ''; } //Creating an md5 to check if message has been allready processed $md5 = md5($overview->date . $overview->from . $subject . $overview->msgno); $exist = Db::getInstance()->getValue('SELECT `md5_header` FROM `' . _DB_PREFIX_ . 'customer_message_sync_imap` WHERE `md5_header` = \'' . pSQL($md5) . '\''); if ($exist) { if (Configuration::get('PS_SAV_IMAP_DELETE_MSG')) { if (!imap_delete($mbox, $overview->msgno)) { $str_error_delete = ', Fail to delete message'; } } } else { //check if subject has id_order preg_match('/\\#ct([0-9]*)/', $subject, $matches1); preg_match('/\\#tc([0-9-a-z-A-Z]*)/', $subject, $matches2); $matchFound = false; if (isset($matches1[1]) && isset($matches2[1])) { $matchFound = true; } $new_ct = Configuration::get('PS_SAV_IMAP_CREATE_THREADS') && !$matchFound && strpos($subject, '[no_sync]') == false; if ($matchFound || $new_ct) { if ($new_ct) { if (!preg_match('/<(' . Tools::cleanNonUnicodeSupport('[a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z\\p{L}0-9]+[._a-z\\p{L}0-9-]*\\.[a-z0-9]+') . ')>/', $overview->from, $result) || !Validate::isEmail($from = $result[1])) { continue; } // we want to assign unrecognized mails to the right contact category $contacts = Contact::getContacts($this->context->language->id); if (!$contacts) { continue; } foreach ($contacts as $contact) { if (strpos($overview->to, $contact['email']) !== false) { $id_contact = $contact['id_contact']; } } if (!isset($id_contact)) { // if not use the default contact category $id_contact = $contacts[0]['id_contact']; } $customer = new Customer(); $client = $customer->getByEmail($from); //check if we already have a customer with this email $ct = new CustomerThread(); if (isset($client->id)) { //if mail is owned by a customer assign to him $ct->id_customer = $client->id; } $ct->email = $from; $ct->id_contact = $id_contact; $ct->id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $ct->id_shop = $this->context->shop->id; //new customer threads for unrecognized mails are not shown without shop id $ct->status = 'open'; $ct->token = Tools::passwdGen(12); $ct->add(); } else { $ct = new CustomerThread((int) $matches1[1]); } //check if order exist in database if (Validate::isLoadedObject($ct) && (isset($matches2[1]) && $ct->token == $matches2[1] || $new_ct)) { $message = imap_fetchbody($mbox, $overview->msgno, 1); $message = quoted_printable_decode($message); $message = utf8_encode($message); $message = quoted_printable_decode($message); $message = nl2br($message); $cm = new CustomerMessage(); $cm->id_customer_thread = $ct->id; $cm->message = $message; $cm->add(); } } Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customer_message_sync_imap` (`md5_header`) VALUES (\'' . pSQL($md5) . '\')'); } } imap_expunge($mbox); imap_close($mbox); $array = array('hasError' => false, 'errors' => array($str_errors . $str_error_delete)); die(Tools::jsonEncode($array)); } }
/** * Gets the mail from the inbox * Reads all the messages there, and adds posts based on them. Then it deletes the entire mailbox. */ function getMail() { $config = Config::current(); if (time() - 60 * $config->emailblog_minutes >= $config->emailblog_mail_checked) { $hostname = '{' . $config->emailblog_server . '}INBOX'; # this isn't working well on localhost $username = $config->emailblog_address; $password = $config->emailblog_pass; $subjpass = $config->emailblog_subjpass; $inbox = imap_open($hostname, $username, $password) or exit("Cannot connect to Gmail: " . imap_last_error()); $emails = imap_search($inbox, 'SUBJECT "' . $subjpass . '"'); if ($emails) { rsort($emails); foreach ($emails as $email_number) { $message = imap_body($inbox, $email_number); $overview = imap_headerinfo($inbox, $email_number); imap_delete($inbox, $email_number); $title = htmlspecialchars($overview->Subject); $title = preg_replace($subjpass, "", $title); $clean = strtolower($title); $body = htmlspecialchars($message); # The subject of the email is used as the post title # the content of the email is used as the body # not sure about compatibility with images or audio feathers Post::add(array("title" => $title, "body" => $message), $clean, Post::check_url($clean), "text"); } } # close the connection imap_close($inbox, CL_EXPUNGE); $config->set("emailblog_mail_checked", time()); } }