示例#1
1
 /**
  * @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 move($msg_index, $folder = 'INBOX.Processed')
 {
     // move on server
     imap_mail_move($this->conn, $msg_index, $folder);
     imap_expunge($this->conn);
     // re-read the inbox
     $this->inbox();
 }
 function move($uid, $folder)
 {
     $tries = 0;
     while ($tries++ < 3) {
         if (imap_mail_move($this->stream, $uid, $folder, CP_UID)) {
             imap_expunge($this->stream);
             return true;
         } else {
             sleep(1);
         }
     }
     return false;
 }
示例#4
0
 /**
  * Disconnects the current IMAP connection.
  */
 public function __destruct()
 {
     if ($this->ressource) {
         imap_expunge($this->ressource);
         imap_close($this->ressource);
     }
 }
示例#5
0
 /**
  * Close the connection to the mail server
  *
  * @param bool $empty_trash (default true) whether to empty the trash upon exit
  *
  */
 function Close($empty_trash = true)
 {
     if ($this->do_delete && $empty_trash) {
         imap_expunge($this->mbox);
     }
     imap_close($this->mbox);
 }
示例#6
0
function deleteMessages($messages)
{
    $mbox = getMbox();
    $messages = uidToSecuence($mbox, $messages);
    imap_delete($mbox, $messages);
    imap_expunge($mbox);
    imap_close($mbox);
}
示例#7
0
 public function delete($msg_index)
 {
     // move on server
     imap_delete($this->conn, $msg_index);
     imap_expunge($this->conn);
     // re-read the inbox
     $this->inbox();
 }
示例#8
0
 private static function _disconnect()
 {
     if (!self::$_conn) {
         return;
     }
     imap_expunge(self::$_conn);
     imap_close(self::$_conn);
     self::$_conn = null;
 }
示例#9
0
 private function disconnect()
 {
     if (!$this->handle) {
         return;
     }
     //deletes all mails marked for deletion
     imap_expunge($this->handle);
     imap_close($this->handle);
 }
示例#10
0
 public function deleteMessage($id)
 {
     $status = imap_setflag_full($this->mailbox, $id, '\\Deleted');
     imap_expunge($this->mailbox);
     header("Location: /");
     /* Redirect browser */
     /* Make sure that code below does not get executed when we redirect. */
     return $status;
 }
 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;
 }
 /**
  * Process emails by invoking of callback processing function.
  * @param $callback function Function which should be executed for every email. This function should take an Email object as a parameter and return boolean as a result of processing.
  * @param $senders list of comma-separated emails/names. This parameter is optional and is used to filter incoming mail by senders. false by default.
  * @param $should_delete boolean Optional parameter. If this parameter is true and callback function returned true, email will be deleted.
  */
 public function process($callback, $senders = false, $should_delete = false)
 {
     if ($senders) {
         $senders = split(",", $senders);
     }
     if (is_array($senders) && !empty($senders)) {
         foreach ($senders as $sender) {
             if ($sender == '') {
                 continue;
             }
             $this->_process('FROM "' . $sender . '"', $callback, $should_delete);
         }
     } else {
         $this->_process('ALL', $callback, $should_delete);
     }
     imap_expunge($this->connection);
 }
 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;
 }
