function getAttachments($id, $path) { $parts = imap_fetchstructure($this->mailbox, $id); $attachments = array(); //FIXME if we do an is_array() here it breaks howver if we don't //we get foreach errors foreach ($parts->parts as $key => $value) { $encoding = $parts->parts[$key]->encoding; if ($parts->parts[$key]->ifdparameters) { $filename = $parts->parts[$key]->dparameters[0]->value; $message = imap_fetchbody($this->mailbox, $id, $key + 1); switch ($encoding) { case 0: $message = imap_8bit($message); case 1: $message = imap_8bit($message); case 2: $message = imap_binary($message); case 3: $message = imap_base64($message); case 4: $message = quoted_printable_decode($message); case 5: default: $message = $message; } $fp = fopen($path . $filename, "w"); fwrite($fp, $message); fclose($fp); $attachments[] = $filename; } } return $attachments; }
function mime_header_many($array) { $return = ""; if (!empty($array[0][0])) { for ($j = 0; $j <= count($array) - 1; $j++) { $return2 = ""; for ($i = 0; $i <= count($array[$j]) - 1; $i++) { if ($i == count($array[$j]) - 1) { if (count($array[$j]) == 1) { $return2 .= "<" . $array[$j][$i] . ">"; } else { $return2 = str_replace(" ", "_", "=?UTF-8?Q?" . imap_8bit($return2) . "?=") . " <" . $array[$j][$i] . ">"; } if ($j < count($array) - 1) { $return2 .= ", "; } } else { $return2 .= $array[$j][$i] . " "; } } $return .= $return2; } } return $return; }
function email($e_mail, $subject, $message, $headers) { // add headers for utf-8 message $headers .= "\r\n"; $headers .= 'From: ijgc-online.com <*****@*****.**>' . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/plain; charset=utf-8\r\n"; $headers .= "Content-Transfer-Encoding: quoted-printable\r\n"; // encode subject //=?UTF-8?Q?encoded_text?= // work a round: for subject with wordwrap // not fixed, no possibility to have one in a single char $subject = wordwrap($subject, 25, "\n", FALSE); $subject = explode("\n", $subject); array_walk($subject, imap8bit); $subject = implode("\r\n ", $subject); $subject = "=?UTF-8?Q?".$subject."?="; // encode e-mail message $message = imap_8bit($message); return(mail("$e_mail", "$subject", "$message", "$headers")); }
function encodeHeader($_string, $_encoding = 'q') { switch ($_encoding) { case "q": if (!preg_match("/[€-ÿ]/", $_string)) { // nothing to quote, only 7 bit ascii return $_string; } $string = imap_8bit($_string); $stringParts = explode("=\r\n", $string); while (list($key, $value) = each($stringParts)) { if (!empty($retString)) { $retString .= " "; } $value = str_replace(" ", "_", $value); // imap_8bit does not convert "?" // it does not need, but it should $value = str_replace("?", "=3F", $value); $retString .= "=?" . strtoupper($this->displayCharset) . "?Q?" . $value . "?="; } #exit; return $retString; break; default: return $_string; } }
function headerQuotedPrintableEncode($string, $encoding = 'UTF-8') { $string = str_replace(" ", "_", trim($string)); // We need to delete "=\r\n" produced by imap_8bit() and replace '?' $string = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($string))); // Now we split by \r\n - i'm not sure about how many chars (header name counts or not?) $string = chunk_split($string, 73); // We also have to remove last unneeded \r\n : $string = substr($string, 0, strlen($string) - 2); // replace newlines with encoding text "=?UTF ..." $string = str_replace("\r\n", "?=" . HEAD_CRLF . " =?" . $encoding . "?Q?", $string); return '=?' . $encoding . '?Q?' . $string . '?='; }
function email_encode($String = '', $Caracteres = 'ISO-8859-1') { // Quoted-printed (Q) if (function_exists('quoted_printable_encode')) { $String = quoted_printable_encode($String); $RT = '=?' . $Caracteres . '?Q?' . $String . '?='; } else { // IMAP 8bit (Q) if (function_exists('imap_8bit')) { $String = imap_8bit($String); $RT = '=?' . $Caracteres . '?Q?' . $String . '?='; } else { $String = base64_encode($String); $RT = '=?' . $Caracteres . '?B?' . $String . '?='; } } return $RT; }
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 decode($encoding, $text) { switch ($encoding) { case 1: $text = imap_8bit($text); break; case 2: $text = imap_binary($text); break; case 3: $text = imap_base64($text); break; case 4: $text = imap_qprint($text); break; case 5: default: $text = $text; } return $text; }
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 build_message($part) { $message = $part['message']; $encoding = $part['encoding']; $charset = $part['charset']; switch ($encoding) { case 'base64': $message = chunk_split(base64_encode($message)); break; case 'quoted-printable': $message = imap_8bit($message); break; default: break; } $val = 'Content-Type: ' . $part['ctype'] . ';'; $val .= $part['charset'] ? ' charset=' . $part['charset'] : ''; $val .= $part['name'] ? $this->crlf . "\tname=\"" . $part['name'] . '"' : ''; $val .= $this->crlf . 'Content-Transfer-Encoding: ' . $encoding; $val .= $part['name'] ? $this->crlf . 'Content-Disposition: attachment;' . $this->crlf . "\tfilename=\"" . $part['name'] . "\"" : ''; $val .= $this->crlf . $this->crlf . $message . $this->crlf; return $val; }
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; }
private function decodeString($string, $encoding) { switch ($encoding) { case self::ENC_7BIT: return $string; case self::ENC_8BIT: return quoted_printable_decode(imap_8bit($string)); case self::ENC_BINARY: return imap_binary($string); case self::ENC_BASE64: return imap_base64($string); case self::ENC_QUOTED_PRINTABLE: return quoted_printable_decode($string); case self::ENC_OTHER: return $string; default: return $string; } }
/** * Private function : Recursivly get attached documents * * @param $mid message id * @param $path temporary path * @param $maxsize of document to be retrieved * @param $structure of the message or part * @param $part part for recursive * * Result is stored in $this->files **/ function getRecursiveAttached($mid, $path, $maxsize, $structure, $part = "") { if ($structure->type == 1) { // multipart reset($structure->parts); while (list($index, $sub) = each($structure->parts)) { $this->getRecursiveAttached($mid, $path, $maxsize, $sub, $part ? $part . "." . ($index + 1) : $index + 1); } } else { $filename = ''; if ($structure->ifdparameters) { // get filename of attachment if present // if there are any dparameters present in this part if (count($structure->dparameters) > 0) { foreach ($structure->dparameters as $dparam) { if (Toolbox::strtoupper($dparam->attribute) == 'NAME' || Toolbox::strtoupper($dparam->attribute) == 'FILENAME') { $filename = $dparam->value; } } } } //if no filename found if (empty($filename) && $structure->ifparameters) { // if there are any parameters present in this part if (count($structure->parameters) > 0) { foreach ($structure->parameters as $param) { if (Toolbox::strtoupper($param->attribute) == 'NAME' || Toolbox::strtoupper($param->attribute) == 'FILENAME') { $filename = $param->value; } } } } if (empty($filename) && $structure->type == 5 && $structure->subtype) { // Embeded image come without filename - generate trivial one $filename = "image_{$part}." . $structure->subtype; } // if no filename found, ignore this part if (empty($filename)) { return false; } //try to avoid conflict between inline image and attachment $i = 2; while (in_array($filename, $this->files)) { //replace filename with name_(num).EXT by name_(num+1).EXT $new_filename = preg_replace("/(.*)_([0-9])*(\\.[a-zA-Z0-9]*)\$/", "\$1_" . $i . "\$3", $filename); if ($new_filename !== $filename) { $filename = $new_filename; } else { //the previous regex didn't found _num pattern, so add it with this one $filename = preg_replace("/(.*)(\\.[a-zA-Z0-9]*)\$/", "\$1_" . $i . "\$2", $filename); } $i++; } $filename = $this->decodeMimeString($filename); if ($structure->bytes > $maxsize) { $this->addtobody .= "\n\n" . sprintf(__('%1$s: %2$s'), __('Too large attached file'), sprintf(__('%1$s (%2$s)'), $filename, Toolbox::getSize($structure->bytes))); return false; } if (!Document::isValidDoc($filename)) { //TRANS: %1$s is the filename and %2$s its mime type $this->addtobody .= "\n\n" . sprintf(__('%1$s: %2$s'), __('Invalid attached file'), sprintf(__('%1$s (%2$s)'), $filename, $this->get_mime_type($structure))); return false; } if ($message = imap_fetchbody($this->marubox, $mid, $part)) { switch ($structure->encoding) { 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; } if (file_put_contents($path . $filename, $message)) { $this->files[$filename] = $filename; // If embeded image, we add a tag if ($structure->type == 5 && $structure->subtype) { end($this->files); $tag = Rule::getUuid(); $this->tags[$filename] = $tag; // Link file based on id if (isset($structure->id)) { $clean = array('<' => '', '>' => ''); $this->altfiles[strtr($structure->id, $clean)] = $filename; } } } } // fetchbody } // Single part }
/** * Encode a string making it an encoded word as RFC2047 wants * @author "Emiliano 'AlberT' Gabrielli" <*****@*****.**> * @access private * * @param string $str: the string to be encoded * @param int $offset: an optional offset to be counted for the first line * @return string the encoded string, made of N encoded words as the original lenght impose */ function _wordEncode($str, $offset = 0) { if (!$this->canEncode) { return $addr; } $cs = $this->charset; $str = str_replace(array(' ', "=\r\n", '?'), array('_', '', '=3F'), trim(imap_8bit($str))); $enlen = strlen("=?{$cs}?Q??="); // -4 is to ensure we do not truncate a trailing encoded char $max_fst_line_len = 75 - $enlen - $offset - 2; if ($this->_strlen($str) <= $max_fst_line_len) { return "=?{$cs}?Q?{$str}?="; } if (FALSE !== $this->_strpos($str, '=', $max_fst_line_len - 3)) { $max_fst_line_len -= 3; } $fst_line = $this->_substr($str, 0, $max_fst_line_len); $str = $this->_substr($str, $max_fst_line_len); $str = chunk_split($str, 75 - $enlen, "\r\n"); // remove last unneeded CRLF $str = $this->_substr($str, 0, -2); $arows = explode("\r\n", $str); //reattach the first line array_unshift($arows, $fst_line); return '=?' . $cs . '?Q?' . implode("?=\r\n =?{$cs}?Q?", $arows) . '?='; }
/** * Get Attached File from Mail * * @param int $mid message id * @param string $path attachment storage path * * @param string $separator list separator for attachment names * * @return string */ public function getAttachment($mid, $path, $separator = ',') { if (!$this->getMailBox()) { return false; } $structure = imap_fetchstructure($this->getMailBox(), $mid); $attachments = ""; if (property_exists($structure, 'parts') && $structure->parts) { foreach (array_keys($structure->parts) as $key) { $enc = $structure->parts[$key]->encoding; if ($structure->parts[$key]->ifdparameters) { $name = $structure->parts[$key]->dparameters[0]->value; $message = imap_fetchbody($this->getMailBox(), $mid, $key + 1); switch ($enc) { case 0: $message = imap_8bit($message); break; 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; } $fp = fopen($path . $name, "w"); fwrite($fp, $message); fclose($fp); $attachments .= $name . $separator; } // Support for embedded attachments starts here if (property_exists($structure->parts[$key], 'parts')) { foreach (array_keys($structure->parts[$key]->parts) as $keyB) { $enc = $structure->parts[$key]->parts[$keyB]->encoding; if ($structure->parts[$key]->parts[$keyB]->ifdparameters) { $name = $structure->parts[$key]->parts[$keyB]->dparameters[0]->value; $partNum = $key + 1 . "." . ($keyB + 1); $message = imap_fetchbody($this->getMailBox(), $mid, $partNum); switch ($enc) { case 0: $message = imap_8bit($message); break; 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; } $fp = fopen($path . $name, "w"); fwrite($fp, $message); fclose($fp); $attachments .= $name . $separator; } } } } } /** Catch embedded images */ $embedded = $this->getEmbeddedImages(array('mid' => $mid, 'path' => $path, 'separator' => $separator)); if ($embedded) { $attachments = $attachments . $embedded; } $attachments = substr($attachments, 0, strlen($attachments) - strlen($separator)); return $attachments; }
if (in_array('pdf', $reportFormat)) { $report_html = $generate->generateReport(90, "HTML", false); ITS4YouReports::sshow($report_html); exit; $generate_pdf_filename = $tmpDir . generate_cool_url($generate->pdf_filename); $fileName = $rootDirectory . $tempFileName . $generate->pdf_filename . '.xls'; if ($generate_pdf_filename != "" && file_exists($generate_pdf_filename)) { $fileName_arr = explode(".", $generate->pdf_filename); $fileName_arr[0] .= '_' . preg_replace('/[^a-zA-Z0-9_-\\s]/', '', $currentTime); $fileName = implode(".", $fileName_arr); $attachments[$fileName] = $generate_pdf_filename; } } if (in_array('xls', $reportFormat)) { $report_data = $generate->generateReport(90, "XLS", false); $ITS4YouReports_xls = "Reports4You_1_90.xls"; $fileName_arr = explode(".", $ITS4YouReports_xls); $fileName_arr[0] .= '_' . preg_replace('/[^a-zA-Z0-9_-\\s]/', '', $currentTime); $fileName = implode(".", $fileName_arr); $fileName_path = $tmpDir . $ITS4YouReports_xls; $generate->writeReportToExcelFile($fileName_path, $report_data); $attachments[$fileName] = $fileName_path; } foreach ($attachments as $attachmentName => $path) { $vtigerMailer->AddAttachment($path, "=?ISO-8859-15?Q?" . imap_8bit(html_entity_decode($attachmentName, ENT_QUOTES, "UTF-8")) . "?="); } $send_result = $vtigerMailer->Send(true); echo "SEND RESULT -> " . $send_result . "<br />"; foreach ($attachments as $attachmentName => $path) { unlink($path); }
/** * 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)); } }
/** * Properly encode a mail header text for using with mail(). * * @param string $text the text to encode * @return string The encoded header */ function vexim_encode_header($text) { if (function_exists('mb_encode_mimeheader')) { mb_internal_encoding('UTF-8'); $text = mb_encode_mimeheader($text, 'UTF-8', 'Q'); } elseif (function_exists('imap_8bit')) { $text = str_replace(" ", "_", imap_8bit(trim($text))); $text = str_replace("?", "=3F", $text); $text = str_replace("=\r\n", "?=\r\n =?UTF-8?Q?", $text); $text = "=?UTF-8?Q?" . $text . "?="; } // if both mb and imap are not available, simply return what was given. // this isn't standards-compliant, and the header will be displayed // incorrectly if it contains accented letters. Let's just hope it won't // be the case too often. :) return $text; }
public function DecodificaMensagem($Mensagem, $Codificacao) { switch ($Codificacao) { case 0: case 1: $Mensagem = imap_8bit($Mensagem); break; case 2: $Mensagem = imap_binary($Mensagem); break; case 3: case 5: case 6: case 7: $Mensagem = imap_base64($Mensagem); break; case 4: $Mensagem = imap_qprint($Mensagem); break; } return $Mensagem; }
function qp_encode($text) { if (function_exists('quoted_printable_encode')) { return quoted_printable_encode($text); } elseif (function_exists('imap_8bit')) { return imap_8bit($text); } else { $arrEncodeSupport = mb_list_encodings(); if (array_search('Quoted-Printable', $arrEncodeSupport) != FALSE) { return mb_convert_encoding($text, 'Quoted-Printable', "JIS"); } else { $crlf = "\r\n"; $text = trim($text); $lines = preg_split("/(\r\n|\n|\r)/s", $text); $out = ''; $temp = ''; foreach ($lines as $line) { for ($j = 0; $j < strlen($line); $j++) { $char = substr($line, $j, 1); $ascii = ord($char); if ($ascii < 32 || $ascii == 61 || $ascii > 126) { $char = '=' . strtoupper(dechex($ascii)); } if (strlen($temp) + strlen($char) >= 76) { $out .= $temp . '=' . $crlf; $temp = ''; } $temp .= $char; } } $out .= $temp; return trim($out); } } }
private function mimeHeaderEncode($text, $encoding = "utf-8") { return "=?{$encoding}?Q?" . imap_8bit($text) . "?="; }
function convert_specialchar($input) { $temp_input = $input; $temp_input = imap_8bit($temp_input); $patterns[0] = '/ /'; $replacements[0] = ' '; $temp_input = preg_replace($patterns, $replacements, $temp_input); return $temp_input; }
/** * Prep Quoted Printable * * Prepares string for Quoted-Printable Content-Transfer-Encoding * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt * * @param string * @return string */ protected function _prep_quoted_printable($str) { // ASCII code numbers for "safe" characters that can always be // used literally, without encoding, as described in RFC 2049. // http://www.ietf.org/rfc/rfc2049.txt static $ascii_safe_chars = array(39, 40, 41, 43, 44, 45, 46, 47, 58, 61, 63, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122); // We are intentionally wrapping so mail servers will encode characters // properly and MUAs will behave, so {unwrap} must go! $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str); // RFC 2045 specifies CRLF as "\r\n". // However, many developers choose to override that and violate // the RFC rules due to (apparently) a bug in MS Exchange, // which only works with "\n". if ($this->crlf === "\r\n") { if (is_php('5.3')) { return quoted_printable_encode($str); } elseif (function_exists('imap_8bit')) { return imap_8bit($str); } } // Reduce multiple spaces & remove nulls $str = preg_replace(array('| +|', '/\\x00+/'), array(' ', ''), $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } $escape = '='; $output = ''; foreach (explode("\n", $str) as $line) { $length = strlen($line); $temp = ''; // Loop through each character in the line to add soft-wrap // characters at the end of a line " =\r\n" and add the newly // processed line(s) to the output (see comment on $crlf class property) for ($i = 0; $i < $length; $i++) { // Grab the next character $char = $line[$i]; $ascii = ord($char); // Convert spaces and tabs but only if it's the end of the line if ($ascii === 32 or $ascii === 9) { if ($i === $length - 1) { $char = $escape . sprintf('%02s', dechex($ascii)); } } elseif ($ascii === 61) { $char = $escape . strtoupper(sprintf('%02s', dechex($ascii))); // =3D } elseif (!in_array($ascii, $ascii_safe_chars, TRUE)) { $char = $escape . strtoupper(sprintf('%02s', dechex($ascii))); } // If we're at the character limit, add the line to the output, // reset our temp variable, and keep on chuggin' if (strlen($temp) + strlen($char) >= 76) { $output .= $temp . $escape . $this->crlf; $temp = ''; } // Add the character to our temporary line $temp .= $char; } // Add our completed line to the output $output .= $temp . $this->crlf; } // get rid of extra CRLF tacked onto the end return substr($output, 0, strlen($this->crlf) * -1); }
$emails = imap_search($inbox, 'SINCE ' . date('d-M-Y', strtotime("-1 day"))); rsort($emails); $header = imap_check($inbox); $range = $header->Nmsgs; if ($emails) { foreach ($emails as $email_number) { $overview = imap_headerinfo($inbox, $email_number); $message = imap_fetchbody($inbox, $email_number, 2); $structure = imap_fetchstructure($inbox, $email_number); if (isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) { $part = $structure->parts[1]; if ($part->encoding == 3) { $message = imap_base64($message); } else { if ($part->encoding == 1) { $message = imap_8bit($message); } else { $message = imap_qprint($message); } } } $output = "<div class='message-text'>"; $output .= "<span><strong>From: </strong>" . imap_utf8($overview->fromaddress) . "</span><br />"; $output .= "<span><strong>Subject: </strong>" . imap_utf8($overview->subject) . "</span><br />"; $output .= "<span><strong>Date: </strong>" . $overview->date . "</span><br />"; $output .= "<span><strong>Message: </strong>" . $message . "</span><br />"; $output .= "</div>"; echo $output; } } ?>
/** * Prep Quoted Printable * * Prepares string for Quoted-Printable Content-Transfer-Encoding * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt * * @param string * @return string */ protected function _prep_quoted_printable($str) { // We are intentionally wrapping so mail servers will encode characters // properly and MUAs will behave, so {unwrap} must go! $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str); // RFC 2045 specifies CRLF as "\r\n". // However, many developers choose to override that and violate // the RFC rules due to (apparently) a bug in MS Exchange, // which only works with "\n". if ($this->crlf === "\r\n") { if (is_php('5.3')) { return quoted_printable_encode($str); } elseif (function_exists('imap_8bit')) { return imap_8bit($str); } } // Reduce multiple spaces & remove nulls $str = preg_replace(array('| +|', '/\\x00+/'), array(' ', ''), $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } $escape = '='; $output = ''; foreach (explode("\n", $str) as $line) { $length = strlen($line); $temp = ''; // Loop through each character in the line to add soft-wrap // characters at the end of a line " =\r\n" and add the newly // processed line(s) to the output (see comment on $crlf class property) for ($i = 0; $i < $length; $i++) { // Grab the next character $char = $line[$i]; $ascii = ord($char); // Convert spaces and tabs but only if it's the end of the line if ($i === $length - 1 && ($ascii === 32 or $ascii === 9)) { $char = $escape . sprintf('%02s', dechex($ascii)); } elseif ($ascii === 61) { $char = $escape . strtoupper(sprintf('%02s', dechex($ascii))); // =3D } // If we're at the character limit, add the line to the output, // reset our temp variable, and keep on chuggin' if (strlen($temp) + strlen($char) >= 76) { $output .= $temp . $escape . $this->crlf; $temp = ''; } // Add the character to our temporary line $temp .= $char; } // Add our completed line to the output $output .= $temp . $this->crlf; } // get rid of extra CRLF tacked onto the end return substr($output, 0, strlen($this->crlf) * -1); }
/** * get attach of the message * * @param string $msg_count * @param string $path * @return array */ public function get_attach($msg_count, $path) { if (!$this->_connect) { return false; } $struckture = imap_fetchstructure($this->_connect, $msg_count); $ar = ""; if ($struckture->parts) { foreach ($struckture->parts as $key => $value) { $enc = $struckture->parts[$key]->encoding; $subtype = $struckture->parts[$key]->subtype; $text_type = array("PLAIN", "HTML", "ALTERNATIVE"); if (in_array($subtype, $text_type)) { continue; } if ($struckture->parts[$key]->ifdparameters) { $name = $this->mail_decode($struckture->parts[$key]->dparameters[0]->value); $cid = $struckture->parts[$key]->id; $cid = substr($cid, 1, strlen($cid) - 2); $disposition = $struckture->parts[$key]->disposition; if (empty($disposition)) { $disposition = "INLINE"; } $name = $cid . "_" . $disposition . "_" . $name; $message = imap_fetchbody($this->_connect, $msg_count, $key + 1); if ($enc == 0) { $message = imap_8bit($message); } if ($enc == 1) { $message = imap_8bit($message); } if ($enc == 2) { $message = imap_binary($message); } if ($enc == 3) { $message = imap_base64($message); } if ($enc == 4) { $message = quoted_printable_decode($message); } if ($enc == 5) { $message = $message; } $fp = fopen($path . urlencode($name), "w"); fwrite($fp, $message); fclose($fp); $ar = $ar . $name . ","; } if ($struckture->parts[$key]->ifparameters && $struckture->parts[$key]->ifdparameters == 0) { if ($struckture->parts[$key]->parameters[0]->attribute == "NAME") { $name = $this->mail_decode($struckture->parts[$key]->parameters[0]->value); } if ($struckture->parts[$key]->parameters[1]->attribute == "NAME") { $name = $this->mail_decode($struckture->parts[$key]->parameters[1]->value); } $cid = $struckture->parts[$key]->id; $cid = substr($cid, 1, strlen($cid) - 2); $disposition = $struckture->parts[$key]->disposition; if (empty($disposition)) { $disposition = "INLINE"; } $name = $cid . "_" . $disposition . "_" . $name; $message = imap_fetchbody($this->_connect, $msg_count, $key + 1); if ($enc == 0) { $message = imap_8bit($message); } if ($enc == 1) { $message = imap_8bit($message); } if ($enc == 2) { $message = imap_binary($message); } if ($enc == 3) { $message = imap_base64($message); } if ($enc == 4) { $message = quoted_printable_decode($message); } if ($enc == 5) { $message = $message; } $fp = fopen($path . urlencode($name), "w"); fwrite($fp, $message); fclose($fp); $ar = $ar . $name . ","; } if ($struckture->parts[$key]->parts) { foreach ($struckture->parts[$key]->parts as $keyb => $valueb) { $enc = $struckture->parts[$key]->parts[$keyb]->encoding; if ($struckture->parts[$key]->parts[$keyb]->ifdparameters) { $name = $this->mail_decode($struckture->parts[$key]->parts[$keyb]->dparameters[0]->value); $id = $struckture->parts[$key]->parts[$keyb]->id; $disposition = $struckture->parts[$key]->parts[$keyb]->disposition; $name = $id . "_" . $disposition . "_" . $name; $partnro = $key + 1 . "." . ($keyb + 1); $message = imap_fetchbody($this->_connect, $msg_count, $partnro); if ($enc == 0) { $message = imap_8bit($message); } if ($enc == 1) { $message = imap_8bit($message); } if ($enc == 2) { $message = imap_binary($message); } if ($enc == 3) { $message = imap_base64($message); } if ($enc == 4) { $message = quoted_printable_decode($message); } if ($enc == 5) { $message = $message; } $fp = fopen($path . urlencode($name), "w"); fwrite($fp, $message); fclose($fp); $ar = $ar . $name . ","; } } } } } $ar = substr($ar, 0, strlen($ar) - 1); return $ar; }
if ($_POST['localpart'] == $_SESSION['localpart']) { $_SESSION['crypt'] = $cryptedpassword; } } else { header("Location: adminuser.php?failupdated={$_POST['localpart']}"); die; } } else { header("Location: adminuser.php?badpass={$_POST['localpart']}"); die; } } if (isset($_POST['vacation']) && is_string($_POST['vacation'])) { $vacation = trim($_POST['vacation']); if (function_exists('imap_8bit')) { $vacation = imap_8bit($vacation); } } else { $vacation = ''; } $query = "UPDATE users SET uid=:uid,\n gid=:gid, smtp=:smtp, pop=:pop,\n realname=:realname,\n admin=:admin,\n on_forward=:on_forward,\n on_piped=:on_piped,\n on_spamassassin=:on_spamassassin,\n on_spambox=:on_spambox,\n on_spamboxreport=:on_spamboxreport,\n on_vacation=:on_vacation,\n enabled=:enabled,\n forward=:forward,\n maxmsgsize=:maxmsgsize,\n quota=:quota,\n sa_tag=:sa_tag,\n sa_refuse=:sa_refuse,\n type=:type,\n vacation=:vacation,\n unseen=:unseen\n WHERE user_id=:user_id"; $sth = $dbh->prepare($query); $success = $sth->execute(array(':uid' => $_POST['uid'], ':gid' => $_POST['gid'], ':smtp' => $smtphomepath, ':pop' => $pophomepath, ':realname' => $_POST['realname'], ':admin' => $_POST['admin'], ':on_forward' => $_POST['on_forward'], ':on_piped' => $_POST['on_piped'], ':on_spamassassin' => $_POST['on_spamassassin'], ':on_spambox' => $_POST['on_spambox'], ':on_spamboxreport' => $_POST['on_spamboxreport'], ':on_vacation' => $_POST['on_vacation'], ':enabled' => $_POST['enabled'], ':forward' => $forwardaddr, ':maxmsgsize' => $_POST['maxmsgsize'], ':quota' => $_POST['quota'], ':sa_tag' => isset($_POST['sa_tag']) ? $_POST['sa_tag'] : 0, ':sa_refuse' => isset($_POST['sa_refuse']) ? $_POST['sa_refuse'] : 0, ':type' => $_POST['type'], ':vacation' => $vacation, ':unseen' => $_POST['unseen'], ':user_id' => $_POST['user_id'])); if ($success) { header("Location: adminuser.php?updated={$_POST['localpart']}"); } else { header("Location: adminuser.php?failupdated={$_POST['localpart']}"); } ?> <!-- Layout and CSS tricks obtained from http://www.bluerobot.com/web/layouts/ -->
/** * 获取邮件附件 * @param $mid 邮件id * @param $path 附件保存路径 * @return string 返回附件名称 */ function GetAttach($mid, $path) { if (!$this->marubox) { return false; } $struckture = imap_fetchstructure($this->marubox, $mid); $ar = ''; if ($struckture->parts) { foreach ($struckture->parts as $key => $value) { $enc = $struckture->parts[$key]->encoding; if ($struckture->parts[$key]->subtype == 'OCTET-STREAM') { $imap_mime_header_decode = imap_mime_header_decode($struckture->parts[$key]->parameters[0]->value); $name = $imap_mime_header_decode[0]->text; $message = imap_fetchbody($this->marubox, $mid, $key + 1); switch ($enc) { case 0: $message = imap_8bit($message); break; 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; case 5: $message = $message; break; } $file_name = time() . '_' . rand(100, 10000) . '_' . $name; $fp = fopen($path . $file_name, "w"); fwrite($fp, $message); fclose($fp); $ar .= $file_name . ','; } } } // 返回附件名 [时间戳_随机数_原始名称] return trim($ar, ','); }
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; }
/** * quoted_printable_encode() * * @link http://php.net/quoted_printable_encode * @param string $str * @return string */ function quoted_printable_encode($str) { if (strlen($str) === 0) { return ''; } elseif (in_array($type = gettype($str), array('array', 'object'), TRUE)) { if ($type === 'object' && method_exists($str, '__toString')) { $str = (string) $str; } else { trigger_error('quoted_printable_encode() expects parameter 1 to be string, ' . $type . ' given', E_USER_WARNING); return NULL; } } if (function_exists('imap_8bit')) { return imap_8bit($str); } $i = $lp = 0; $output = ''; $hex = '0123456789ABCDEF'; $length = extension_loaded('mbstring') && ini_get('mbstring.func_overload') ? mb_strlen($str, '8bit') : strlen($str); while ($length--) { if (($c = $str[$i++]) === "\r" && isset($str[$i]) && $str[$i] === "\n" && $length > 0) { $output .= "\r" . $str[$i++]; $length--; $lp = 0; continue; } if (ctype_cntrl($c) or ord($c) === 0x7f or ord($c) & 0x80 or $c === '=' or $c === ' ' && isset($str[$i]) && $str[$i] === "\r") { if (($lp += 3) > 75 && ord($c) <= 0x7f or ord($c) > 0x7f && ord($c) <= 0xdf && $lp + 3 > 75 or ord($c) > 0xdf && ord($c) <= 0xef && $lp + 6 > 75 or ord($c) > 0xef && ord($c) <= 0xf4 && $lp + 9 > 75) { $output .= "=\r\n"; $lp = 3; } $output .= '=' . $hex[ord($c) >> 4] . $hex[ord($c) & 0xf]; continue; } if (++$lp > 75) { $output .= "=\r\n"; $lp = 1; } $output .= $c; } return $output; }