/**
	 * Recupera o conteúdo de uma mensagem
	 * @param	MailContext $context Contexto da conexão
	 * @param	Message $message
	 * @return	Message A própria mensagem
	 * @throws	MailStateException Caso o estado do objeto não implemente abertura
	 * @throws	MailException Caso não seja possível recuperar o conteúdo da mensagem
	 */
	public function fetch( MailContext $context , Message $message ) {
		$msgNum = imap_msgno( ImapState::$resource , $message->getUID() );

		$structure = imap_fetchstructure( ImapState::$resource , $msgNum );
		$overview = (array) current( imap_fetch_overview( ImapState::$resource , $msgNum ) );

		$message->setHeaders( imap_fetchheader( ImapState::$resource , $msgNum ) );
		$message->setOverview( $overview );

		if ( isset( $structure->parts ) && count( $structure->parts ) ) {
			foreach ( $structure->parts as $key => $part ) {
				$this->fetchContent( $message , $part->subtype , $msgNum , $key + 1 );
			}
		} else {
			$this->fetchContent( $message , $structure->subtype , $msgNum , 1 );
		}
	}
 /**
  * Open mail from Imap and parse structure
  * @license   http://www.gnu.org/copyleft/gpl.html GPL
  * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
  * @return string  menssagem
  */
 public function setStructureFromMail($folder, $msgNumber)
 {
     $this->folder = mb_convert_encoding($folder, 'UTF7-IMAP', mb_detect_encoding($folder . 'x', 'UTF-8, ISO-8859-1'));
     $this->msgNumber = $msgNumber;
     $this->username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
     $this->password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
     $this->imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
     $this->imap_port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
     $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
     $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] : str_replace("*", "", $this->functions->getLang("Sent"));
     $this->has_cid = false;
     if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes') {
         $this->imap_options = '/tls/novalidate-cert';
     } else {
         $this->imap_options = '/notls/novalidate-cert';
     }
     $this->mbox = @imap_open("{" . $this->imap_server . ":" . $this->imap_port . $this->imap_options . "}" . $this->folder, $this->username, $this->password) or die('Error');
     $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $this->msgNumber), 80, 255);
     $this->messageId = $header->message_id;
     $rawMessageData = $this->_getRaw();
     $decoder = new Mail_mimeDecode($rawMessageData);
     $this->structure = $decoder->decode($this->decodeConf);
     //TODO: Descartar código após atualização do módulo de segurança da SERPRO
     if ($this->isSignedMenssage()) {
         $this->convertSignedMenssage($rawMessageData);
     }
     //////////////////////////////////////////////////////
     /*
      * Clean memory and close imap connection
      */
     $rawMessageData = null;
     $decoder = null;
     @imap_close($this->mbox);
     //-----------------------------------------//
 }
Beispiel #3
0
 public function getAllMessages($imap, $dsn)
 {
     $status = imap_status($imap, $dsn, SA_ALL);
     $msgs = imap_sort($imap, SORTDATE, 1, SE_UID);
     foreach ($msgs as $msguid) {
         $msgno = imap_msgno($imap, $msguid);
         $messages[$msgno] = imap_headerinfo($imap, $msgno);
     }
     return $messages;
 }
 function header($stream, $msg_nr, $fromlength = 0, $tolength = 0, $defaulthost = '')
 {
     // do we need to temporarily switch to regular msg num sequence for this function?
     if ($this->force_msg_uids == True) {
         // this function can nothandle UIDs, switch to sequence number
         $new_msg_nr = imap_msgno($stream, $msg_nr);
         if ($new_msg_nr) {
             $msg_nr = $new_msg_nr;
         }
     }
     return imap_header($stream, $msg_nr, $fromlength, $tolength, $defaulthost);
 }