示例#14
0
    while ($a = $ie->db->fetchByAssoc($r)) {
        $ieX = new InboundEmail();
        $ieX->retrieve($a['id']);
        $ieX->connectMailserver();
        //$newMsgs = $ieX->getNewMessageIds();
        $newMsgs = array();
        if ($ieX->isPop3Protocol()) {
            $newMsgs = $ieX->getPop3NewMessagesToDownload();
        } else {
            $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);
            }
        }
        imap_expunge($ieX->conn);
        imap_close($ieX->conn);
    }
    header('Location: index.php?module=Emails&action=ListViewGroup');
} else {
    // fail gracefully
    header('Location: index.php?module=Emails&action=index');
}
示例#15
0
 public function chamado_mail()
 {
     function mes($mes)
     {
         switch ($mes) {
             case 'Jan':
                 $mes = '01';
                 break;
             case 'Fev':
                 $mes = '02';
                 break;
             case 'Mar':
                 $mes = '03';
                 break;
             case 'Apr':
                 $mes = '04';
                 break;
             case 'May':
                 $mes = '05';
                 break;
             case 'Jun':
                 $mes = '06';
                 break;
             case 'Jul':
                 $mes = '07';
                 break;
             case 'Aug':
                 $mes = '08';
                 break;
             case 'Sep':
                 $mes = '09';
                 break;
             case 'Oct':
                 $mes = '10';
                 break;
             case 'Nov':
                 $mes = '11';
                 break;
             case 'Dec':
                 $mes = '12';
                 break;
         }
         return $mes;
     }
     global $controle_id_empresa, $controle_id_usuario;
     $servidor = "mail.cartoriopostal.com.br";
     $usuario = "*****@*****.**";
     $senha = "a123d321";
     @ini_set('display_errors', '0');
     $mbox = imap_open("{" . $servidor . ":143/novalidate-cert}INBOX", $usuario, $senha);
     $erro[] = imap_last_error();
     if ($erro[0] == "") {
         for ($i = 0; $i < imap_num_msg($mbox); $i++) {
             # **************************************************************
             date_default_timezone_set('America/Sao_Paulo');
             $headers = imap_header($mbox, $i);
             if ($controle_id_empresa == 1 && $controle_id_usuario == 1) {
                 print_r($mbox);
                 exit;
             }
             $email = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
             if (substr_count($email, 'cartoriopostal') > 0 || substr_count($email, 'softfox') > 0) {
                 #***************************************************************
                 $data = str_replace(' ', ',', $headers->date);
                 $data = explode(',', $data);
                 $mes = mes($data[3]);
                 $dia = $data[2] < 10 ? '0' . $data[2] : $data[2];
                 $data = $data[4] . ':' . $mes . ':' . $dia . ' ' . $data[5];
                 # **************************************************************
                 $usuario = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
                 $usuario = $this->f_usuario($usuario);
                 $usuario = count($usuario) == 0 ? 1 : $usuario[1];
                 # **************************************************************
                 $empresa = $headers->to[0]->mailbox . '@' . $headers->to[0]->host;
                 $empresa = $this->f_usuario($empresa);
                 $empresa = $empresa[0];
                 # **************************************************************
                 $h = "<b>De: </b>" . $headers->fromaddress . " [" . $headers->from[0]->mailbox . '@' . $headers->from[0]->host . "]<br />\n";
                 $h .= "<b>Para: </b>";
                 for ($c = 0; $c < count($headers->to); $c++) {
                     if (strlen($headers->to[$c]->personal) > 0) {
                         $h .= $headers->to[$c]->personal . " [" . $headers->to[$c]->mailbox . '@' . $headers->to[$c]->host . "]";
                     } else {
                         $h .= $headers->to[$c]->mailbox . '@' . $headers->to[$c]->host;
                     }
                     $h .= $c < count($headers->to) - 1 ? '; ' : '';
                 }
                 $h .= "<br />\n";
                 if (count($headers->cc) > 0) {
                     $h .= "<b>Cc: </b>";
                     for ($c = 0; $c < count($headers->cc); $c++) {
                         if (strlen($headers->cc[$c]->personal) > 0) {
                             $h .= $headers->cc[$c]->personal . " [" . $headers->cc[$c]->mailbox . '@' . $headers->cc[$c]->host . "]";
                         } else {
                             $h .= $headers->cc[$c]->mailbox . '@' . $headers->cc[$c]->host;
                         }
                         $h .= $c < count($headers->cc) - 1 ? '; ' : '';
                     }
                     $h .= "<br />\n";
                 }
                 $headers->subject = strip_tags($headers->subject);
                 #if($controle_id_empresa == 1 && $controle_id_usuario == 1){
                 if (substr_count($headers->subject, 'iso-8859-1') > 0) {
                     $subject = imap_mime_header_decode($headers->subject);
                     $headers->subject = $subject[0]->text;
                 }
                 #}
                 $h .= "<b>Enviada em: </b>" . $headers->date . "<br />\n";
                 $h .= "<b>Assunto: </b>" . $headers->subject . "<br /><br />\n\n";
                 $msg = imap_qprint(imap_body($mbox, $i));
                 $msg = strip_tags($msg);
                 if (substr_count($msg, 'Content-ID') > 0) {
                     $msg = explode("Content-ID", $msg);
                     $msg = explode("\n", $msg[0]);
                 } else {
                     $msg = explode("\n", $msg);
                 }
                 $mensagem = '';
                 for ($k = 0; $k < count($msg); $k++) {
                     $msg[$k] = str_replace('&nbsp;', ' ', $msg[$k]);
                     $msg[$k] = trim($msg[$k]);
                     if (strlen(trim($msg[$k])) > 0) {
                         $cont = $this->LimparLinha($msg[$k]);
                         if ($cont == 0 && strlen(trim($msg[$k])) > 0) {
                             if (substr_count($msg[$k], 'De: ') > 0) {
                                 if (substr_count($msg[$k], '@cartoriopostal.com.br') > 0 || substr_count($msg[$k], '@softfox.com.br') > 0 || substr_count($msg[$k], '@sistecart.com.br') > 0 || substr_count($msg[$k], '@seupetcomsobrenome.com.br') > 0 || substr_count($msg[$k], '@franchiseemporium.com.br') > 0) {
                                     $k = count($msg);
                                 } else {
                                     $mensagem .= $msg[$k] . "<br /><br />\n\n";
                                 }
                             } else {
                                 $mensagem .= $msg[$k] . "<br /><br />\n\n";
                             }
                         }
                     }
                 }
                 # **************************************************************
                 if (strlen($mensagem) > 0) {
                     #if($controle_id_empresa == 1 && $controle_id_usuario == 1){
                     $mensagem = $h . $mensagem;
                     $stt = substr_count(strtolower($headers->subject), '| aberto') == 0 || ubstr_count(strtolower($headers->subject), '|aberto') == 0 ? 1 : 0;
                     $headers->subject = str_replace('| aberto', '', $headers->subject);
                     $headers->subject = str_replace('|aberto', '', $headers->subject);
                     $headers->subject = str_replace('RES: ', '', $headers->subject);
                     $headers->subject = trim($headers->subject);
                     # **************************************************************
                     $this->sql = "SELECT c.* FROM vsites_chamado AS c WHERE \n\t\t\t\t\t\t\t\t(c.pergunta LIKE '%" . $headers->subject . "%') AND c.id_empresa = ? AND c.id_usuario = ?";
                     $this->values = array($empresa, $usuario);
                     $dt = $this->fetch();
                     if (count($dt) == 0) {
                         $this->fields = array('id_pedido', 'ordem', 'id_empresa', 'id_usuario', 'status', 'pergunta', 'resposta', 'data_cadastro', 'data_atualizacao', 'forma_atend');
                         $this->values = array('id_pedido' => 0, 'ordem' => 0, 'id_empresa' => $empresa, 'id_usuario' => $usuario, 'status' => $stt, 'pergunta' => $headers->subject, 'resposta' => $mensagem, 'data_cadastro' => $data, 'data_atualizacao' => $data, 'forma_atend' => 2);
                         if ($controle_id_empresa == 1 && $controle_id_usuario == 1) {
                             $dt = $this->insert();
                         } else {
                             $this->insert();
                             #comentar se precisar
                         }
                     } else {
                         if ($dt[0]->status == 0) {
                             $sql = 'UPDATE ' . $this->table . ' SET status=?, data_atualizacao=?, pergunta=?, resposta=? ';
                             $sql .= 'WHERE id_chamado = ?';
                             $this->sql = $sql;
                             $this->values = array($stt, date('Y-m-d H:i:s'), $headers->subject, $mensagem . $dt[0]->resposta, $dt[0]->id_chamado);
                             if ($controle_id_empresa == 1 && $controle_id_usuario == 1) {
                                 $dt = $this->exec();
                             } else {
                                 $this->exec();
                                 #comentar se precisar
                             }
                         }
                     }
                     #}
                 }
                 #echo $mensagem."\n\n\n";
             }
             if ($controle_id_empresa == 1 && $controle_id_usuario == 1) {
                 #$headers = imap_header($mbox, $i);
                 #$teste = imap_headerinfo($mbox, $i);
                 #print_r($teste); echo "\n\n";
                 print_r(imap_errors());
                 exit;
                 imap_delete($mbox, $i);
                 print_r(imap_errors());
                 echo $headers->message_id;
             }
         }
         if ($controle_id_empresa == 1 && $controle_id_usuario == 1) {
             imap_expunge($mbox);
         }
     }
     if ($controle_id_empresa == 1 && $controle_id_usuario == 1) {
         imap_close($mbox);
     }
 }
