/** * Get messages according to a search criteria * * @param string search criteria (RFC2060, sec. 6.4.4). Set to "UNSEEN" by default * NB: Search criteria only affects IMAP mailboxes. * @param string date format. Set to "Y-m-d H:i:s" by default * @return mixed array containing messages */ public function get_messages($search_criteria = "UNSEEN", $date_format = "Y-m-d H:i:s") { $msgs = imap_search($this->imap_stream, $search_criteria); $no_of_msgs = $msgs ? count($msgs) : 0; $messages = array(); for ($i = 0; $i < $no_of_msgs; $i++) { // Get Message Unique ID in case mail box changes // in the middle of this operation $message_id = imap_uid($this->imap_stream, $msgs[$i]); $header = imap_header($this->imap_stream, $message_id); $date = date($date_format, $header->udate); $from = $header->from; $fromname = ""; $fromaddress = ""; $subject = ""; foreach ($from as $id => $object) { if (isset($object->personal)) { $fromname = $object->personal; } $fromaddress = $object->mailbox . "@" . $object->host; if ($fromname == "") { // In case from object doesn't have Name $fromname = $fromaddress; } } if (isset($header->subject)) { $subject = $this->_mime_decode($header->subject); } $structure = imap_fetchstructure($this->imap_stream, $message_id); $body = ''; if (!empty($structure->parts)) { for ($j = 0, $k = count($structure->parts); $j < $k; $j++) { $part = $structure->parts[$j]; if ($part->subtype == 'PLAIN') { $body = imap_fetchbody($this->imap_stream, $message_id, $j + 1); } } } else { $body = imap_body($this->imap_stream, $message_id); } // Convert quoted-printable strings (RFC2045) $body = imap_qprint($body); array_push($messages, array('msg_no' => $message_id, 'date' => $date, 'from' => $fromname, 'email' => $fromaddress, 'subject' => $subject, 'body' => $body)); // Mark Message As Read imap_setflag_full($this->imap_stream, $message_id, "\\Seen"); } return $messages; }
/** * Get messages according to a search criteria * * @param string search criteria (RFC2060, sec. 6.4.4). Set to "UNSEEN" by default NB: Search criteria only affects IMAP mailboxes. * @param string date format. Set to "Y-m-d H:i:s" by default * @return mixed array containing messages */ public function get_messages($search_criteria = "UNSEEN", $date_format = "Y-m-d H:i:s") { $msgs = imap_search($this->imap_stream, $search_criteria); $no_of_msgs = $msgs ? count($msgs) : 0; $messages = array(); for ($i = 0; $i < $no_of_msgs; $i++) { $header = imap_header($this->imap_stream, $msgs[$i]); $date = date($date_format, $header->udate); $from = $this->_mime_decode($header->fromaddress); $subject = $this->_mime_decode($header->subject); $structure = imap_fetchstructure($this->imap_stream, $msgs[$i]); if (!empty($structure->parts)) { for ($j = 0, $k = count($structure->parts); $j < $k; $j++) { $part = $structure->parts[$j]; if ($part->subtype == 'PLAIN') { $body = imap_fetchbody($this->imap_stream, $msgs[$i], $j + 1); } } } else { $body = imap_body($this->imap_stream, $msgs[$i]); } // Convert quoted-printable strings (RFC2045) $body = imap_qprint($body); array_push($messages, array('msg_no' => $msgs[$i], 'date' => $date, 'from' => $from, 'subject' => $subject, 'body' => $body)); } return $messages; }
function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) { if (!$structure) { $structure = imap_fetchstructure($stream, $msg_number); } if ($structure) { if ($mime_type == $this->get_mime_type($structure)) { if (!$part_number) { $part_number = "1"; } $text = imap_fetchbody($stream, $msg_number, $part_number); if ($structure->encoding == 3) { return imap_base64($text); } else { if ($structure->encoding == 4) { return imap_qprint($text); } else { return $text; } } } if ($structure->type == 1) { while (list($index, $sub_structure) = each($structure->parts)) { if ($part_number) { $prefix = $part_number . '.'; } $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); if ($data) { return $data; } } } } return false; }
function download($VAR) { if (empty($VAR['id'])) { return false; } $id = $VAR['id']; // get ticket id $db =& DB(); $rs = $db->Execute(sqlSelect($db, array("ticket_attachment", "ticket"), "A.ticket_id,B.department_id,B.account_id", "A.id=::{$id}:: AND A.ticket_id=B.id")); if (!$rs || $rs->RecordCount() == 0) { return false; } // is this an admin? global $C_auth; if ($C_auth->auth_method_by_name("ticket", "view")) { // get the data & type $rs = $db->Execute(sqlSelect($db, "ticket_attachment", "*", "id=::{$id}::")); // set the header require_once PATH_CORE . 'file_extensions.inc.php'; $ft = new file_extensions(); $type = $ft->set_headers_ext($rs->fields['type'], $rs->fields['name']); if (empty($type)) { echo imap_qprint($rs->fields['content']); } elseif (preg_match("/^text/i", $type)) { echo imap_base64($rs->fields['content']); } else { echo imap_base64($rs->fields['content']); } exit; } }
private function _decodeMail($encoding, $body) { switch ($encoding) { case ENC7BIT: return $body; case ENC8BIT: return $body; case ENCBINARY: return $body; case ENCBASE64: return imap_base64($body); case ENCQUOTEDPRINTABLE: return imap_qprint($body); case ENCOTHER: return $body; default: return $body; } }
function getdecodevalue($message,$coding) { switch($coding) { case 0: case 1: $message = imap_8bit($message); break; case 2: $message = imap_binary($message); break; case 3: case 5: $message=imap_base64($message); break; case 4: $message = imap_qprint($message); break; } return $message; }
function get_msg($imap_box, $email_number, $mime_type, $structure = false, $part_number = false) { if (!$structure) { // ПЕРВЫЙ запуск, получение корня структуры $structure = imap_fetchstructure($imap_box, $email_number); } $message = ""; if ($structure->subtype == $mime_type) { //"CHARSET") if (!$part_number) { $part_number = "1"; } $data = imap_fetchbody($imap_box, $email_number, $part_number); //получить конкретную часть письма if ($structure->encoding == 3) { $data = base64_decode($data); } if ($structure->encoding == 4) { $data = imap_qprint($data); } if ($structure->parameters[0]->value == "windows-1251") { $data = mb_convert_encoding($data, 'utf-8', 'windows-1251'); } if ($structure->parameters[0]->value == "koi8-r") { $data = mb_convert_encoding($data, 'utf-8', 'koi8-r'); } //echo "<br> Вложенная часть: " . $part_number . "<br>"; $message .= $data; } // Если письмо состоит из многа частей - разбираем каждую отдельно if ($structure->parts) { while (list($index, $sub_structure) = each($structure->parts)) { if ($part_number) { $prefix = $part_number . '.'; } $message .= get_msg($imap_box, $email_number, $mime_type, $sub_structure, $prefix . ($index + 1)); } // end while } // end if return $message; }
/** * Attempts to Decode the message body. If a valid encoding is not passed then it will attempt to detect the encoding itself. * @param $body * @param int|null $encoding * @return string */ public function decodeBody($body, $encoding = null) { switch ($encoding) { case ENCBASE64: return imap_base64($body); case ENCQUOTEDPRINTABLE: return imap_qprint($body); case ENCBINARY: return $body; default: // Let's check if the message is base64 if ($decoded = base64_decode($body, true)) { return $decoded; } if ($this->isQuotedPrintable($body)) { return imap_qprint($body); } return $body; } }
function get_one_mail($number) { $mail = imap_headerinfo($this->connection, $number); //echo "<hr/>"; //echo "mail nummer: ".$number."<br/>"; //echo "date: ".$mail->date."<br/>"; //echo "subject: ".$mail->subject."<br/>"; //echo "from-mailbox: ".$mail->from[0]->mailbox."<br/>"; //echo "from-host: ".$mail->from[0]->host."<br/>"; $this->mails[$number]["date"]["raw"] = $mail->date; $this->mails[$number]["date"]["timestamp"] = strtotime($mail->date); $last_char_1 = substr($mail->subject, -1, 1); $cleansubject = $mail->subject; $cleansubject = utf8_encode(imap_qprint($cleansubject)); $cleansubject = ereg_replace("=\\?ISO-8859-1\\?Q\\?", "", $cleansubject); $cleansubject = ereg_replace("\\?=", "", $cleansubject); $cleansubject = ereg_replace("_", " ", $cleansubject); $last_char_2 = substr($cleansubject, -1, 1); if ($last_char_1 != $last_char_2) { $cleansubject = substr($cleansubject, 0, strlen($cleansubject) - 1); } //$cleansubject = ereg_replace("?", "", $cleansubject); $this->mails[$number]["subject"] = $cleansubject; $this->mails[$number]["mailbox"] = $mail->from[0]->mailbox; $this->mails[$number]["host"] = $mail->from[0]->host; $body = utf8_encode(imap_qprint(imap_fetchbody($this->connection, $number, "1"))); if ($body != "") { $this->mails[$number]["text"] = $body; } $struct = imap_fetchstructure($this->connection, $number); //print_r($struct); $counter = 2; while (imap_fetchbody($this->connection, $number, $counter) != "") { $image = imap_fetchbody($this->connection, $number, $counter); $this->mails[$number]["image"][$counter]["data"] = $image; $parts = $counter - 1; $this->mails[$number]["image"][$counter]["name"] = $struct->parts[$parts]->dparameters[0]->value; $this->email_base64_to_file($number, $counter); $counter++; } }
public static function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) { if (!$structure) { $structure = imap_fetchstructure($stream, $msg_number); } if ($structure) { if ($mime_type == self::get_mime_type($structure)) { if (!$part_number) { $part_number = "1"; } $text = imap_fetchbody($stream, $msg_number, $part_number); if ($structure->encoding == 3) { return imap_base64($text); } else { if ($structure->encoding == 4) { return imap_qprint($text); } else { return $text; } } } if ($structure->type == 1) { while (list($index, $sub_structure) = each($structure->parts)) { if ($part_number) { $prefix = $part_number . '.'; } else { $prefix = ""; } $data = self::get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); if ($data) { return $data; } } // END OF WHILE } // END OF MULTIPART } // END OF STRUTURE return false; }
function get_plain_text_body($mbox, $msgNum, &$attachments = array()) { $structure = imap_fetchstructure($mbox, $msgNum); // only plain text if ('PLAIN' == $structure->subtype) { return trim(imap_qprint(imap_body($mbox, $msgNum))); } if (isset($structure->parts)) { // get attachments foreach ($structure->parts as $partNum => $part) { if (in_array($part->subtype, array('JPEG', 'PNG', 'GIF'))) { // oeh an image $name = 'image-from-email-' . $msgNum . '.' . strtolower($part->subtype); foreach ($part->parameters as $param) { if ('NAME' == $param->attribute) { $name = $param->value; } } $data = imap_fetchbody($mbox, $msgNum, (string) ($partNum + 1)); file_put_contents($attachments[] = 'attachments/' . time() . '--' . $name, base64_decode($data)); } } // multipart (probably) -- look for plain text part foreach ($structure->parts as $partNum => $part) { if ('PLAIN' == $part->subtype) { $body = imap_fetchbody($mbox, $msgNum, (string) ($partNum + 1)); return trim($body); } else { if ('ALTERNATIVE' == $part->subtype && isset($part->parts)) { foreach ($part->parts as $subPartNum => $subPart) { if ('PLAIN' == $subPart->subtype) { $body = imap_fetchbody($mbox, $msgNum, $partNum + 1 . '.' . ($subPartNum + 1)); return trim($body); } } } } } } }
/** * Fetches email body * * @param int $msgno Message number * @return string */ protected function fetchBody($msgno) { $body = imap_fetchbody($this->connection, $msgno, '1', FT_PEEK); $structure = imap_fetchstructure($this->connection, $msgno); $encoding = $structure->parts[0]->encoding; $charset = null; foreach ($structure->parts[0]->parameters as $param) { if ($param->attribute == 'CHARSET') { $charset = $param->value; break; } } if ($encoding == ENCBASE64) { $body = imap_base64($body); } elseif ($encoding == ENCQUOTEDPRINTABLE) { $body = imap_qprint($body); } if ($charset) { $body = iconv($charset, "UTF-8", $body); } return $body; }
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) { if (!$structure) { //$imap_uid = imap_uid ($imap, $uid); //echo "$uid->".$uid; $structure = imap_fetchstructure($imap, $uid, FT_UID); } //echo "<br/>structure-><pre>".print_r($structure)."</pre>"; if ($structure) { if ($mimetype == get_mime_type($structure)) { if (!$partNumber) { $partNumber = 1; } $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID); switch ($structure->encoding) { case 3: return imap_base64($text); case 4: return imap_qprint($text); default: return $text; } } // multipart if ($structure->type == 1) { foreach ($structure->parts as $index => $subStruct) { $prefix = ""; if ($partNumber) { $prefix = $partNumber . "."; } $data = get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1)); if ($data) { return $data; } } } } return false; }
public function __toString() { $encoding = $this->attachment->encoding; switch ($encoding) { case 0: // 7BIT // 7BIT case 1: // 8BIT // 8BIT case 2: // BINARY return $this->getBody(); case 3: // BASE-64 return base64_decode($this->getBody()); case 4: // QUOTED-PRINTABLE return imap_qprint($this->getBody()); } throw new Exception(sprintf('Encoding failed: Unknown encoding %s (5: OTHER).', $encoding)); }
private function read() { $allMails = imap_search($this->conn, 'ALL'); if ($allMails) { rsort($allMails); foreach ($allMails as $email_number) { $overview = imap_fetch_overview($this->conn, $email_number, 0); $structure = imap_fetchstructure($this->conn, $email_number); $body = ''; if (isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) { $part = $structure->parts[1]; $body = imap_fetchbody($this->conn, $email_number, 2); if ($part->encoding == 3) { $body = imap_base64($body); } else { if ($part->encoding == 1) { $body = imap_8bit($body); } else { $body = imap_qprint($body); } } } $body = utf8_decode($body); $fromaddress = utf8_decode(imap_utf7_encode($overview[0]->from)); $subject = mb_decode_mimeheader($overview[0]->subject); $date = utf8_decode(imap_utf8($overview[0]->date)); $date = date('Y-m-d H:i:s', strtotime($date)); $key = md5($fromaddress . $subject . $body); //save to MySQL $sql = "SELECT count(*) FROM EMAIL_INFORMATION WHERE IDMAIL = " . $this->id . " AND CHECKVERS = \"" . $key . "\""; $resul = $this->pdo->query($sql)->fetch(); if ($resul[0] == 0) { $this->pdo->prepare("INSERT INTO EMAIL_INFORMATION (IDMAIL,FROMADDRESS,SUBJECT,DATE,BODY,CHECKVERS) VALUES (?,?,?,?,?,?)"); $this->pdo->execute(array($this->id, $fromaddress, $subject, $date, $body, $key)); } } } }
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) { if (!$structure) { $structure = imap_fetchstructure($imap, $uid, FT_UID); } if ($structure) { if ($mimetype == get_mime_type($structure)) { if (!$partNumber) { $partNumber = 1; } $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID); switch ($structure->encoding) { case 3: return imap_base64($text); case 4: return imap_qprint($text); default: return $text; } } /*/ multipart */ if ($structure->type == 1) { foreach ($structure->parts as $index => $subStruct) { $prefix = ""; if ($partNumber) { $prefix = $partNumber . "."; } $imap = ''; $data = get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1)); if ($data) { return $data; } } } } return false; }
/** * Decode given string with encoding in current string and convert it to UTF-8 from part charset * * @param $string * @return string */ private function decode($string) { if (!$string) { return $string; } //transfer encoding switch (strtolower($this->contentTransferEncoding)) { case "7bit": $decodedString = mb_convert_encoding($string, "UTF-8", "auto"); break; case "8bit": $decodedString = imap_8bit($string); break; case "binary": $decodedString = imap_base64(imap_binary($string)); break; case "base64": $decodedString = imap_base64($string); break; case "quoted-printable": $decodedString = imap_qprint($string); break; default: throw new \UnexpectedValueException('Cannot decode ' . $this->contentTransferEncoding); } //do not convert if string is attachment content if ($this->disposition == "attachment") { return $decodedString; } //charset encoding //TODO add different charsets $decodedString = quoted_printable_decode($decodedString); if (in_array($this->charset, ['windows-1250', 'koi8-r'])) { return iconv(strtoupper($this->charset), "UTF-8", $decodedString); } else { return mb_convert_encoding($decodedString, "UTF-8", strtoupper($this->charset)); } }
function saveForwardAttachments($id, $module, $file_details) { global $log; $log->debug("Entering into saveForwardAttachments({$id},{$module},{$file_details}) method."); global $adb, $current_user; global $upload_badext; require_once 'modules/Webmails/MailBox.php'; $mailbox = $_REQUEST["mailbox"]; $MailBox = new MailBox($mailbox); $mail = $MailBox->mbox; $binFile = sanitizeUploadFileName($file_details['name'], $upload_badext); $filename = ltrim(basename(" " . $binFile)); //allowed filename like UTF-8 characters $filetype = $file_details['type']; $filesize = $file_details['size']; $filepart = $file_details['part']; $transfer = $file_details['transfer']; $file = imap_fetchbody($mail, $_REQUEST['mailid'], $filepart); if ($transfer == 'BASE64') { $file = imap_base64($file); } elseif ($transfer == 'QUOTED-PRINTABLE') { $file = imap_qprint($file); } $current_id = $adb->getUniqueID("vtiger_crmentity"); $date_var = date('Y-m-d H:i:s'); //to get the owner id $ownerid = $this->column_fields['assigned_user_id']; if (!isset($ownerid) || $ownerid == '') { $ownerid = $current_user->id; } $upload_file_path = decideFilePath(); file_put_contents($upload_file_path . $current_id . "_" . $filename, $file); $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?,?,?,?,?,?,?)"; $params1 = array($current_id, $current_user->id, $ownerid, $module . " Attachment", $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true)); $adb->pquery($sql1, $params1); $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?,?,?,?,?)"; $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path); $result = $adb->pquery($sql2, $params2); if ($_REQUEST['mode'] == 'edit') { if ($id != '' && $_REQUEST['fileid'] != '') { $delquery = 'delete from vtiger_seattachmentsrel where crmid = ? and attachmentsid = ?'; $adb->pquery($delquery, array($id, $_REQUEST['fileid'])); } } $sql3 = 'insert into vtiger_seattachmentsrel values(?,?)'; $adb->pquery($sql3, array($id, $current_id)); return true; $log->debug("exiting from saveforwardattachment function."); }
public function chamado_mail2() { 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; } $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 = 1; $i <= imap_num_msg($mbox); $i++) { # ************************************************************** date_default_timezone_set('America/Sao_Paulo'); $headers = imap_header($mbox, $i); $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>" . $headers->to[0]->personal . " [" . $headers->to[0]->mailbox . '@' . $headers->to[0]->host . "]<br />\n"; $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(' ', ' ', $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) { $k = count($msg); } else { $mensagem .= $msg[$k] . "<br /><br />\n\n"; } } else { $mensagem .= $msg[$k] . "<br /><br />\n\n"; } } } } # ************************************************************** if (strlen($mensagem) > 0) { $mensagem = $h . $mensagem; $this->sql = "SELECT c.id_chamado FROM vsites_chamado AS c WHERE \n\t\t\t\t\t\t\tc.pergunta = ? AND c.data_atualizacao = ?"; $this->values = array($headers->subject, $data); $dt = $this->fetch(); if (count($dt) == 0) { $headers->subject = utf8_encode($headers->subject); ${$mensagem} = utf8_encode($mensagem); $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' => 1, 'pergunta' => $headers->subject, 'resposta' => $mensagem, 'data_cadastro' => $data, 'data_atualizacao' => $data, 'forma_atend' => 2); return $this->insert(); } } #echo $mensagem."\n\n\n"; } } } }
function decode($text, $encoding) { switch ($encoding) { case 1: $text = imap_8bit($text); break; case 2: $text = imap_binary($text); break; case 3: // imap_base64 implies strict mode. If it refuses to decode the // data, then fallback to base64_decode in non-strict mode $text = ($conv = imap_base64($text)) ? $conv : base64_decode($text); break; case 4: $text = imap_qprint($text); break; } return $text; }
/** * Get Part Of Message Internal Private Use * * @param $stream An IMAP stream returned by imap_open * @param $msg_number The message number * @param $mime_type mime type of the mail * @param $structure structure of the mail (false by default) * @param $part_number The part number (false by default) * * @return data of false if error **/ function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) { if ($structure) { if ($mime_type == $this->get_mime_type($structure)) { if (!$part_number) { $part_number = "1"; } $text = imap_fetchbody($stream, $msg_number, $part_number); if ($structure->encoding == 3) { $text = imap_base64($text); } else { if ($structure->encoding == 4) { $text = imap_qprint($text); } } //else { return $text; } if ($structure->subtype && $structure->subtype == "HTML") { $text = str_replace("\r", " ", $text); $text = str_replace("\n", " ", $text); } if (count($structure->parameters) > 0) { foreach ($structure->parameters as $param) { if (strtoupper($param->attribute) == 'CHARSET' && function_exists('mb_convert_encoding') && strtoupper($param->value) != 'UTF-8') { $text = mb_convert_encoding($text, 'utf-8', $param->value); $this->body_converted = true; } } } return $text; } if ($structure->type == 1) { /* multipart */ $prefix = ""; reset($structure->parts); while (list($index, $sub_structure) = each($structure->parts)) { if ($part_number) { $prefix = $part_number . '.'; } $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); if ($data) { return $data; } } } } return false; }
function fetchMessageBody($uid, $partID, $encoding, $charset = '') { #// MS-Outlookbug workaround (don't break links) #$mimeMessage = preg_replace("!((http(s?)://)|((www|ftp)\.))(([^\n\t\r]+)([=](\r)?\n))+!i", # "$1$7", # $mimeMessage); $body = @imap_fetchbody($this->_stream, $uid, $partID, FT_PEEK + FT_UID); switch ($encoding) { case ENCBASE64: //3 // use imap_base64 to decode $body = imap_base64($body); break; case ENCQUOTEDPRINTABLE: //4 // use imap_qprint to decode $body = imap_qprint($body); break; // case 0: $body = imap_7bit( $body ); break; // case 1: $body = imap_8bit( $body ); break; // case 2: $body = imap_binary( $body ); break; // case 0: $body = imap_7bit( $body ); break; // case 1: $body = imap_8bit( $body ); break; // case 2: $body = imap_binary( $body ); break; default: break; } if (!empty($charset) && $charset != 'default' && $charset != 'unknown') { $body = mb_convert_encoding($body, $this->displayCharset, $charset); } return $body; }
function getMailPart($stream, $msg_number, $mime_type, $structure, $part_number = false) { if ($mime_type == $this->getMailMimeType($structure)) { if (!$part_number) { $part_number = "1"; } $text = imap_fetchbody($stream, $msg_number, $part_number); if ($structure->encoding == self::MAIL_ENCODING_BASE64) { $ret_val = imap_base64($text); } elseif ($structure->encoding == self::MAIL_ENCODING_QUOTED) { $ret_val = imap_qprint($text); } else { $ret_val = $text; } return $ret_val; } if ($structure->type == 1) { while (list($index, $sub_structure) = each($structure->parts)) { if ($part_number) { $prefix = $part_number . '.'; } $data = $this->getMailPart($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); if ($data) { return $data; } } // END OF WHILE } // END OF MULTIPART return false; }
/** * MIME encode function to prepare input to target charset supported by normal IMAP clients. */ static function __mime_encode($input, $encoding = 'Q', $charset = 'iso-8859-1') { $returnvalue = $input; $encoded = false; if (strtoupper($encoding) == 'B') { $returnvalue = self::__convert_encoding($input, $charset); $returnvalue = base64_encode($returnvalue); $encoded = true; } else { $returnvalue = self::__convert_encoding($input, $charset); if (function_exists('imap_qprint')) { $returnvalue = imap_qprint($returnvalue); $encoded = true; } else { // TODO: Handle case when imap_qprint is not available. } } if ($encoded) { $returnvalue = "=?{$charset}?{$encoding}?{$returnvalue}?="; } return $returnvalue; }
protected function initMailPart($mbox, $mail, $partStructure, $partNum) { $data = $partNum ? imap_fetchbody($mbox, $mail['id'], $partNum, FT_UID | FT_PEEK) : imap_body($mbox, $mail['id'], FT_UID | FT_PEEK); if ($partStructure->encoding == 1) { $data = imap_utf8($data); } elseif ($partStructure->encoding == 2) { $data = imap_binary($data); } elseif ($partStructure->encoding == 3) { $data = imap_base64($data); } elseif ($partStructure->encoding == 4) { $data = imap_qprint($data); } $params = array(); if (!empty($partStructure->parameters)) { foreach ($partStructure->parameters as $param) { $params[strtolower($param->attribute)] = $param->value; } } if (!empty($partStructure->dparameters)) { foreach ($partStructure->dparameters as $param) { $paramName = strtolower(preg_match('~^(.*?)\\*~', $param->attribute, $matches) ? $matches[1] : $param->attribute); if (isset($params[$paramName])) { $params[$paramName] .= $param->value; } else { $params[$paramName] = $param->value; } } } if (!empty($params['charset'])) { $data = iconv(strtoupper($params['charset']), 'utf-8', $data); } $attachmentId = $partStructure->ifid ? trim($partStructure->id, " <>") : (isset($params['filename']) || isset($params['name']) ? mt_rand() . mt_rand() : null); if ($attachmentId) { if (empty($params['filename']) && empty($params['name'])) { $fileName = $attachmentId . '.' . strtolower($partStructure->subtype); } else { $fileName = !empty($params['filename']) ? $params['filename'] : $params['name']; $fileName = self::decodeMimeStr($fileName); $fileName = self::decodeRFC2231($fileName); } $mail['attachments'][$attachmentId]['filename'] = $fileName; $mail['attachments'][$attachmentId]['attachment'] = $data; } elseif ($partStructure->type == 0 && $data) { if (base64_decode($data, true)) { $data = base64_decode($data); } if (strtolower($partStructure->subtype) == 'plain') { $mail['textPlain'] .= $data; } else { $mail['textHtml'] .= $data; } } elseif ($partStructure->type == 2 && $data) { $mail['textPlain'] .= trim($data); } if (!empty($partStructure->parts)) { foreach ($partStructure->parts as $subPartNum => $subPartStructure) { if ($partStructure->type == 2 && $partStructure->subtype == 'RFC822') { $mail = self::initMailPart($mbox, $mail, $subPartStructure, $partNum); } else { $mail = self::initMailPart($mbox, $mail, $subPartStructure, $partNum . '.' . ($subPartNum + 1)); } } } return $mail; }
} ?> > </td> </tr> <tr> <?php if (function_exists('imap_qprint')) { ?> <td><?php echo _('Vacation message'); ?> :</td> <td> <textarea name="vacation" cols="40" rows="5" class="textfield"><?php print imap_qprint($row['vacation']); ?> </textarea> </td> <?php } else { ?> <td><?php echo _('Vacation message (ASCII only!)'); ?> :</td> <td> <textarea name="vacation" cols="40" rows="5" class="textfield"><?php print $row['vacation']; ?> </textarea>
function getEmailAttachments($inbox, $email_number, $structure) { $attachments = array(); // Tomar adjuntos de e-mail if (isset($structure->parts) && count($structure->parts)) { for ($i = 0; $i < count($structure->parts); $i++) { $is_attachment = false; $filename = ""; $name = ""; $attachment = ""; if ($structure->parts[$i]->ifdparameters) { foreach ($structure->parts[$i]->dparameters as $object) { if (strtolower($object->attribute) == 'name') { $is_attachment = true; $filename = $object->value; } } } if ($structure->parts[$i]->ifparameters) { foreach ($structure->parts[$i]->parameters as $object) { if (strtolower($object->attribute) == 'name') { $is_attachment = true; $filename = $object->value; } } } if ($is_attachment) { $attachment = imap_fetchbody($inbox, $email_number, $i + 1); switch ($structure->parts[$i]->encoding) { case 0: case 1: $attachment = imap_8bit($attachment); break; case 2: $attachment = imap_binary($attachment); break; case 3: case 5: $attachment = imap_base64($attachment); break; case 4: $attachment = imap_qprint($attachment); break; } $attachments[$i] = array('is_attachment' => $is_attachment, 'filename' => $filename, 'name' => $name, 'attachment' => $attachment); } } } // Procesar adjuntos y formatear arreglo $tmpAttachments = array(); foreach ($attachments as $attachment) { mb_internal_encoding('UTF-8'); $attachment["filename"] = str_replace("_", " ", mb_decode_mimeheader($attachment["filename"])); $attachmentArray = array(); $tmpFilenameArray = explode(".", $attachment["filename"]); $basename = $tmpFilenameArray[0]; $extension = end($tmpFilenameArray); $attachmentArray["basename"] = $basename; switch (strtolower($extension)) { case 'xml': $attachmentArray["extension"] = "xml"; $attachmentArray["attachment"] = $attachment["attachment"]; $tmpAttachments[] = $attachmentArray; break; case 'zip': $zipArray = processZipFile($attachment["attachment"]); foreach ($zipArray as $zippedFile) { $attachmentArray = array(); $attachmentArray["basename"] = $zippedFile["basename"]; $attachmentArray["extension"] = $zippedFile["extension"]; $attachmentArray["attachment"] = $zippedFile["attachment"]; $tmpAttachments[] = $attachmentArray; } break; default: $attachmentArray["extension"] = $extension; $attachmentArray["attachment"] = $attachment["attachment"]; $tmpAttachments[] = $attachmentArray; break; } } // Armar arreglo final (juntar xml con su pdf respectivo) $returnArray = array(); foreach ($tmpAttachments as $attachment) { $tmpArray = array(); if (strtolower($attachment["extension"]) == "xml") { $tmpArray = array("xml_basename" => $attachment["basename"], "xml_extension" => $attachment["extension"], "xml_attachment" => $attachment["attachment"], "pdf_basename" => "", "pdf_extension" => "", "pdf_attachment" => ""); foreach ($tmpAttachments as $pdfAttachment) { if ((strtolower($pdfAttachment["extension"]) == "pdf" || strtolower($pdfAttachment["extension"]) == "tiff") && $pdfAttachment["basename"] == $attachment["basename"]) { $tmpArray["pdf_basename"] = $pdfAttachment["basename"]; $tmpArray["pdf_extension"] = $pdfAttachment["extension"]; $tmpArray["pdf_attachment"] = $pdfAttachment["attachment"]; } } $returnArray[] = $tmpArray; } } return $returnArray; }
protected function initMailPart(IncomingMail $mail, $partStructure, $partNum) { $data = $partNum ? imap_fetchbody($this->getImapStream(), $mail->id, $partNum, FT_UID) : imap_body($this->getImapStream(), $mail->id, FT_UID); if ($partStructure->encoding == 1) { $data = imap_utf8($data); } elseif ($partStructure->encoding == 2) { $data = imap_binary($data); } elseif ($partStructure->encoding == 3) { $data = imap_base64($data); } elseif ($partStructure->encoding == 4) { $data = imap_qprint($data); } $params = array(); if (!empty($partStructure->parameters)) { foreach ($partStructure->parameters as $param) { $params[strtolower($param->attribute)] = $param->value; } } if (!empty($partStructure->dparameters)) { foreach ($partStructure->dparameters as $param) { $paramName = strtolower(preg_match('~^(.*?)\\*~', $param->attribute, $matches) ? $matches[1] : $param->attribute); if (isset($params[$paramName])) { $params[$paramName] .= $param->value; } else { $params[$paramName] = $param->value; } } } if (!empty($params['charset'])) { $data = iconv(strtoupper($params['charset']), $this->serverEncoding . '//IGNORE', $data); } // attachments $attachmentId = $partStructure->ifid ? trim($partStructure->id, " <>") : (isset($params['filename']) || isset($params['name']) ? mt_rand() . mt_rand() : null); if ($attachmentId) { if (empty($params['filename']) && empty($params['name'])) { $fileName = $attachmentId . '.' . strtolower($partStructure->subtype); } else { $fileName = !empty($params['filename']) ? $params['filename'] : $params['name']; $fileName = $this->decodeMimeStr($fileName, $this->serverEncoding); $fileName = $this->decodeRFC2231($fileName, $this->serverEncoding); } $attachment = new IncomingMailAttachment(); $attachment->id = $attachmentId; $attachment->name = $fileName; if ($this->attachmentsDir) { $replace = array('/\\s/' => '_', '/[^0-9a-zA-Z_\\.]/' => '', '/_+/' => '_', '/(^_)|(_$)/' => ''); $fileSysName = preg_replace('~[\\\\/]~', '', $mail->id . '_' . $attachmentId . '_' . preg_replace(array_keys($replace), $replace, $fileName)); $attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . $fileSysName; file_put_contents($attachment->filePath, $data); } $mail->addAttachment($attachment); } elseif ($partStructure->type == 0 && $data) { if (strtolower($partStructure->subtype) == 'plain') { $mail->textPlain .= $data; } else { $mail->textHtml .= $data; } } elseif ($partStructure->type == 2 && $data) { $mail->textPlain .= trim($data); } if (!empty($partStructure->parts)) { foreach ($partStructure->parts as $subPartNum => $subPartStructure) { if ($partStructure->type == 2 && $partStructure->subtype == 'RFC822') { $this->initMailPart($mail, $subPartStructure, $partNum); } else { $this->initMailPart($mail, $subPartStructure, $partNum . '.' . ($subPartNum + 1)); } } } }
/** Parse messages sitting in mailbox */ function parse_messages() { if ($this->num_msgs > 0) { for ($x = 1; $x < $this->num_msgs + 1; $x++) { # Retrieve raw mail body $rawdata = imap_fetchheader($this->conn, $x) . imap_body($this->conn, $x); # Retrieve mail structure $struct = imap_fetchstructure($this->conn, $x); # Retrieve mail headers $headers = imap_headerinfo($this->conn, $x); # Build array of addresses mail was sent to $to = array(); foreach ($headers->to as $item) { array_push($to, $item->mailbox . "@" . $item->host); } # Get the address message is from $from = $headers->from[0]->mailbox . "@" . $headers->from[0]->host; # FIXME - attachment handling: # Use of dparameters seems to be wrong - the correct key is 'filename' I guess. # More info http://php.net/manual/en/function.imap-fetchstructure.php # Anyway, I have removed the attachment code since it doesn't work AND # the code in the parser script already handle the attachments. # Check if this is a multipart message. (can not use type since # it is 0 for text (.txt) attachments.) // if ($struct->type == 1) { if ($struct->parts) { foreach ($struct->parts as $key => $part) { // Skipping HTML if ($part->ifsubtype == 1 and $part->subtype == "HTML") { continue; } // Ignoring all attachements if (strtolower($part->disposition) != "attachment") { # Retrieve mail body $body = imap_fetchbody($this->conn, $x, $key + 1); # Check for base64 or quoted printable encoding if ($part->encoding == 3) { $body = imap_base64($body); } else { if ($part->encoding == 4) { $body = imap_qprint($body); } } } } } else { # Retrieve mail body (for this single part message). $body = imap_body($this->conn, $x); # Check for base64 or quoted printable encoding if ($struct->encoding == 3) { $body = imap_base64($body); } else { if ($struct->encoding == 4) { $body = imap_qprint($body); } } } # Add message to array $this->messages[] = array('msgno' => $x, 'from' => $from, 'to' => $to, 'message_id' => $headers->message_id, 'subject' => $headers->subject, 'body' => $body, 'rawdata' => $rawdata); } } }
/** * Decode text to the application encoding * * @param string $text */ protected function _decode($text) { if (is_object($text)) { $decoded = $text; $text = $decoded->text; } else { $decoded = imap_mime_header_decode($text); $decoded = $decoded[0]; } if (empty($decoded) || empty($decoded->text) || $decoded->charset === 'default') { return $text; } $text = imap_qprint($decoded->text); $app_encoding = Configure::read('App.encoding'); $mail_encoding = $decoded->charset; $encodings = mb_list_encodings(); $valid = true; if ($app_encoding !== $mail_encoding || !($valid = mb_check_encoding($text, $mail_encoding))) { if (!in_array($mail_encoding, $encodings) || !$valid) { $mail_encoding = mb_detect_encoding($text); } if (!in_array($app_encoding, $encodings)) { $app_encoding = 'UTF-8'; } $text = mb_convert_encoding($text, $app_encoding, $mail_encoding); } return $text; }