Beispiel #5
0
function imap_get_url($u)
{
    if (!($c = imap_open_url($u))) {
        return FALSE;
    }
    extract(parse_url($u));
    extract(imap_parse_path($path));
    if ($mailbox) {
        if ($uid) {
            $msgno = imap_msgno($c, $uid);
            $o = imap_fetchstructure($c, $msgno);
        } else {
            $o = array();
            $n = imap_num_msg($c);
            while ($i++ < $n) {
                $o[] = imap_fetchheader($c, $i);
            }
        }
    } else {
        $o = imap_list($c, '{}', '*');
    }
    return $o;
}
Beispiel #6
0
             $status = $ie->importOneEmail($ie->getCorrectMessageNoForPop3($msgNo), $uid);
         }
         // else
         $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($status ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
         $count++;
         if ($_REQUEST['delete'] == 'true' && $status && ($current_user->is_admin == 1 || $ie->group_id == $current_user->id)) {
             $ie->deleteMessageOnMailServer($uid);
             $ie->deleteMessageFromCache($uid);
         }
         // if
     }
     // for
 } else {
     $msgNo = $_REQUEST['uid'];
     if ($ie->protocol == 'imap') {
         $msgNo = imap_msgno($ie->conn, $_REQUEST['uid']);
         $status = $ie->importOneEmail($msgNo, $_REQUEST['uid']);
     } else {
         $status = $ie->importOneEmail($ie->getCorrectMessageNoForPop3($msgNo), $_REQUEST['uid']);
     }
     // else
     $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($status ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
     if ($_REQUEST['delete'] == 'true' && $status && ($current_user->is_admin == 1 || $ie->group_id == $current_user->id)) {
         $ie->deleteMessageOnMailServer($_REQUEST['uid']);
         $ie->deleteMessageFromCache($_REQUEST['uid']);
     }
     // if
 }
 // else
 echo $json->encode($return);
 break;
Beispiel #7
0
 function saveAttachment($uid, $partNum, $encoding)
 {
     $partStruct = imap_bodystruct($this->stream, imap_msgno($this->stream, $uid), $partNum);
     $message = imap_fetchbody($this->stream, $uid, $partNum, FT_UID);
     switch ($encoding) {
         case 0:
         case 1:
             $message = imap_8bit($message);
             break;
         case 2:
             $message = imap_binary($message);
             break;
         case 3:
             $message = imap_base64($message);
             break;
         case 4:
             $message = quoted_printable_decode($message);
             break;
     }
     return $message;
 }
Beispiel #8
0
<?php

$emailAddress = '*****@*****.**';
$password = '******';
$server = 'localhost';
$folder = 'Inbox';
$dsn = sprintf('{%s}%s', $server, $folder);
$mbox = imap_open($dsn, $emailAddress, $password);
if (!$mbox) {
    die('Unable to connect');
}
$status = imap_status($mbox, $dsn, SA_ALL);
$msgs = imap_sort($mbox, SORTDATE, 1, SE_UID);
foreach ($msgs as $msguid) {
    $msgno = imap_msgno($mbox, $msguid);
    $headers = imap_headerinfo($mbox, $msgno);
    $structure = imap_fetchstructure($mbox, $msguid, FT_UID);
    var_dump($headers);
    var_dump($structure);
}
Beispiel #9
0
 /**
  * return content of messages attachment
  *
  * @return binary attachment
  * @param $id of the message
  * @param $index of the attachment (default: first attachment)
  */
 public function getAttachment($id, $index = 0)
 {
     // find message
     $attachments = false;
     $messageIndex = imap_msgno($this->imap, $id);
     $header = imap_headerinfo($this->imap, $messageIndex);
     $mailStruct = imap_fetchstructure($this->imap, $messageIndex);
     $attachments = $this->getAttachments($this->imap, $messageIndex, $mailStruct, "");
     if ($attachments == false) {
         return false;
     }
     // find attachment
     if ($index > count($attachments)) {
         return false;
     }
     $attachment = $attachments[$index];
     // get attachment body
     $partStruct = imap_bodystruct($this->imap, imap_msgno($this->imap, $id), $attachment['partNum']);
     $filename = $partStruct->dparameters[0]->value;
     $message = imap_fetchbody($this->imap, $id, $attachment['partNum'], FT_UID);
     switch ($attachment['enc']) {
         case 0:
         case 1:
             $message = imap_8bit($message);
             break;
         case 2:
             $message = imap_binary($message);
             break;
         case 3:
             $message = imap_base64($message);
             break;
         case 4:
             $message = quoted_printable_decode($message);
             break;
     }
     return array("name" => $attachment['name'], "size" => $attachment['size'], "content" => $message);
 }
 /**
  * get the basic details like sender and reciver with flags like attatchments etc
  *
  * @param int $uid the number of the message
  * @return array empty on error/nothing or array of formatted details
  */
 protected function _getFormattedMail($Model, $uid, $fetchAttachments = false)
 {
     // Translate uid to msg_no. Has no decent fail
     $msg_number = imap_msgno($this->Stream, $uid);
     // A hack to detect if imap_msgno failed, and we're in fact looking at the wrong mail
     if ($uid != ($mailuid = imap_uid($this->Stream, $msg_number))) {
         pr(compact('Mail'));
         return $this->err($Model, 'Mail id mismatch. parameter id: %s vs mail id: %s', $uid, $mailuid);
     }
     // Get Mail with a property: 'date' or fail
     if (!($Mail = imap_headerinfo($this->Stream, $msg_number)) || !property_exists($Mail, 'date')) {
         pr(compact('Mail'));
         return $this->err($Model, 'Unable to find mail date property in Mail corresponding with uid: %s. Something must be wrong', $uid);
     }
     // Get Mail with a property: 'type' or fail
     if (!($flatStructure = $this->_flatStructure($Model, $uid))) {
         return $this->err($Model, 'Unable to find structure type property in Mail corresponding with uid: %s. Something must be wrong', $uid);
     }
     $plain = $this->_fetchFirstByMime($flatStructure, 'text/plain');
     $html = $this->_fetchFirstByMime($flatStructure, 'text/html');
     $return[$Model->alias] = array('id' => $this->_toId($uid), 'message_id' => $Mail->message_id, 'email_number' => $Mail->Msgno, 'to' => $this->_personId($Mail, 'to', 'address'), 'to_name' => $this->_personId($Mail, 'to', 'name'), 'from' => $this->_personId($Mail, 'from', 'address'), 'from_name' => $this->_personId($Mail, 'from', 'name'), 'reply_to' => $this->_personId($Mail, 'reply_to', 'address'), 'reply_to_name' => $this->_personId($Mail, 'reply_to', 'name'), 'sender' => $this->_personId($Mail, 'sender', 'address'), 'sender_name' => $this->_personId($Mail, 'sender', 'name'), 'subject' => htmlspecialchars(@$Mail->subject), 'slug' => Inflector::slug(@$Mail->subject, '-'), 'header' => @imap_fetchheader($this->Stream, $uid, FT_UID), 'body' => $html, 'plainmsg' => $plain ? $plain : $html, 'size' => @$Mail->Size, 'recent' => @$Mail->Recent === 'R' ? 1 : 0, 'seen' => @$Mail->Unseen === 'U' ? 0 : 1, 'flagged' => @$Mail->Flagged === 'F' ? 1 : 0, 'answered' => @$Mail->Answered === 'A' ? 1 : 0, 'draft' => @$Mail->Draft === 'X' ? 1 : 0, 'deleted' => @$Mail->Deleted === 'D' ? 1 : 0, 'thread_count' => $this->_getThreadCount($Mail), 'in_reply_to' => @$Mail->in_reply_to, 'reference' => @$Mail->references, 'new' => (int) @$Mail->in_reply_to, 'created' => date('Y-m-d H:i:s', strtotime($Mail->date)));
     if ($fetchAttachments) {
         $return['Attachment'] = $this->_fetchAttachments($flatStructure, $Model);
     }
     // Auto mark after read
     if (!empty($this->config['auto_mark_as'])) {
         $marks = '\\' . join(' \\', $this->config['auto_mark_as']);
         if (!imap_setflag_full($this->Stream, $uid, $marks, ST_UID)) {
             $this->err($Model, 'Unable to mark email %s as %s', $uid, $marks);
         }
     }
     return $return;
 }
Beispiel #11
0
 function doAssignment($distributeMethod, $ieid, $folder, $uids, $users)
 {
     global $app_strings;
     $users = explode(",", $users);
     $emailIds = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
     $out = "";
     if ($folder != 'sugar::Emails') {
         $emailIds = array();
         $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
         $ie = new InboundEmail();
         $ie->retrieve($ieid);
         $messageIndex = 1;
         // dealing with an inbound email data so we need to import an email and then
         foreach ($uids as $uid) {
             $ie->mailbox = $folder;
             $ie->connectMailserver();
             $msgNo = $uid;
             if (!$ie->isPop3Protocol()) {
                 $msgNo = imap_msgno($ie->conn, $uid);
             } else {
                 $msgNo = $ie->getCorrectMessageNoForPop3($uid);
             }
             if (!empty($msgNo)) {
                 if ($ie->importOneEmail($msgNo, $uid)) {
                     $emailIds[] = $ie->email->id;
                     $ie->deleteMessageOnMailServer($uid);
                     //$ie->retrieve($ieid);
                     //$ie->connectMailserver();
                     $ie->mailbox = $folder;
                     $ie->deleteMessageFromCache($uids[] = $uid);
                 } else {
                     $out = $out . "Message No : " . $messageIndex . " failed. Reason : Message already imported \r\n";
                 }
             }
             $messageIndex++;
         }
         // for
     }
     // if
     if (count($emailIds) > 0) {
         $this->doDistributionWithMethod($users, $emailIds, $distributeMethod);
     }
     // if
     return $out;
 }
Beispiel #12
0
 function get_message_id_uid($params)
 {
     $password = $this->get_user_password($params['username']);
     $mbox = $this->imap_connect($params['username'], $password, $params['folder']);
     $msgno = imap_msgno($mbox, $params['uid']);
     $header = imap_header($mbox, $msgno);
     $message_id = $header->message_id;
     return $header->message_id;
 }
Beispiel #13
0
 public static function mail_Scan($mbox, $account, $folder, $scan_id)
 {
     $return = [];
     $last_user_uid = self::getUidFolder($account['user_id'], $folder);
     $msgno = imap_msgno($mbox, $last_user_uid);
     $num_msg = imap_num_msg($mbox);
     $get_emails = false;
     if ($msgno == 0 && $num_msg != 0) {
         $last_email_uid = imap_uid($mbox, $num_msg);
         if ($last_user_uid == 1) {
             $get_emails = true;
             $msgno = 1;
         } elseif ($last_email_uid > $last_user_uid) {
             $exit = true;
             while ($exit) {
                 $last_user_uid++;
                 $last_scaned_num = imap_msgno($mbox, $last_user_uid);
                 if ($last_scaned_num != 0) {
                     $exit = false;
                     $msgno = $last_scaned_num;
                 } elseif ($last_user_uid == $last_email_uid) {
                     $exit = false;
                     $msgno = $num_msg;
                 }
             }
             $get_emails = true;
         }
     } else {
         if ($msgno < $num_msg) {
             $get_emails = true;
         }
     }
     if ($get_emails) {
         $return['count'] = 0;
         for ($i = $msgno; $i <= $num_msg; $i++) {
             $OSSMailModel = Vtiger_Record_Model::getCleanInstance('OSSMail');
             self::checkFolderUid($account['user_id'], $folder);
             $uid = imap_uid($mbox, $i);
             $mail_detail = $OSSMailModel->get_mail_detail($mbox, $uid, $i);
             $mail_detail['Account_username'] = $account['username'];
             $mail_detail['Account_user_id'] = $account['user_id'];
             self::executeActions($account, $mail_detail, $folder);
             $adb = PearDatabase::getInstance();
             $adb->pquery("update vtiger_ossmailscanner_folders_uid set uid=? where user_id=? AND folder = ?", array($uid, $account['user_id'], $folder));
             self::update_scan_history($scan_id, array('status' => '1', 'count' => $return['count'], 'action' => 'Action_CronMailScanner'));
             $return['count']++;
         }
     }
     return $return;
 }
Beispiel #14
0
 /**
  * @return int
  */
 public function getMessageSequenceNumber()
 {
     return imap_msgno($this->getStream(), $this->getNumber());
 }
Beispiel #15
0
 /**
  * @param $uid
  * @return int
  */
 public function getMessageNumber($uid)
 {
     return imap_msgno($this->getImapStream(), $uid);
 }
Beispiel #16
0
 /**
  * Get message headers
  *
  * @return Message\Headers
  */
 public function getHeaders()
 {
     if (null === $this->headers) {
         // imap_header is much faster than imap_fetchheader
         // imap_header returns only a subset of all mail headers,
         // but it does include the message flags.
         $headers = imap_header($this->stream, imap_msgno($this->stream, $this->messageNumber));
         $this->headers = new Message\Headers($headers);
     }
     return $this->headers;
 }
Beispiel #17
0
 /**
  * Get raw message headers
  *
  * @return string
  */
 public function getRawHeaders()
 {
     if (null === $this->rawHeaders) {
         $this->rawHeaders = imap_fetchheader($this->stream, imap_msgno($this->stream, $this->messageNumber));
     }
     return $this->rawHeaders;
 }
Beispiel #18
0
 /**
  * Returns headers.
  *
  * @param string $pid Part Id
  * @return array
  * @throws \Jyxo\Mail\Parser\EmailNotExistException If no such email exists
  */
 public function getHeaders($pid = null)
 {
     // Parses headers
     $rawHeaders = $this->getRawHeaders($pid);
     if (null === $pid) {
         $msgno = imap_msgno($this->connection, $this->uid);
         if (0 === $msgno) {
             throw new Parser\EmailNotExistException('Email does not exist');
         }
         $headerInfo = imap_headerinfo($this->connection, $msgno);
     } else {
         $headerInfo = imap_rfc822_parse_headers($rawHeaders);
     }
     // Adds a header that the IMAP extension does not support
     if (preg_match("~Disposition-Notification-To:(.+?)(?=\r?\n(?:\\S|\r?\n))~is", $rawHeaders, $matches)) {
         $addressList = imap_rfc822_parse_adrlist($matches[1], '');
         // {''} is used because of CS rules
         $headerInfo->{'disposition_notification_toaddress'} = substr(trim($matches[1]), 0, 1024);
         $headerInfo->{'disposition_notification_to'} = array($addressList[0]);
     }
     $headers = array();
     static $mimeHeaders = array('toaddress', 'ccaddress', 'bccaddress', 'fromaddress', 'reply_toaddress', 'senderaddress', 'return_pathaddress', 'subject', 'fetchfrom', 'fetchsubject', 'disposition_notification_toaddress');
     foreach ($headerInfo as $key => $value) {
         if (!is_object($value) && !is_array($value)) {
             if (in_array($key, $mimeHeaders)) {
                 $headers[$key] = $this->decodeMimeHeader($value);
             } else {
                 $headers[$key] = $this->convertToUtf8($value);
             }
         }
     }
     // Adds "udate" if missing
     if (!empty($headerInfo->udate)) {
         $headers['udate'] = $headerInfo->udate;
     } elseif (!empty($headerInfo->date)) {
         $headers['udate'] = strtotime($headerInfo->date);
     } else {
         $headers['udate'] = time();
     }
     // Parses references
     $headers['references'] = isset($headers['references']) ? explode('> <', trim($headers['references'], '<>')) : array();
     static $types = array('to', 'cc', 'bcc', 'from', 'reply_to', 'sender', 'return_path', 'disposition_notification_to');
     for ($i = 0; $i < count($types); $i++) {
         $type = $types[$i];
         $headers[$type] = array();
         if (isset($headerInfo->{$type})) {
             foreach ($headerInfo->{$type} as $object) {
                 $newHeader = array();
                 foreach ($object as $attributeName => $attributeValue) {
                     if (!empty($attributeValue)) {
                         $newHeader[$attributeName] = 'personal' === $attributeName ? $this->decodeMimeHeader($attributeValue) : $this->convertToUtf8($attributeValue);
                     }
                 }
                 if (!empty($newHeader)) {
                     if (isset($newHeader['mailbox'], $newHeader['host'])) {
                         $newHeader['email'] = $newHeader['mailbox'] . '@' . $newHeader['host'];
                     } elseif (isset($newHeader['mailbox'])) {
                         $newHeader['email'] = $newHeader['mailbox'];
                     } else {
                         $newHeader['email'] = 'undisclosed-recipients';
                     }
                     $headers[$type][] = $newHeader;
                 }
             }
         }
     }
     // Adds X-headers
     if (preg_match_all("~(X(?:[\\-]\\w+)+):(.+?)(?=\r?\n(?:\\S|\r?\n))~is", $rawHeaders, $matches) > 0) {
         for ($i = 0; $i < count($matches[0]); $i++) {
             // Converts to the format used by imap_headerinfo()
             $key = str_replace('-', '_', strtolower($matches[1][$i]));
             // Removes line endings
             $value = strtr(trim($matches[2][$i]), array("\r" => '', "\n" => '', "\t" => ' '));
             $headers[$key] = $value;
         }
     }
     return $headers;
 }
Beispiel #19
0
 function get_message_id_uid($params)
 {
     $account = $this->getAccountByName($params['username']);
     $mbox = $this->imapConnect($params['username'], $account['password'], $account['mail_host'], $params['folder']);
     $msgno = imap_msgno($mbox, $params['uid']);
     $header = imap_header($mbox, $msgno);
     $message_id = $header->message_id;
     return $header->message_id;
 }
Beispiel #20
0
 /**
  * Fetches the header, body & attachments of a msg.
  *
  * @param  <string> $msgId id string of the msg
  * @return <MailMsg> the mail's data, or false on failure
  */
 public function fetchMsg($msgId)
 {
     if (!$this->connectIfNeeded()) {
         return false;
     }
     $newMsg = new MailMsg();
     $structure = imap_fetchstructure($this->connection, $msgId, FT_UID);
     $msgNum = imap_msgno($this->connection, $msgId);
     if (!$structure) {
         return false;
     } else {
         // some parts might be set to 'false' if an error occured
         $newMsg->header = $this->getHeader($msgNum);
         $newMsg->body = $this->getBody($msgNum, $structure);
         $newMsg->attachments = $this->getAttachments($msgNum, $structure);
         return $newMsg;
     }
 }
Beispiel #21
0
 public static function mail_Scan($mbox, $account, $folder, $scan_id, $countEmails)
 {
     $last_user_uid = self::getUidFolder($account['user_id'], $folder);
     $msgno = imap_msgno($mbox, $last_user_uid);
     $num_msg = imap_num_msg($mbox);
     $get_emails = false;
     if ($msgno == 0 && $num_msg != 0) {
         $last_email_uid = imap_uid($mbox, $num_msg);
         if ($last_user_uid == 1) {
             $get_emails = true;
             $msgno = 1;
         } elseif ($last_email_uid > $last_user_uid) {
             $exit = true;
             while ($exit) {
                 $last_user_uid++;
                 $last_scaned_num = imap_msgno($mbox, $last_user_uid);
                 if ($last_scaned_num != 0) {
                     $exit = false;
                     $msgno = $last_scaned_num;
                 } elseif ($last_user_uid == $last_email_uid) {
                     $exit = false;
                     $msgno = $num_msg;
                 }
             }
             $get_emails = true;
         }
     } else {
         if ($msgno < $num_msg) {
             $get_emails = true;
         }
     }
     if ($get_emails) {
         for ($i = $msgno; $i <= $num_msg; $i++) {
             $OSSMailModel = Vtiger_Record_Model::getCleanInstance('OSSMail');
             self::checkFolderUid($account['user_id'], $folder);
             $uid = imap_uid($mbox, $i);
             $mail_detail = $OSSMailModel->get_mail_detail($mbox, $uid, $i);
             $mail_detail['Account_username'] = $account['username'];
             $mail_detail['Account_user_id'] = $account['user_id'];
             self::executeActions($account, $mail_detail, $folder);
             $adb = PearDatabase::getInstance();
             $adb->pquery('UPDATE vtiger_ossmailscanner_folders_uid SET uid=? WHERE user_id=? AND BINARY folder = ?', [$uid, $account['user_id'], $folder]);
             $countEmails++;
             self::update_scan_history($scan_id, ['status' => '1', 'count' => $countEmails, 'action' => 'Action_CronMailScanner']);
             if ($countEmails >= AppConfig::performance('NUMBERS_EMAILS_DOWNLOADED_DURING_ONE_SCANNING')) {
                 return $countEmails;
             }
         }
     }
     return $countEmails;
 }
Beispiel #22
0
function inbox($servr, $user, $passwd, $folder, $sort, $sortdir, $lang, $theme)
{
    $mailhost = $servr;
    require 'conf.php';
    $pop = @imap_open('{' . $mailhost . '}' . $folder, $user, $passwd);
    if ($pop == false) {
        return -1;
    } else {
        if (($num_messages = @imap_num_msg($pop)) == 0) {
            imap_close($pop);
            return 0;
        } else {
            //if ($sort != '' && $sortdir != '')
            $sorted = imap_sort($pop, $sort, $sortdir, SE_UID);
            for ($i = 0; $i < $num_messages; $i++) {
                $subject = $from = '';
                $msgnum = $sorted[$i];
                $ref_contenu_message = imap_header($pop, imap_msgno($pop, $msgnum));
                $struct_msg = imap_fetchstructure($pop, imap_msgno($pop, $msgnum));
                $subject_array = imap_mime_header_decode($ref_contenu_message->subject);
                for ($j = 0; $j < count($subject_array); $j++) {
                    $subject .= $subject_array[$j]->text;
                }
                $from_array = imap_mime_header_decode($ref_contenu_message->fromaddress);
                for ($j = 0; $j < count($from_array); $j++) {
                    $from .= $from_array[$j]->text;
                }
                if (is_Imap($mailhost)) {
                    $msg_size = get_mail_size($struct_msg);
                } else {
                    $msg_size = $struct_msg->bytes > 1000 ? ceil($struct_msg->bytes / 1000) : 1;
                }
                if ($struct_msg->type == 1) {
                    if ($struct_msg->subtype == 'ALTERNATIVE' || $struct_msg->subtype == 'RELATED') {
                        $attach = '&nbsp;';
                    } else {
                        $attach = '<img src="themes/' . $theme . '/img/attach.gif" height="28" width="27" alt="" />';
                    }
                } else {
                    $attach = '&nbsp;';
                }
                // Check Status Line with UCB POP Server to
                // see if this is a new message. This is a
                // non-RFC standard line header.
                // Set this in conf.php
                if ($have_ucb_pop_server) {
                    $header_msg = imap_fetchheader($pop, imap_msgno($pop, $msgnum));
                    $header_lines = explode("\r\n", $header_msg);
                    while (list($k, $v) = each($header_lines)) {
                        list($header_field, $header_value) = explode(':', $v);
                        if ($header_field == 'Status') {
                            $new_mail_from_header = $header_value;
                        }
                    }
                } else {
                    if ($ref_contenu_message->Unseen == 'U' || $ref_contenu_message->Recent == 'N') {
                        $new_mail_from_header = '';
                    } else {
                        $new_mail_from_header = '&nbsp;';
                    }
                }
                if ($new_mail_from_header == '') {
                    $newmail = '<img src="themes/' . $theme . '/img/new.gif" alt="" height="17" width="17" />';
                } else {
                    $newmail = '&nbsp;';
                }
                $msg_list[$i] = array('new' => $newmail, 'number' => imap_msgno($pop, $msgnum), 'next' => imap_msgno($pop, $sorted[$i + 1]), 'prev' => imap_msgno($pop, $sorted[$i - 1]), 'attach' => $attach, 'from' => htmlspecialchars($from), 'subject' => htmlspecialchars($subject), 'date' => change_date(chop($ref_contenu_message->udate), $lang), 'size' => $msg_size, 'sort' => $sort, 'sortdir' => $sortdir);
            }
            imap_close($pop);
            return $msg_list;
        }
    }
}
 /**
  * liefert die laufende msg_number der Nachricht, die die unique ID uid hat
  * @param integer $uid
  * @return integer
  */
 public function imapMsgNo($uid)
 {
     if ($this->imap === null) {
         throw new IMAPException(__METHOD__ . ' not connected');
     }
     $this->imapPing(true);
     return imap_msgno($this->imap, $uid);
 }
Beispiel #24
0
 public static function get_mail_detail($mbox, $id, $msgno = false)
 {
     $return = array();
     if (!$msgno) {
         $msgno = imap_msgno($mbox, $id);
     }
     if (!$id) {
         $id = imap_uid($mbox, $msgno);
     }
     if (!$msgno) {
         return false;
     }
     $header = imap_header($mbox, $msgno);
     $structure = self::_get_body_attach($mbox, $id, $msgno);
     $return['id'] = $id;
     $return['Msgno'] = $header->Msgno;
     $return['message_id'] = $header->message_id;
     $return['toaddress'] = self::get_only_email($header->to);
     $return['fromaddress'] = self::get_only_email($header->from);
     $return['reply_toaddress'] = self::get_only_email($header->reply_to);
     $return['ccaddress'] = self::get_only_email($header->cc);
     $return['bccaddress'] = self::get_only_email($header->bcc);
     $return['senderaddress'] = self::get_only_email($header->sender);
     $return['subject'] = self::_decode_text($header->subject);
     $return['MailDate'] = $header->MailDate;
     $return['date'] = $header->date;
     $return['udate'] = $header->udate;
     $return['udate_formated'] = date("Y-m-d H:i:s", $header->udate);
     $return['Recent'] = $header->Recent;
     $return['Unseen'] = $header->Unseen;
     $return['Flagged'] = $header->Flagged;
     $return['Answered'] = $header->Answered;
     $return['Deleted'] = $header->Deleted;
     $return['Draft'] = $header->Draft;
     $return['Size'] = $header->Size;
     $return['body'] = $structure['body'];
     $return['attachments'] = $structure['attachment'];
     $return['clean'] = '';
     $msgs = imap_fetch_overview($mbox, $msgno);
     foreach ($msgs as $msg) {
         $return['clean'] .= imap_fetchheader($mbox, $msg->msgno);
     }
     return $return;
 }
Beispiel #25
0
 function getMessage($uid, $extended = false, $useCache = true)
 {
     if ($useCache) {
         $cacheID = $this->cache->getMessageCacheID($uid);
         $aMessage = $this->cache->get($this->getCurrentMailbox(), $cacheID, false);
         $updateCache = false;
     } else {
         $aMessage = false;
     }
     if ($aMessage === false) {
         $aMessage = array('uid' => $uid, 'header' => '', 'date' => '', 'body' => false, 'attachments' => false, 'attachments_view' => '');
         //получаем краткую информацию о письме
         $aMessage['header'] = imap_headerinfo($this->stream(), imap_msgno($this->stream(), $uid));
         $aMessage['header'] = array('subject' => $this->decodeHeader(property_exists($aMessage['header'], 'subject') ? $aMessage['header']->subject : ''), 'from' => $aMessage['header']->from[0]->mailbox == 'INVALID_ADDRESS' ? '' : $aMessage['header']->from[0]->mailbox . '@' . $aMessage['header']->from[0]->host, 'from_personal' => $this->decodeHeader(property_exists($aMessage['header']->from[0], 'personal') ? $aMessage['header']->from[0]->personal : ''), 'date' => $aMessage['header']->udate);
         $aMessage['date'] = Func::datetime2dateUSSRWithMonth(date('Y-m-d H:i:s', $aMessage['header']['date']), true);
         $updateCache = true;
     }
     if ($extended && empty($aMessage['body'])) {
         $updateCache = true;
         $old_error = error_reporting(0);
         $structure = @imap_fetchstructure($this->stream(), $uid, FT_UID);
         error_reporting($old_error);
         //            echo '<pre>';
         //            print_r($structure);
         //            echo '</pre><br /><br />';
         //            exit;
         if (!$aMessage['body']) {
             $aMessage['body'] = $this->_getMessageBody($uid, false, $structure, IMAPMNGR_BODY_PRINT);
         }
         if (!$aMessage['attachments']) {
             //анализируем структуру сообщения, расскладываем на секции
             $this->_parseMessageStructure($sections, $structure);
             $aMessage['attachments'] = $this->_getMessageAttachments($uid, $sections);
             //                if($aMessage['attachments'])
             //                {
             //                    $sAttach = '<hr size="1" style="color:#ddd; margin-bottom:4px;" />';
             //                    foreach($aMessage['attachments'] as $attach)
             //                        $sAttach .= "<div class=\"attachment\">{$attach['filename']} ({$attach['mimeType']}, ".Func::getfilesize($attach['size']).")</div>";
             //
             //                    $aMessage['attachments_view'] = $sAttach;
             //                }
             //        echo '<pre>';
             //        print_r($sections);
             //        echo '</pre>';
             //        echo '<br /><br />';
         }
     }
     //            echo '<pre>';
     //            print_r($aMessage);
     //            echo '</pre><br /><br />';
     //            exit;
     if ($useCache && $updateCache) {
         $this->cache->set($this->getCurrentMailbox(), array($cacheID => $aMessage));
     }
     return $aMessage;
 }
Beispiel #26
0
 /**
  * Get the full email for a read / find(first)
  *
  * @param object $Model
  * @param array $query
  *
  * @return array the email according to the find
  */
 private function __getMail($Model, $query)
 {
     if (!isset($query['conditions'][$Model->alias . '.id']) || empty($query['conditions'][$Model->alias . '.id'])) {
         return array();
     }
     if ($this->__connectionType == 'imap') {
         $uuid = $query['conditions'][$Model->alias . '.id'];
     } else {
         $uuid = base64_decode($query['conditions'][$Model->alias . '.id']);
     }
     return $this->__getFormattedMail($Model, imap_msgno($this->MailServer, $uuid));
 }
Beispiel #27
0
<?php

$mbox = @imap_open($server, $user, $pass);
$msgno = imap_msgno($mbox, $mess);
$struct = imap_fetchstructure($mbox, $msgno);
$file = imap_fetchbody($mbox, $msgno, $part);
 /**
  * Get the message number for the uid.
  * @param $uid
  * @return int
  */
 public function getMessageNumber($uid)
 {
     return imap_msgno($this->connection->getConnection(), $uid);
 }
 /**
  * fills InboundEmail->email with an email's details
  * @param int uid Unique ID of email
  * @param bool isMsgNo flag that passed ID is msgNo, default false
  * @param bool setRead Sets the 'seen' flag in cache
  * @param bool forceRefresh Skips cache file
  * @return string
  */
 function setEmailForDisplay($uid, $isMsgNo = false, $setRead = false, $forceRefresh = false)
 {
     if (empty($uid)) {
         $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
         return 'NOOP';
     }
     global $sugar_config;
     global $app_strings;
     // if its a pop3 then get the UIDL and see if this file name exist or not
     if ($this->isPop3Protocol()) {
         // get the UIDL from database;
         $cachedUIDL = md5($uid);
         $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
     } else {
         $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
     }
     if (file_exists($cache) && !$forceRefresh) {
         $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
         include $cache;
         // profides $cacheFile
         /** @var $cacheFile array */
         $metaOut = unserialize($cacheFile['out']);
         $meta = $metaOut['meta']['email'];
         $email = new Email();
         foreach ($meta as $k => $v) {
             $email->{$k} = $v;
         }
         $email->to_addrs = $meta['toaddrs'];
         $email->date_sent = $meta['date_start'];
         //_ppf($email,true);
         $this->email = $email;
         $this->email->email2init();
         $ret = 'cache';
     } else {
         $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
         if ($this->isPop3Protocol()) {
             $msgNo = $this->getCorrectMessageNoForPop3($uid);
         } else {
             if (empty($this->conn)) {
                 $this->connectMailserver();
             }
             $msgNo = $isMsgNo ? $uid : imap_msgno($this->conn, $uid);
         }
         if (empty($this->conn)) {
             $status = $this->connectMailserver();
             if ($status == "false") {
                 $this->email = new Email();
                 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
                 $ret = 'error';
                 return $ret;
             }
         }
         $this->importOneEmail($msgNo, $uid, true);
         $this->email->id = '';
         $this->email->new_with_id = false;
         $ret = 'import';
     }
     if ($setRead) {
         $this->setStatuses($uid, 'seen', 1);
     }
     return $ret;
 }
 function getBody($msg_number)
 {
     $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
     $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
     if ($header->Unseen == 'U' || $header->Recent == 'N') {
         imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
     }
     return $body;
 }