示例#16
0
 protected function check_mailbox()
 {
     imap_ping($this->conn);
     $count = imap_num_msg($this->conn);
     common_log(LOG_INFO, "Found {$count} messages");
     if ($count > 0) {
         $handler = new IMAPMailHandler();
         for ($i = 1; $i <= $count; $i++) {
             $rawmessage = imap_fetchheader($this->conn, $count, FT_PREFETCHTEXT) . imap_body($this->conn, $i);
             $handler->handle_message($rawmessage);
             imap_delete($this->conn, $i);
         }
         imap_expunge($this->conn);
         common_log(LOG_INFO, "Finished processing messages");
     }
     return $count;
 }
示例#17
0
 /**
  * Deletes all the mails marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().
  * @return bool
  */
 public function expungeDeletedMails()
 {
     return imap_expunge($this->getImapStream());
 }
示例#18
0
 function fetchEmails()
 {
     if (!$this->connect()) {
         return false;
     }
     $archiveFolder = $this->getArchiveFolder();
     $delete = $this->canDeleteEmails();
     $max = $this->getMaxFetch();
     $nummsgs = imap_num_msg($this->mbox);
     //echo "New Emails:  $nummsgs\n";
     $msgs = $errors = 0;
     for ($i = $nummsgs; $i > 0; $i--) {
         //process messages in reverse.
         if ($this->createTicket($i)) {
             imap_setflag_full($this->mbox, imap_uid($this->mbox, $i), "\\Seen", ST_UID);
             //IMAP only??
             if ((!$archiveFolder || !imap_mail_move($this->mbox, $i, $archiveFolder)) && $delete) {
                 imap_delete($this->mbox, $i);
             }
             $msgs++;
             $errors = 0;
             //We are only interested in consecutive errors.
         } else {
             $errors++;
         }
         if ($max && ($msgs >= $max || $errors > $max * 0.8)) {
             break;
         }
     }
     //Warn on excessive errors
     if ($errors > $msgs) {
         $warn = sprintf(_S('Excessive errors processing emails for %1$s/%2$s. Please manually check the inbox.'), $this->getHost(), $this->getUsername());
         $this->log($warn);
     }
     @imap_expunge($this->mbox);
     return $msgs;
 }
