Ejemplo n.º 1
3
 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 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;
     }
 }
Ejemplo n.º 3
0
 public static function getReadme($owner, $repo)
 {
     $token = self::getAccessToken();
     $readmeUrl = 'https://api.github.com/repos/' . $owner . '/' . $repo . '/readme?access_token=' . $token;
     $client = self::getClient();
     $res = $client->get($readmeUrl, []);
     $readmeHash = json_decode($res->getBody(), true);
     $readme = ['readme' => \Markdown::convertToHtml(imap_base64($readmeHash['content']))];
     return $readme;
 }
Ejemplo n.º 4
0
function getAttachmentData($clientObj, $xml)
{
    $attachment = $clientObj->GetAttachmentsForBusinessObject('KnowledgeArticle', $xml->FieldList->Field[0]);
    if ($attachment != "<Attachments />") {
        $attachment_xml = simplexml_load_string($attachment);
        if ($attachment_xml->Attachment->AttachmentType == 'html') {
            $res = $clientObj->getAttachment($attachment_xml->Attachment['AttachmentId']);
            $atl = simplexml_load_string($res);
            $rawBody = imap_base64($atl);
        } else {
            $rawBody = '';
        }
    } else {
        $rawBody = '';
    }
    return $rawBody;
}
Ejemplo n.º 5
0
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;
	}
Ejemplo n.º 6
0
 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;
     }
 }
Ejemplo n.º 7
0
 /**
  * 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;
     }
 }
Ejemplo n.º 8
0
 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;
 }
Ejemplo n.º 9
0
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;
}
Ejemplo n.º 10
0
 /**
  * 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;
 }
Ejemplo n.º 11
0
 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));
             }
         }
     }
 }
Ejemplo n.º 12
0
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;
}
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 == 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) {
            /* multipart */
            while (list($index, $sub_structure) = each($structure->parts)) {
                if ($part_number) {
                    $prefix = $part_number . '.';
                }
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}
 $content = $contentfirstline . str_replace($firstline, '', $content);
 $content = trim($content);
 //Please uncomment following line, only if you want to check user and password.
 //		echo "<p><b>Login:</b> $user_login, <b>Pass:</b> $user_pass</p>";
 #Check to see if there is an attachment, if there is, save the filename in the temp directory
 #First define some constants and message types
 $type = array("text", "multipart", "message", "application", "audio", "image", "video", "other");
 #message encodings
 $encoding = array("7bit", "8bit", "binary", "base64", "quoted-printable", "other");
 #parse message body (not really used yet, will be used for multiple attachments)
 $attach = parse($struct);
 $attach_parts = get_attachments($attach);
 #get the attachment
 $attachment = imap_fetchbody($mbox, $iCount, 2);
 if ($attachment != '') {
     $attachment = imap_base64($attachment);
     $temp_file = mb_convert_encoding(mb_decode_mimeheader($struct->parts[1]->dparameters[0]->value), $blog_charset, "auto");
     echo $temp_file;
     if (!($temp_fp = fopen("attach/" . $temp_file, "w"))) {
         echo "error1";
         continue;
     }
     fputs($temp_fp, $attachment);
     fclose($temp_fp);
     wp_create_thumbnail("attach/" . $temp_file, 160, "");
 } else {
     $attachment = false;
 }
 if ($xooptDB) {
     $sql = "SELECT ID, user_level FROM {$tableusers} WHERE user_login='******' ORDER BY ID DESC LIMIT 1";
     $result = $wpdb->get_row($sql);
Ejemplo n.º 15
0
$ih = @imap_open("{" . ConfigHelper::getConfig('cashimport.server') . "}INBOX", ConfigHelper::getConfig('cashimport.username'), ConfigHelper::getConfig('cashimport.password'));
if (!$ih) {
    die("Cannot connect to mail server!" . PHP_EOL);
}
$posts = imap_search($ih, ConfigHelper::checkValue(ConfigHelper::getConfig('cashimport.use_seen_flag', true)) ? 'UNSEEN' : 'ALL');
if (!empty($posts)) {
    foreach ($posts as $postid) {
        $post = imap_fetchstructure($ih, $postid);
        if ($post->type == 1) {
            $parts = $post->parts;
            //print_r($parts);
            foreach ($parts as $partid => $part) {
                if ($part->ifdisposition && strtoupper($part->disposition) == 'ATTACHMENT' && $part->type == 0) {
                    $fname = $part->dparameters[0]->value;
                    $msg = imap_fetchbody($ih, $postid, $partid + 1);
                    if ($part->encoding == 3) {
                        $msg = imap_base64($msg);
                    }
                    if (ConfigHelper::checkValue(ConfigHelper::getConfig('cashimport.use_seen_flag', true))) {
                        imap_setflag_full($ih, $postid, "\\Seen");
                    }
                    parse_file($fname, $msg);
                    if (ConfigHelper::checkValue(ConfigHelper::getConfig('cashimport.autocommit', false))) {
                        commit_cashimport();
                    }
                }
            }
        }
    }
}
imap_close($ih);
Ejemplo n.º 16
0
 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.");
 }
Ejemplo n.º 17
0
 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;
 }
Ejemplo n.º 18
0
 protected function initMailPart(IncomingMail $mail, $partStructure, $partNum, $markAsSeen = true)
 {
     $options = FT_UID;
     if (!$markAsSeen) {
         $options |= FT_PEEK;
     }
     $data = $partNum ? imap_fetchbody($this->getImapStream(), $mail->id, $partNum, $options) : imap_body($this->getImapStream(), $mail->id, $options);
     if ($partStructure->encoding == 1) {
         $data = imap_utf8($data);
     } elseif ($partStructure->encoding == 2) {
         $data = imap_binary($data);
     } elseif ($partStructure->encoding == 3) {
         $data = preg_replace('~[^a-zA-Z0-9+=/]+~s', '', $data);
         // https://github.com/barbushin/php-imap/issues/88
         $data = imap_base64($data);
     } elseif ($partStructure->encoding == 4) {
         $data = quoted_printable_decode($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;
             }
         }
     }
     // 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;
         $attachment->disposition = isset($partStructure->disposition) ? $partStructure->disposition : null;
         if ($this->attachmentsDir) {
             $replace = array('/\\s/' => '_', '/[^0-9a-zа-яіїє_\\.]/iu' => '', '/_+/' => '_', '/(^_)|(_$)/' => '');
             $fileSysName = preg_replace('~[\\\\/]~', '', $mail->id . '_' . $attachmentId . '_' . preg_replace(array_keys($replace), $replace, $fileName));
             $attachment->filePath = $this->attachmentsDir . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . $fileSysName;
             file_put_contents($attachment->filePath, $data);
         }
         $mail->addAttachment($attachment);
     } else {
         if (!empty($params['charset'])) {
             $data = $this->convertStringEncoding($data, $params['charset'], $this->serverEncoding);
         }
         if ($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, $markAsSeen);
             } else {
                 $this->initMailPart($mail, $subPartStructure, $partNum . '.' . ($subPartNum + 1), $markAsSeen);
             }
         }
     }
 }
Ejemplo n.º 19
0
 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;
 }
Ejemplo n.º 20
0
 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;
     }
 }
Ejemplo n.º 21
0
 /**
  * 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
 }
Ejemplo n.º 22
0
 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;
 }
Ejemplo n.º 23
0
 /**
  * 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));
     }
 }
Ejemplo n.º 24
0
 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;
 }
Ejemplo n.º 25
0
 /**
  * Get part of message
  *
  * @param      $stream
  * @param      $msgNumber
  * @param      $mimeType
  * @param bool $structure
  * @param bool $partNumber
  *
  * @return mixed
  */
 public function getPart($stream, $msgNumber, $mimeType, $structure = false, $partNumber = false)
 {
     if (!$structure) {
         $structure = imap_fetchstructure($stream, $msgNumber);
     }
     if ($structure) {
         if ($mimeType == $this->getMimeType($structure)) {
             if (!$partNumber) {
                 $partNumber = "1";
             }
             $text = imap_fetchbody($stream, $msgNumber, $partNumber);
             if ($structure->encoding == 3) {
                 return imap_base64($text);
             } else {
                 if ($structure->encoding == 4) {
                     return imap_qprint($text);
                 } else {
                     return $text;
                 }
             }
         }
         $prefix = null;
         if ($structure->type == 1) {
             while (list($index, $subStructure) = each($structure->parts)) {
                 if ($partNumber) {
                     $prefix = $partNumber . '.';
                 }
                 $data = $this->getPart($stream, $msgNumber, $mimeType, $subStructure, $prefix . ($index + 1));
                 if ($data) {
                     return $data;
                 }
             }
         }
     }
     return false;
 }
Ejemplo n.º 26
0
                     $body = imap_fetchbody($ih, $postid, $partid + 1);
                     if ($part->encoding == 3) {
                         $body = imap_base64($body);
                     }
                     $files[] = array('name' => $fname, 'contents' => $body);
                 }
             }
         }
     }
 } elseif ($post->type == 3 && $post->ifdispostion && in_array(strtolower($post->disposition), array('attachment', 'inline')) && $post->ifdparameters) {
     foreach ($part->dparameters as $dparameter) {
         if (strtolower($dparameter->attribute) == 'filename') {
             $fname = $dparameter->value;
             $body = imap_fetchbody($ih, $postid, '1');
             if ($post->encoding == 3) {
                 $body = imap_base64($body);
             }
             $files[] = array('name' => $fname, 'contents' => $body);
         }
     }
 }
 if ($cashimport_use_seen_flag) {
     imap_setflag_full($ih, $postid, "\\Seen");
 }
 if (empty($files)) {
     continue;
 }
 foreach ($files as $file) {
     if (!empty($cashimport_filename_pattern) && !preg_match('/' . $cashimport_filename_pattern . '/', $file['name'])) {
         continue;
     }
Ejemplo n.º 27
0
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;
}
Ejemplo n.º 28
0
 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));
             }
         }
     }
 }
Ejemplo n.º 29
0
 /** 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);
         }
     }
 }
Ejemplo n.º 30
0
 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;
 }