示例#19
0
 /**
  * Delete
  *
  * @created: 15.10.2008 18:35:38
  * @param type $var
  *
  */
 public function delete(&$model)
 {
     //    debug("ImapSource::delete({$model->id})");
     //    debug(func_get_args());
     //    die();
     if ($this->connected) {
         $id = $model->id;
         imap_delete($this->connection, $id);
         imap_expunge($this->connection);
         return true;
     }
     return false;
 }
示例#20
0
 /**
  * Constructor
  *
  * @param $mailgateID   ID of the mailgate
  * @param $display      display messages in MessageAfterRedirect or just return error (default 0=)
  *
  * @return if $display = false return messages result string
  **/
 function collect($mailgateID, $display = 0)
 {
     global $CFG_GLPI;
     if ($this->getFromDB($mailgateID)) {
         $this->mid = -1;
         $this->fetch_emails = 0;
         //Connect to the Mail Box
         $this->connect();
         $rejected = new NotImportedEmail();
         // Clean from previous collect (from GUI, cron already truncate the table)
         $rejected->deleteByCriteria(array('mailcollectors_id' => $this->fields['id']));
         if ($this->marubox) {
             // Get Total Number of Unread Email in mail box
             $tot = $this->getTotalMails();
             //Total Mails in Inbox Return integer value
             $error = 0;
             $refused = 0;
             $blacklisted = 0;
             for ($i = 1; $i <= $tot && $this->fetch_emails < $this->maxfetch_emails; $i++) {
                 $tkt = $this->buildTicket($i, array('mailgates_id' => $mailgateID, 'play_rules' => true));
                 toolbox::logdebug("tkt", $tkt);
                 //Indicates that the mail must be deleted from the mailbox
                 $delete_mail = false;
                 //If entity assigned, or email refused by rule, or no user and no supplier associated with the email
                 $user_condition = $CFG_GLPI["use_anonymous_helpdesk"] || isset($tkt['_users_id_requester']) && $tkt['_users_id_requester'] > 0 || isset($tkt['_supplier_email']) && $tkt['_supplier_email'];
                 $rejinput = array();
                 $rejinput['mailcollectors_id'] = $mailgateID;
                 if (!$tkt['_blacklisted']) {
                     $rejinput['from'] = $tkt['_head']['from'];
                     $rejinput['to'] = $tkt['_head']['to'];
                     $rejinput['users_id'] = $tkt['_users_id_requester'];
                     $rejinput['subject'] = $this->textCleaner($tkt['_head']['subject']);
                     $rejinput['messageid'] = $tkt['_head']['message_id'];
                 }
                 $rejinput['date'] = $_SESSION["glpi_currenttime"];
                 // Manage blacklisted emails
                 if (isset($tkt['_blacklisted']) && $tkt['_blacklisted']) {
                     $this->deleteMails($i, self::REFUSED_FOLDER);
                     $blacklisted++;
                     // entities_id set when new ticket / tickets_id when new followup
                 } else {
                     if ((isset($tkt['entities_id']) || isset($tkt['tickets_id'])) && $user_condition || isset($tkt['_refuse_email_no_response']) || isset($tkt['_refuse_email_with_response'])) {
                         if (isset($tkt['_refuse_email_with_response'])) {
                             $this->sendMailRefusedResponse($tkt['_head']['from'], $tkt['name']);
                             $delete_mail = self::REFUSED_FOLDER;
                             $refused++;
                         } else {
                             if (isset($tkt['_refuse_email_no_response'])) {
                                 $delete_mail = self::REFUSED_FOLDER;
                                 $refused++;
                             } else {
                                 if (isset($tkt['entities_id']) || isset($tkt['tickets_id'])) {
                                     // Is a mail responding of an already existing ticket ?
                                     if (isset($tkt['tickets_id'])) {
                                         $fup = new TicketFollowup();
                                         if ($fup->add($tkt)) {
                                             $delete_mail = self::ACCEPTED_FOLDER;
                                         } else {
                                             $error++;
                                             $rejinput['reason'] = NotImportedEmail::FAILED_INSERT;
                                             $rejected->add($rejinput);
                                         }
                                     } else {
                                         // New ticket
                                         $track = new Ticket();
                                         if ($track->add($tkt)) {
                                             $delete_mail = self::ACCEPTED_FOLDER;
                                         } else {
                                             $error++;
                                             $rejinput['reason'] = NotImportedEmail::FAILED_INSERT;
                                             $rejected->add($rejinput);
                                         }
                                     }
                                 } else {
                                     // Case never raise
                                     $delete_mail = self::REFUSED_FOLDER;
                                     $refused++;
                                 }
                             }
                         }
                         //Delete Mail from Mail box if ticket is added successfully
                         if ($delete_mail) {
                             $this->deleteMails($i, $delete_mail);
                         }
                     } else {
                         if (!$tkt['_users_id_requester']) {
                             $rejinput['reason'] = NotImportedEmail::USER_UNKNOWN;
                         } else {
                             $rejinput['reason'] = NotImportedEmail::MATCH_NO_RULE;
                         }
                         $rejected->add($rejinput);
                     }
                 }
                 $this->fetch_emails++;
             }
             imap_expunge($this->marubox);
             $this->close_mailbox();
             //Close Mail Box
             //TRANS: %1$d, %2$d, %3$d, %4$d and %5$d are number of messages
             $msg = sprintf(__('Number of messages: available=%1$d, retrieved=%2$d, refused=%3$d, errors=%4$d, blacklisted=%5$d'), $tot, $this->fetch_emails, $refused, $error, $blacklisted);
             if ($display) {
                 Session::addMessageAfterRedirect($msg, false, $error ? ERROR : INFO);
             } else {
                 return $msg;
             }
         } else {
             $msg = __('Could not connect to mailgate server');
             if ($display) {
                 Session::addMessageAfterRedirect($msg, false, ERROR);
             } else {
                 return $msg;
             }
         }
     } else {
         //TRANS: %s is the ID of the mailgate
         $msg = sprintf(__('Could not find mailgate %d'), $mailgateID);
         if ($display) {
             Session::addMessageAfterRedirect($msg, false, ERROR);
         } else {
             return $msg;
         }
     }
 }
                            # Add a non-confirmed row to the DB
                            $DB_Confirmed = "0";
                            $query = "INSERT INTO " . $infrespsubscribers . " (ResponderID, SentMsgs, EmailAddress, TimeJoined, Real_TimeJoined, CanReceiveHTML, LastActivity, FirstName, LastName, IP_Addy, ReferralSource, UniqueCode, Confirmed)\n\t\t\t\t\t\t\tVALUES('{$DB_ResponderID}','{$DB_SentMsgs}', '{$DB_EmailAddress}', '{$DB_TimeJoined}', '{$DB_Real_TimeJoined}', '{$CanReceiveHTML}', '{$DB_LastActivity}', '{$DB_FirstName}', '{$DB_LastName}', '{$DB_IPaddy}', '{$DB_ReferralSource}', '{$DB_UniqueCode}', '{$DB_Confirmed}')";
                            $DB_result = mysql_query($query) or die("Invalid query: " . mysql_error());
                            $DB_SubscriberID = mysql_insert_id();
                            # Send confirmation msg
                            SendMessageTemplate('templates/messages/subscribe.confirm.txt', $DB_EmailAddress, $ResponderInfo['FromEmail'], $DB_SubscriberID);
                        } else {
                            # Add a confirmed row to the DB
                            $DB_Confirmed = "1";
                            $query = "INSERT INTO " . $infrespsubscribers . " (ResponderID, SentMsgs, EmailAddress, TimeJoined, Real_TimeJoined, CanReceiveHTML, LastActivity, FirstName, LastName, IP_Addy, ReferralSource, UniqueCode, Confirmed)\n\t\t\t\t\t\t\tVALUES('{$DB_ResponderID}','{$DB_SentMsgs}', '{$DB_EmailAddress}', '{$DB_TimeJoined}', '{$DB_Real_TimeJoined}', '{$CanReceiveHTML}', '{$DB_LastActivity}', '{$DB_FirstName}', '{$DB_LastName}', '{$DB_IPaddy}', '{$DB_ReferralSource}', '{$DB_UniqueCode}', '{$DB_Confirmed}')";
                            $DB_result = mysql_query($query) or die("Invalid query: " . mysql_error());
                            $DB_SubscriberID = mysql_insert_id();
                            # Send welcome and notification
                            SendMessageTemplate('templates/messages/subscribe.complete.txt', $DB_EmailAddress, $ResponderInfo['FromEmail'], $DB_SubscriberID);
                            if ($DB_NotifyOnSub == "1") {
                                SendMessageTemplate('templates/messages/new_subscriber.notify.txt', $ResponderInfo['FromEmail'], $ResponderInfo['FromEmail']);
                            }
                        }
                    }
                }
                @imap_expunge($conn);
                @imap_close($conn);
            }
        }
    }
}
# Should we disconnect from the DB?
if ($included != TRUE) {
    DB_disconnect();
}
示例#22
0
 /**
  * Handles purging any files that are marked for deletion
  */
 function expungeMessages()
 {
     imap_expunge($this->_connection);
 }
 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);
 }
    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));
        }
    }
 /**
  * Disconnects this account from the imap resource		 * 
  */
 public function disconnect()
 {
     if (!$this->doesKeepEmails()) {
         imap_expunge($this->connection);
     }
     imap_close($this->_connection);
     $this->_connection = null;
 }
  /**
  * Delete marked messages 
  */ 
 function email_expunge(){
   
   imap_expunge($this->link);
 
 }
                }
            }
            #
            # End of category work stuff
        } else {
            echo '<p><strong>Level 0 users can\'t post.</strong></p>';
        }
        echo '</div>';
        if ($output_debugging_info) {
            ob_end_flush();
        } else {
            ob_end_clean();
        }
    }
    #Clean out the inbox by deleting emails marked for deletion
    imap_expunge($mbox);
}
#Global Function definitions (as from PHP.net), not used yet, will be used for multiple
#attachment parsing
function parse($structure)
{
    global $type;
    global $encoding;
    // create an array to hold message sections
    $ret = array();
    // split structure into parts
    $parts = $structure->parts;
    for ($x = 0; $x < sizeof($parts); $x++) {
        $ret[$x]["pid"] = $x + 1;
        $this = $parts[$x];
        // default to text
示例#28
0
 function deleteMessage($uid, $expunge = false)
 {
     imap_delete($this->_stream, $uid, FT_UID);
     if ($expunge) {
         imap_expunge($this->_stream);
         $this->cache->expire($this->getCurrentMailbox(), $this->cache->getMessageCacheID($uid));
     }
 }
 /**
  * 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} ]");
         }
     }
 }
示例#30
0
/**
 * Job 1
 */
function pollMonitoredInboxes()
{
    $_bck_up = array('team_id' => $GLOBALS['current_user']->team_id, 'team_set_id' => $GLOBALS['current_user']->team_set_id);
    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\'');
    Log::debug('Just got Result from get all Inbounds of Inbound Emails');
    while ($a = $ie->db->fetchByAssoc($r)) {
        Log::debug('In while loop of Inbound Emails');
        $ieX = new InboundEmail();
        $ieX->retrieve($a['id']);
        $GLOBALS['current_user']->team_id = $ieX->team_id;
        $GLOBALS['current_user']->team_set_id = $ieX->team_set_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
            Log::debug('Trying to connect to mailserver for [ ' . $a['name'] . ' ]');
            if ($connectToMailServer) {
                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);
                        }
                        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
                                    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
                        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 {
                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
    $GLOBALS['current_user']->team_id = $_bck_up['team_id'];
    $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id'];
    return true;
}