/**
  * Sends out email via Mandrill
  *
  * @param CakeEmail $email
  * @return array
  */
 public function send(CakeEmail $email)
 {
     // CakeEmail
     $this->_cakeEmail = $email;
     $from = $this->_cakeEmail->from();
     list($fromEmail) = array_keys($from);
     $fromName = $from[$fromEmail];
     $this->_config = $this->_cakeEmail->config();
     $this->_headers = $this->_cakeEmail->getHeaders();
     $message = array('html' => $this->_cakeEmail->message('html'), 'text' => $this->_cakeEmail->message('text'), 'subject' => mb_decode_mimeheader($this->_cakeEmail->subject()), 'from_email' => $fromEmail, 'from_name' => $fromName, 'to' => array(), 'headers' => array('Reply-To' => $fromEmail), 'important' => false, 'track_opens' => null, 'track_clicks' => null, 'auto_text' => null, 'auto_html' => null, 'inline_css' => null, 'url_strip_qs' => null, 'preserve_recipients' => null, 'view_content_link' => null, 'tracking_domain' => null, 'signing_domain' => null, 'return_path_domain' => null, 'merge' => true, 'tags' => null, 'subaccount' => null);
     $message = array_merge($message, $this->_headers);
     foreach ($this->_cakeEmail->to() as $email => $name) {
         $message['to'][] = array('email' => $email, 'name' => $name, 'type' => 'to');
     }
     foreach ($this->_cakeEmail->cc() as $email => $name) {
         $message['to'][] = array('email' => $email, 'name' => $name, 'type' => 'cc');
     }
     foreach ($this->_cakeEmail->bcc() as $email => $name) {
         $message['to'][] = array('email' => $email, 'name' => $name, 'type' => 'bcc');
     }
     $attachments = $this->_cakeEmail->attachments();
     if (!empty($attachments)) {
         $message['attachments'] = array();
         foreach ($attachments as $file => $data) {
             $message['attachments'][] = array('type' => $data['mimetype'], 'name' => $file, 'content' => base64_encode(file_get_contents($data['file'])));
         }
     }
     $params = array('message' => $message, "async" => false, "ip_pool" => null, "send_at" => null);
     return $this->_exec($params);
 }
 /**
  * Send mail using Mandrill (by MailChimp)
  *
  * @param \Cake\Network\Email\Email $email Cake Email
  * @return array
  */
 public function send(\Cake\Network\Email\Email $email)
 {
     $this->transportConfig = Hash::merge($this->transportConfig, $this->_config);
     // Initiate a new Mandrill Message parameter array
     $message = ['html' => $email->message(\Cake\Network\Email\Email::MESSAGE_HTML), 'text' => $email->message(\Cake\Network\Email\Email::MESSAGE_TEXT), 'subject' => mb_decode_mimeheader($email->subject()), 'from_email' => key($email->from()), 'from_name' => current($email->from()), 'to' => [], 'headers' => ['Reply-To' => key($email->from())], 'recipient_metadata' => [], 'attachments' => [], 'images' => []];
     // Merge Mandrill Parameters
     $message = array_merge($message, Hash::merge($this->defaultParameters, $email->profile()['Mandrill']));
     // Format attachments
     $message = $this->_attachments($email, $message);
     // Format recipients
     $message = $this->_recipients($email, $message);
     // Create a new scoped Http Client
     $this->http = new Client(['host' => 'mandrillapp.com', 'scheme' => 'https', 'headers' => ['User-Agent' => 'CakePHP Mandrill Plugin']]);
     // Sending as a template? Then in case we find mail content, we add this as a 'template_content'.
     // In you Mandrill template, use <div mc:edit="content"></div> to get the contents of your email
     if (!is_null($message['template_name']) && $message['html']) {
         if (!isset($message['template_content']) || !is_array($message['template_content'])) {
             $message['template_content'] = [];
         }
         $message['template_content'][] = ['name' => 'content', 'content' => $message['html']];
     }
     // Are we sending a template?
     if (!is_null($message['template_name']) && !empty($message['template_content'])) {
         return $this->_sendTemplate($message, $this->transportConfig['async'], $this->transportConfig['ip_pool'], $message['send_at']);
     } else {
         return $this->_send($message, $this->transportConfig['async'], $this->transportConfig['ip_pool'], $message['send_at']);
     }
 }
 /**
  * Sends out email via SparkPost
  *
  * @param CakeEmail $email
  * @return array
  */
 public function send(CakeEmail $email)
 {
     // CakeEmail
     $this->_cakeEmail = $email;
     $this->_config = $this->_cakeEmail->config();
     $this->_headers = $this->_cakeEmail->getHeaders();
     // Not allowed by SparkPost
     unset($this->_headers['Content-Type']);
     unset($this->_headers['Content-Transfer-Encoding']);
     unset($this->_headers['MIME-Version']);
     unset($this->_headers['X-Mailer']);
     $from = $this->_cakeEmail->from();
     list($fromEmail) = array_keys($from);
     $fromName = $from[$fromEmail];
     $message = ['html' => $this->_cakeEmail->message('html'), 'text' => $this->_cakeEmail->message('text'), 'from' => ['name' => $fromName, 'email' => $fromEmail], 'subject' => mb_decode_mimeheader($this->_cakeEmail->subject()), 'recipients' => [], 'transactional' => true];
     foreach ($this->_cakeEmail->to() as $email => $name) {
         $message['recipients'][] = ['address' => ['email' => $email, 'name' => $name], 'tags' => $this->_headers['tags']];
     }
     foreach ($this->_cakeEmail->cc() as $email => $name) {
         $message['recipients'][] = ['address' => ['email' => $email, 'name' => $name], 'tags' => $this->_headers['tags']];
     }
     foreach ($this->_cakeEmail->bcc() as $email => $name) {
         $message['recipients'][] = ['address' => ['email' => $email, 'name' => $name], 'tags' => $this->_headers['tags']];
     }
     unset($this->_headers['tags']);
     $attachments = $this->_cakeEmail->attachments();
     if (!empty($attachments)) {
         $message['attachments'] = array();
         foreach ($attachments as $file => $data) {
             if (!empty($data['contentId'])) {
                 $message['inlineImages'][] = array('type' => $data['mimetype'], 'name' => $data['contentId'], 'data' => base64_encode(file_get_contents($data['file'])));
             } else {
                 $message['attachments'][] = array('type' => $data['mimetype'], 'name' => $file, 'data' => base64_encode(file_get_contents($data['file'])));
             }
         }
     }
     $message = array_merge($message, $this->_headers);
     // Load SparkPost configuration settings
     $config = ['key' => $this->_config['sparkpost']['api_key']];
     if (isset($this->_config['sparkpost']['timeout'])) {
         $config['timeout'] = $this->_config['sparkpost']['timeout'];
     }
     // Set up HTTP request adapter
     $httpAdapter = new Ivory\HttpAdapter\Guzzle6HttpAdapter($this->__getClient());
     // Create SparkPost API accessor
     $sparkpost = new SparkPost\SparkPost($httpAdapter, $config);
     // Send message
     try {
         return $sparkpost->transmission->send($message);
     } catch (SparkPost\APIResponseException $e) {
         // TODO: Determine if BRE is the best exception type
         throw new BadRequestException(sprintf('SparkPost API error %d (%d): %s (%s)', $e->getAPICode(), $e->getCode(), ucfirst($e->getAPIMessage()), $e->getAPIDescription()));
     }
 }
 public function getHeader($name, $format = null)
 {
     $result = parent::getHeader($name, $format);
     if ('array' !== $format && function_exists('mb_decode_mimeheader')) {
         $result = mb_decode_mimeheader($result);
     }
     if ('from' === strtolower($name) || 'to' === strtolower($name)) {
         $result = $this->extractAddrSpec($result);
     }
     return $result;
 }
Example #5
0
 function convert_mail_str($str, $to = "", $from = "")
 {
     $str = mb_decode_mimeheader($str);
     if ($to != "" && $from != "") {
         $str = mb_convert_encoding($str, $to, $from);
     } else {
         if ($to != "") {
             $str = mb_convert_encoding($str, $to, "auto");
         }
     }
     return $str;
 }
 /**
  * Send mail
  *
  * @param \Cake\Mailer\Email $email Email instance.
  * @return array
  */
 public function send(Email $email)
 {
     $this->transportConfig = Hash::merge($this->transportConfig, $this->_config);
     $message = ['html' => $email->message(Email::MESSAGE_HTML), 'text' => $email->message(Email::MESSAGE_TEXT), 'subject' => mb_decode_mimeheader($email->subject()), 'from' => key($email->from()), 'fromname' => current($email->from()), 'to' => [], 'toname' => [], 'cc' => [], 'ccname' => [], 'bcc' => [], 'bccname' => [], 'replyto' => array_keys($email->replyTo())[0]];
     // Add receipients
     foreach (['to', 'cc', 'bcc'] as $type) {
         foreach ($email->{$type}() as $mail => $name) {
             $message[$type][] = $mail;
             $message[$type . 'name'][] = $name;
         }
     }
     // Create a new scoped Http Client
     $this->http = new Client(['host' => 'api.sendgrid.com', 'scheme' => 'https', 'headers' => ['User-Agent' => 'CakePHP SendGrid Plugin']]);
     $message = $this->_attachments($email, $message);
     return $this->_send($message);
 }
 /**
  * Parse attachments from message mimeparts.
  */
 function process(&$message, $source)
 {
     $message['attachments'] = array();
     foreach ($message['mimeparts'] as $attachment) {
         // 'unnamed_attachment' files are not really attachments, but mimeparts like HTML or Plain Text.
         // We only want to save real attachments, like images and files.
         if ($attachment->filename !== 'unnamed_attachment') {
             $destination = 'temporary://';
             $filename = mb_decode_mimeheader($attachment->filename);
             $file = file_save_data($attachment->data, $destination . $filename);
             $file->status = 0;
             drupal_write_record('file_managed', $file, 'fid');
             $message['attachments'][] = new FeedsEnclosure($file->uri, $attachment->filemime);
         }
     }
     unset($message['mimeparts']);
 }
Example #8
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));
             }
         }
     }
 }
 /**
  * Parse attachments from message mimeparts.
  */
 public function process(&$message, $source)
 {
     $message['attachments'] = array();
     foreach ($message['mimeparts'] as $attachment) {
         // 'unnamed_attachment' files are not really attachments, but mimeparts like HTML or Plain Text.
         // We only want to save real attachments, like images and files.
         if ($attachment->filename !== 'unnamed_attachment') {
             $destination = 'public://mailhandler_temp/';
             file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
             $filename = mb_decode_mimeheader($attachment->filename);
             $file = file_save_data($attachment->data, $destination . $filename);
             $file->status = 0;
             drupal_write_record('file_managed', $file, 'fid');
             if (!empty($attachment->id)) {
                 $cid = trim($attachment->id, '<>');
                 $uri = 'cid:' . $cid;
                 $message['body_html'] = str_replace($uri, $file->uri, $message['body_html']);
             }
             $message['attachments'][] = new FeedsEnclosure($file->uri, $attachment->filemime);
         }
     }
     unset($message['mimeparts']);
 }
 /**
  * Send mail via SparkPost REST API
  *
  * @param \Cake\Mailer\Email $email Email message
  * @return array
  */
 public function send(Email $email)
 {
     // Load SparkPost configuration settings
     $apiKey = $this->config('apiKey');
     // Set up HTTP request adapter
     $adapter = new CakeHttpAdapter(new Client());
     // Create SparkPost API accessor
     $sparkpost = new SparkPost($adapter, ['key' => $apiKey]);
     // Pre-process CakePHP email object fields
     $from = (array) $email->from();
     $sender = sprintf('%s <%s>', mb_encode_mimeheader(array_values($from)[0]), array_keys($from)[0]);
     $to = (array) $email->to();
     $recipients = [['address' => ['name' => mb_encode_mimeheader(array_values($to)[0]), 'email' => array_keys($to)[0]]]];
     // Build message to send
     $message = ['from' => $sender, 'html' => empty($email->message('html')) ? $email->message('text') : $email->message('html'), 'text' => $email->message('text'), 'subject' => mb_decode_mimeheader($email->subject()), 'recipients' => $recipients];
     // Send message
     try {
         $sparkpost->transmission->send($message);
     } catch (APIResponseException $e) {
         // TODO: Determine if BRE is the best exception type
         throw new BadRequestException(sprintf('SparkPost API error %d (%d): %s (%s)', $e->getAPICode(), $e->getCode(), ucfirst($e->getAPIMessage()), $e->getAPIDescription()));
     }
 }
Example #11
0
function plugin_forumml_show_search_results($p, $result, $group_id, $list_id)
{
    echo "<table width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th class=forumml>" . $GLOBALS['Language']->getText('plugin_forumml', 'thread') . "\n\t\t\t\t</th>\n\t\t\t\t<th class=forumml>" . $GLOBALS['Language']->getText('plugin_forumml', 'submitted_on') . "\n\t\t\t\t</th>\n\t\t\t\t<th class=forumml>" . $GLOBALS['Language']->getText('plugin_forumml', 'author') . "\n\t\t\t\t</th>\n\t\t\t</tr>";
    $idx = 0;
    // Build a table full of search results
    while ($rows = db_fetch_array($result)) {
        $idx++;
        if ($idx % 2 == 0) {
            $class = "boxitemalt";
        } else {
            $class = "boxitem";
        }
        $sql1 = sprintf('SELECT value, body' . ' FROM plugin_forumml_message m, plugin_forumml_messageheader mh' . ' WHERE m.id_message = %d' . ' AND mh.id_message = %d' . ' AND m.id_list = %d' . ' AND mh.id_header = %s', db_ei($rows['id_message']), db_ei($rows['id_message']), db_ei($list_id), FORUMML_SUBJECT);
        $res1 = db_query($sql1);
        $subject = mb_decode_mimeheader(db_result($res1, 0, 'value'));
        $sql2 = sprintf('SELECT value FROM plugin_forumml_messageheader' . ' WHERE id_message = %d' . ' LIMIT 1,2', db_ei($rows['id_message']));
        $res2 = db_query($sql2);
        $k = 1;
        while ($rows2 = db_fetch_array($res2)) {
            $header[$k] = $rows2['value'];
            $k++;
        }
        $from = mb_decode_mimeheader($header[2]);
        // Replace '<' by '&lt;' and '>' by '&gt;'. Otherwise the email adress won't be displayed
        // because it will be considered as an xhtml tag.
        $from = preg_replace('/\\</', '&lt;', $from);
        $from = preg_replace('/\\>/', '&gt;', $from);
        $date = date("Y-m-d H:i", strtotime($header[1]));
        // purify message subject (CODENDI_PURIFIER_FORUMML level)
        $hp =& ForumML_HTMLPurifier::instance();
        $subject = $hp->purify($subject, CODENDI_PURIFIER_FORUMML);
        // display the resulting threads in rows
        printf("<tr class='" . $class . "'>\n\t\t\t\t\t<td class='subject'>\n\t\t\t\t\t\t&nbsp;<img src='" . $p->getThemePath() . "/images/ic/comment.png'/>\n    \t\t\t\t\t<a href='message.php?group_id=" . $group_id . "&topic=" . $rows['id_message'] . "&list=" . $list_id . "'><b>%s</b></a>\t\t\t\t\t\t\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>\t\t\t\t\t\t\n         \t\t\t\t<font class='info'>%s</font>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<font class='info'>%s</font>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>", $subject, $date, $from);
    }
    echo "</table>";
}
function decodeHeader($header)
{
    return mb_decode_mimeheader($header);
}
 /**
  * Decode the specified string using the current charset
  *
  * @param string $text String to decode
  * @return string Decoded string
  */
 protected function _decode($text)
 {
     $restore = mb_internal_encoding();
     mb_internal_encoding(Configure::read('App.encoding'));
     $return = mb_decode_mimeheader($text);
     mb_internal_encoding($restore);
     return $return;
 }
// define some classes
class classWithToString
{
    public function __toString()
    {
        return "Class A object";
    }
}
class classWithoutToString
{
}
// heredoc string
$heredoc = <<<EOT
hello world
EOT;
// get a resource variable
$fp = fopen(__FILE__, "r");
// add arrays
$index_array = array(1, 2, 3);
$assoc_array = array('one' => 1, 'two' => 2);
//array of values to iterate over
$inputs = array('int 0' => 0, 'int 1' => 1, 'int 12345' => 12345, 'int -12345' => -2345, 'float 10.5' => 10.5, 'float -10.5' => -10.5, 'float 12.3456789000e10' => 123456789000.0, 'float -12.3456789000e10' => -123456789000.0, 'float .5' => 0.5, 'empty array' => array(), 'int indexed array' => $index_array, 'associative array' => $assoc_array, 'nested arrays' => array('foo', $index_array, $assoc_array), 'uppercase NULL' => NULL, 'lowercase null' => null, 'lowercase true' => true, 'lowercase false' => false, 'uppercase TRUE' => TRUE, 'uppercase FALSE' => FALSE, 'empty string DQ' => "", 'empty string SQ' => '', 'instance of classWithToString' => new classWithToString(), 'instance of classWithoutToString' => new classWithoutToString(), 'undefined var' => @$undefined_var, 'unset var' => @$unset_var, 'resource' => $fp);
// loop through each element of the array for string
foreach ($inputs as $key => $value) {
    echo "\n--{$key}--\n";
    var_dump(mb_decode_mimeheader($value));
}
fclose($fp);
?>
===DONE===
 $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);
     if (!$result) {
 function renderSubject(MailQueue $m)
 {
     $s = $m->subject;
     if (strpos($s, '=?') === 0) {
         $s = mb_decode_mimeheader($s);
     }
     return "<td>" . Am_Controller::escape($s) . "</td>";
 }
Example #17
0
 /**
  * @param string|array $value
  * @return string
  */
 protected function decodeHeader($value)
 {
     if (is_array($value)) {
         foreach ($value as &$v) {
             $v = $this->decodeHeader($v);
         }
         unset($v);
         return $value;
     }
     if (preg_match("/=\\?(.+)\\?(B|Q)\\?(.*)\\?=?(.*)/i", $value, $m)) {
         $value = ltrim($value);
         if (isset($m[3]) && strpos($m[3], '_') !== false && strpos($m[3], ' ') === false) {
             $value = iconv_mime_decode(str_replace("\n", "", $value), 0, 'UTF-8');
         } else {
             $temp = mb_decode_mimeheader($value);
             if ($temp === $value) {
                 $value = iconv_mime_decode($value, 0, 'UTF-8');
             } else {
                 $value = $temp;
             }
         }
     } elseif (isset($this->part['params']['charset'])) {
         $value = @iconv($this->part['params']['charset'], 'UTF-8', $value);
     }
     if (!preg_match('//u', $value)) {
         $charset = mb_detect_encoding($value);
         if ($charset && ($temp = iconv($charset, 'UTF-8', $value))) {
             $value = $temp;
         }
     }
     return $value;
 }
Example #18
0
 public function processIncomingEmailAccount(IncomingEmailAccount $account)
 {
     $count = 0;
     if ($emails = $account->getUnprocessedEmails()) {
         try {
             $current_user = framework\Context::getUser();
             foreach ($emails as $email) {
                 $user = $this->getOrCreateUserFromEmailString($email->from);
                 if ($user instanceof User) {
                     if (framework\Context::getUser()->getID() != $user->getID()) {
                         framework\Context::switchUserContext($user);
                     }
                     $message = $account->getMessage($email);
                     $data = $message->getBodyPlain() ? $message->getBodyPlain() : strip_tags($message->getBodyHTML());
                     if ($data) {
                         if (mb_detect_encoding($data, 'UTF-8', true) === false) {
                             $data = utf8_encode($data);
                         }
                         $new_data = '';
                         foreach (explode("\n", $data) as $line) {
                             $line = trim($line);
                             if ($line) {
                                 $line = preg_replace('/^(_{2,}|-{2,})$/', "<hr>", $line);
                                 $new_data .= $line . "\n";
                             } else {
                                 $new_data .= "\n";
                             }
                         }
                         $data = nl2br($new_data, false);
                     }
                     // Parse the subject, and obtain the issues.
                     $parsed_commit = Issue::getIssuesFromTextByRegex(mb_decode_mimeheader($email->subject));
                     $issues = $parsed_commit["issues"];
                     // If any issues were found, add new comment to each issue.
                     if ($issues) {
                         foreach ($issues as $issue) {
                             $text = preg_replace('#(^\\w.+:\\n)?(^>.*(\\n|$))+#mi', "", $data);
                             $text = trim($text);
                             if (!$this->processIncomingEmailCommand($text, $issue) && $user->canPostComments()) {
                                 $comment = new Comment();
                                 $comment->setContent($text);
                                 $comment->setPostedBy($user);
                                 $comment->setTargetID($issue->getID());
                                 $comment->setTargetType(Comment::TYPE_ISSUE);
                                 $comment->save();
                             }
                         }
                     } else {
                         if ($user->canReportIssues($account->getProject())) {
                             $issue = new Issue();
                             $issue->setProject($account->getProject());
                             $issue->setTitle(mb_decode_mimeheader($email->subject));
                             $issue->setDescription($data);
                             $issue->setPostedBy($user);
                             $issue->setIssuetype($account->getIssuetype());
                             $issue->save();
                             // Append the new issue to the list of affected issues. This
                             // is necessary in order to process the attachments properly.
                             $issues[] = $issue;
                         }
                     }
                     // If there was at least a single affected issue, and mail
                     // contains attachments, add those attachments to related issues.
                     if ($issues && $message->hasAttachments()) {
                         foreach ($message->getAttachments() as $attachment_no => $attachment) {
                             echo 'saving attachment ' . $attachment_no;
                             $name = $attachment['filename'];
                             $new_filename = framework\Context::getUser()->getID() . '_' . NOW . '_' . basename($name);
                             if (framework\Settings::getUploadStorage() == 'files') {
                                 $files_dir = framework\Settings::getUploadsLocalpath();
                                 $filename = $files_dir . $new_filename;
                             } else {
                                 $filename = $name;
                             }
                             Logging::log('Creating issue attachment ' . $filename . ' from attachment ' . $attachment_no);
                             echo 'Creating issue attachment ' . $filename . ' from attachment ' . $attachment_no;
                             $content_type = $attachment['type'] . '/' . $attachment['subtype'];
                             $file = new File();
                             $file->setRealFilename($new_filename);
                             $file->setOriginalFilename(basename($name));
                             $file->setContentType($content_type);
                             $file->setDescription($name);
                             $file->setUploadedBy(framework\Context::getUser());
                             if (framework\Settings::getUploadStorage() == 'database') {
                                 $file->setContent($attachment['data']);
                             } else {
                                 Logging::log('Saving file ' . $new_filename . ' with content from attachment ' . $attachment_no);
                                 file_put_contents($new_filename, $attachment['data']);
                             }
                             $file->save();
                             // Attach file to each related issue.
                             foreach ($issues as $issue) {
                                 $issue->attachFile($file);
                             }
                         }
                     }
                     $count++;
                 }
             }
         } catch (\Exception $e) {
         }
         if (framework\Context::getUser()->getID() != $current_user->getID()) {
             framework\Context::switchUserContext($current_user);
         }
     }
     $account->setTimeLastFetched(time());
     $account->setNumberOfEmailsLastFetched($count);
     $account->save();
     return $count;
 }
 /**
  * Decode MIME header elements
  *
  * @param string $header
  * @return string
  */
 protected function _mimeHeaderDecode($header)
 {
     return mb_decode_mimeheader($header);
     //return iconv_mime_decode($header, 0, 'UTF-8');
     /*
     $utf8Header = imap_utf8($header);
     $decoded = imap_mime_header_decode($utf8Header);
     if (isset($decoded[0])) {
         $decodedObj = $decoded[0];
         return $decodedObj->text;
     } else {
         return $utf8Header;
     }
     */
 }
Example #20
0
 /**
  * Secret Sauce - Transform an email string
  * response to array key value format
  *
  * @param *string      $email    The actual email
  * @param string|null  $uniqueId The mail UID
  * @param array        $flags    Any mail flags
  *
  * @return array
  */
 private function getEmailFormat($email, $uniqueId = null, array $flags = array())
 {
     //if email is an array
     if (is_array($email)) {
         //make it into a string
         $email = implode("\n", $email);
     }
     //split the head and the body
     $parts = preg_split("/\n\\s*\n/", $email, 2);
     $head = $parts[0];
     $body = null;
     if (isset($parts[1]) && trim($parts[1]) != ')') {
         $body = $parts[1];
     }
     $lines = explode("\n", $head);
     $head = array();
     foreach ($lines as $line) {
         if (trim($line) && preg_match("/^\\s+/", $line)) {
             $head[count($head) - 1] .= ' ' . trim($line);
             continue;
         }
         $head[] = trim($line);
     }
     $head = implode("\n", $head);
     $recipientsTo = $recipientsCc = $recipientsBcc = $sender = array();
     //get the headers
     $headers1 = imap_rfc822_parse_headers($head);
     $headers2 = $this->getHeaders($head);
     //set the from
     $sender['name'] = null;
     if (isset($headers1->from[0]->personal)) {
         $sender['name'] = $headers1->from[0]->personal;
         //if the name is iso or utf encoded
         if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($sender['name']))) {
             //decode the subject
             $sender['name'] = str_replace('_', ' ', mb_decode_mimeheader($sender['name']));
         }
     }
     $sender['email'] = $headers1->from[0]->mailbox . '@' . $headers1->from[0]->host;
     //set the to
     if (isset($headers1->to)) {
         foreach ($headers1->to as $to) {
             if (!isset($to->mailbox, $to->host)) {
                 continue;
             }
             $recipient = array('name' => null);
             if (isset($to->personal)) {
                 $recipient['name'] = $to->personal;
                 //if the name is iso or utf encoded
                 if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($recipient['name']))) {
                     //decode the subject
                     $recipient['name'] = str_replace('_', ' ', mb_decode_mimeheader($recipient['name']));
                 }
             }
             $recipient['email'] = $to->mailbox . '@' . $to->host;
             $recipientsTo[] = $recipient;
         }
     }
     //set the cc
     if (isset($headers1->cc)) {
         foreach ($headers1->cc as $cc) {
             $recipient = array('name' => null);
             if (isset($cc->personal)) {
                 $recipient['name'] = $cc->personal;
                 //if the name is iso or utf encoded
                 if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($recipient['name']))) {
                     //decode the subject
                     $recipient['name'] = str_replace('_', ' ', mb_decode_mimeheader($recipient['name']));
                 }
             }
             $recipient['email'] = $cc->mailbox . '@' . $cc->host;
             $recipientsCc[] = $recipient;
         }
     }
     //set the bcc
     if (isset($headers1->bcc)) {
         foreach ($headers1->bcc as $bcc) {
             $recipient = array('name' => null);
             if (isset($bcc->personal)) {
                 $recipient['name'] = $bcc->personal;
                 //if the name is iso or utf encoded
                 if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($recipient['name']))) {
                     //decode the subject
                     $recipient['name'] = str_replace('_', ' ', mb_decode_mimeheader($recipient['name']));
                 }
             }
             $recipient['email'] = $bcc->mailbox . '@' . $bcc->host;
             $recipientsBcc[] = $recipient;
         }
     }
     //if subject is not set
     if (!isset($headers1->subject) || strlen(trim($headers1->subject)) === 0) {
         //set subject
         $headers1->subject = self::NO_SUBJECT;
     }
     //trim the subject
     $headers1->subject = str_replace(array('<', '>'), '', trim($headers1->subject));
     //if the subject is iso or utf encoded
     if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($headers1->subject))) {
         //decode the subject
         $headers1->subject = str_replace('_', ' ', mb_decode_mimeheader($headers1->subject));
     }
     //set thread details
     $topic = isset($headers2['thread-topic']) ? $headers2['thread-topic'] : $headers1->subject;
     $parent = isset($headers2['in-reply-to']) ? str_replace('"', '', $headers2['in-reply-to']) : null;
     //set date
     $date = isset($headers1->date) ? strtotime($headers1->date) : null;
     //set message id
     if (isset($headers2['message-id'])) {
         $messageId = str_replace('"', '', $headers2['message-id']);
     } else {
         $messageId = '<eden-no-id-' . md5(uniqid()) . '>';
     }
     $attachment = isset($headers2['content-type']) && strpos($headers2['content-type'], 'multipart/mixed') === 0;
     $format = array('id' => $messageId, 'parent' => $parent, 'topic' => $topic, 'mailbox' => $this->mailbox, 'uid' => $uniqueId, 'date' => $date, 'subject' => str_replace('’', '\'', $headers1->subject), 'from' => $sender, 'flags' => $flags, 'to' => $recipientsTo, 'cc' => $recipientsCc, 'bcc' => $recipientsBcc, 'attachment' => $attachment);
     if (trim($body) && $body != ')') {
         //get the body parts
         $parts = $this->getParts($email);
         //if there are no parts
         if (empty($parts)) {
             //just make the body as a single part
             $parts = array('text/plain' => $body);
         }
         //set body to the body parts
         $body = $parts;
         //look for attachments
         $attachment = array();
         //if there is an attachment in the body
         if (isset($body['attachment'])) {
             //take it out
             $attachment = $body['attachment'];
             unset($body['attachment']);
         }
         $format['body'] = $body;
         $format['attachment'] = $attachment;
     }
     return $format;
 }
Example #21
0
function search_quarantine()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $textsearch = "{select_messages} ";
    if ($_GET["zDate"] != null) {
        $q_zdate = ParseQueryDate($_GET["zDate"], "zDate");
        $textsearch = $textsearch . "{from_date}: {$_GET["zDate"]}";
    }
    $limit = "LIMIT 0,100";
    if ($_GET["mailfrom"] != null) {
        $_GET["mailfrom"] = str_replace('*', '%', $_GET["mailfrom"]);
        $q_mailfrom = "AND mailfrom LIKE '{$_GET["mailfrom"]}%'";
        $textsearch = $textsearch . " {and} {from}:{$_GET["mailfrom"]}";
    }
    if ($_GET["recipient"] != null) {
        $_GET["recipient"] = str_replace('*', '%', $_GET["recipient"]);
        $q_mailfrom = $q_mailfrom . " AND mailto LIKE '{$_GET["recipient"]}%'";
        $textsearch = $textsearch . " {and} {recipient}:{$_GET["recipient"]}";
    }
    if ($_GET["subject"] != null) {
        $_GET["subject"] = str_replace('*', '%', $_GET["subject"]);
        $q_mailfrom = $q_mailfrom . " AND subject LIKE '{$_GET["subject"]}%'";
        $textsearch = $textsearch . " {and} {subject}:{$_GET["subject"]}";
    }
    $sql = "SELECT MessageID,zDate,mailfrom,subject,mailto FROM quarantine WHERE 1 {$q_zdate} {$q_mailfrom} ORDER BY zDate DESC {$limit}";
    $sql = str_replace('%%', '%', $sql);
    $q = new mysql();
    $html = "\n\t<div class=explain>{$textsearch}</div>\n<table cellspacing='0' cellpadding='0' border='0' class='tableView' style='width:100%'>\n<thead class='thead'>\n\t<tr>\n\t\t<th>{date}</th>\n\t\t<th>{from}</th>\n\t\t<th>{to}</th>\n\t</tr>\n</thead>\n<tbody class='tbody'>";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        if ($classtr == "oddRow") {
            $classtr = null;
        } else {
            $classtr = "oddRow";
        }
        if (trim($ligne["mailfrom"]) == null) {
            $ligne["mailfrom"] = "&nbsp;";
        }
        if (trim($ligne["delivery_user"]) == null) {
            $ligne["sender_user"] = "******";
        }
        $ligne["mailfrom"] = wordwrap($ligne["mailfrom"], 20, "<br />\n", true);
        $ligne["mailto"] = wordwrap($ligne["mailto"], 20, "<br />\n", true);
        mb_internal_encoding("UTF-8");
        $ligne["subject"] = mb_decode_mimeheader($ligne["subject"]);
        $ligne["subject"] = wordwrap($ligne["subject"], 85, "<br />\n", true);
        //$ligne["subject"]=utf8_encode($ligne["subject"]);
        $link = "<a href=\"javascript:blur()\" OnClick=\"javascript:Loadjs('domains.quarantine.php?message-id=" . urlencode($ligne["MessageID"]) . "')\" style='text-decoration:underline'>";
        $html = $html . "\n\t\t\t<tr class={$classtr}>\t\n\t\t\t<td width=1% nowrap style='font-size:14px'>{$link}{$ligne["zDate"]}</a></td>\n\t\t\t<td width=1% nowrap style='font-size:14px'>{$link}{$ligne["mailfrom"]}</a></td>\n\t\t\t<td width=1% nowrap style='font-size:14px'>{$link}{$ligne["mailto"]}</a></td>\n\t\t\t</tr>\n\t\t\t<tr class={$classtr}>\n\t\t\t<td width=99% style='font-size:14px' colspan=3><i style='font-weight:bold'>{$link}{$ligne["subject"]}</a></i></td>\n\t\t\t</tr>\n\t\t\t";
    }
    $html = $html . "</table>";
    echo $tpl->_ENGINE_parse_body($html);
}
Example #22
0
 /**
  * Load structure and save every part of message to common array EmbeddedMessage::$structure
  */
 private function loadStructure()
 {
     $this->rawMimeHeader = imap_fetchmime($this->stream, $this->messageNumber, $this->partNumber, FT_UID);
     $this->parsedHeader = imap_rfc822_parse_headers($this->getContent());
     if (!count((array) $this->parsedHeader)) {
         $this->parsedHeader = imap_rfc822_parse_headers($this->rawMimeHeader);
     }
     //Message ID
     $this->id = $this->parsedHeader->message_id;
     //Email from
     $emailFrom = $this->parsedHeader->from[0];
     $emailFrom->personal = isset($emailFrom->personal) ? $emailFrom->personal : null;
     $this->from = new EmailAddress($emailFrom->mailbox, $emailFrom->host, imap_utf8($emailFrom->personal));
     //EmailsTo
     $emailsTo = [];
     $parsedEmails = $this->parsedHeader->to;
     foreach ($parsedEmails as $email) {
         $email->personal = isset($email->personal) ? $email->personal : null;
         $emailsTo[] = new EmailAddress($email->mailbox, $email->host, imap_utf8($email->personal));
     }
     $this->to = $emailsTo;
     //EmailsCC
     $emailsCc = [];
     $parsedEmails = isset($this->parsedHeader->cc) ? $this->parsedHeader->cc : [];
     foreach ($parsedEmails as $email) {
         $email->personal = isset($email->personal) ? $email->personal : null;
         $emailsCc[] = new EmailAddress($email->mailbox, $email->host, imap_utf8($email->personal));
     }
     $this->cc = $emailsCc;
     //Date
     $this->date = new \DateTime($this->parsedHeader->date);
     //Subject
     if (preg_match('/=\\?(.*?)\\?(.*?)\\?/', $this->parsedHeader->subject, $matchSubject)) {
         $subjectEncoding = strtolower($matchSubject[1]);
         switch ($subjectEncoding) {
             case "utf-8":
                 $this->subject = mb_decode_mimeheader($this->parsedHeader->subject);
                 break;
             default:
                 $this->subject = quoted_printable_decode(imap_utf8($this->parsedHeader->subject));
                 break;
         }
     } else {
         $this->subject = imap_utf8($this->parsedHeader->subject);
     }
     $this->structure = $this->parseStructure();
     //extract attachments from common structure
     $this->attachments = $this->parseAttachments();
 }
Example #23
0
 /**
  * Normalize encoded words  (via. RFC2047)
  * 
  * @param string $words 
  * @return string decoded string
  */
 private function _normalizeEncodedWords($words)
 {
     $words = trim($words);
     $charset = "";
     $encoding = "";
     if (preg_match('/=\\?(.+?)\\?(B|Q)\\?(.+?)\\?=/i', $words, $m)) {
         $charset = $m[1];
         $encoding = strtoupper($m[2]);
         if (strtolower($charset) == 'iso-2022-jp') {
             $words = preg_replace('/\\?ISO-2022-JP\\?/i', '?ISO-2022-JP-MS?', $words);
         }
     }
     if ($encoding != "") {
         $words = mb_decode_mimeheader($words);
     }
     return $words;
 }
 /**
  * 	ISO Clean
  *
  *	@param string
  *	@return string
  */
 function iso_clean($str)
 {
     if (stristr($str, '=?') === FALSE) {
         return $str;
     }
     // -------------------------------------------------
     //  There exists two functions that do this for us
     //  but they are not available on all servers and some
     //  seem to work better than others I have found. The
     //  base64_decode() method works for many encodings
     //  but I am not sure how well it handles non Latin
     //  characters.
     //
     //  The mb_decode_mimeheader() function seems to trim
     //  any line breaks off the end of the str, so we put
     //  those back because we need it for the Header
     //  matching stuff.  I added it on for the imap_utf8()
     //  function just in case.
     // -------------------------------------------------
     if (function_exists('imap_utf8') && strtoupper($this->EE->config->item('charset')) == 'UTF-8') {
         return rtrim(imap_utf8($str)) . "\r\n";
     }
     if (function_exists('mb_decode_mimeheader')) {
         // mb_decode_mimeheader() doesn't replace underscores
         return str_replace('_', ' ', rtrim(mb_decode_mimeheader($str))) . "\r\n";
     }
     if (function_exists('iconv_mime_decode')) {
         return rtrim(iconv_mime_decode($str)) . "\r\n";
     }
     if (substr(trim($str), -2) != '?=') {
         $str = trim($str) . '?=';
     }
     if (preg_match("|\\=\\?iso\\-(.*?)\\?[A-Z]{1}\\?(.*?)\\?\\=|i", trim($str), $mime)) {
         if ($mime['1'] == '8859-1') {
             $charHex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
             for ($z = 0, $sz = count($charHex); $z < $sz; ++$z) {
                 for ($i = 0, $si = count($charHex); $i < $si; ++$i) {
                     $mime['2'] = str_replace('=' . $charHex[$z] . $charHex[$i], chr(hexdec($charHex[$z] . $charHex[$i])), $mime['2']);
                 }
             }
             $str = str_replace($mime['0'], $mime['2'], $str);
         } else {
             $str = str_replace($mime['0'], base64_decode($mime['2']), $str);
         }
         $str = str_replace('_', ' ', $str);
     }
     return ltrim($str);
 }
function wp_getattach($content, $prefix = "", $create_thumbs = 0)
{
    $contents = explode("\r\n\r\n", $content);
    $subtype = preg_match("/Content-Type: [^\\/]*\\/([^\\;]*);/", $contents[0], $matches);
    if ($subtype) {
        $subtype = strtolower($matches[1]);
    }
    $temp_file = "";
    if (in_array($subtype, array("gif", "jpg", "jpeg", "png"))) {
        if ($prefix == 0 && eregi("name=\"?([^\"\n]+)\"?", $contents[0], $filereg)) {
            $filename = ereg_replace("[\t\r\n]", "", $filereg[1]);
            if (function_exists('mb_convert_encoding')) {
                $temp_file = mb_convert_encoding(mb_decode_mimeheader($filename, $blog_charset, "auto"));
            } else {
                $temp_file = $filename;
            }
        }
        // 添付データをデコードして保存
        if (eregi("Content-Transfer-Encoding:.*base64", $contents[0])) {
            $tmp = base64_decode($contents[1]);
            if (!$temp_file) {
                $temp_file_base = $prefix . "_" . time();
            } else {
                $temp_file_info = pathinfo($temp_file);
                $temp_file_base = basename($temp_file, "." . $temp_file_info["extension"]);
            }
            $i = 0;
            $temp_file = $temp_file_base . ".{$subtype}";
            while (file_exists("attach/" . $temp_file)) {
                $temp_file = $temp_file_base . "-" . $i . ".{$subtype}";
                $i++;
            }
            if (!($temp_fp = fopen("attach/" . $temp_file, "wb"))) {
                echo "Error1<br/>\n";
                continue;
            }
            fputs($temp_fp, $tmp);
            fclose($temp_fp);
            if ($create_thumbs) {
                wp_create_thumbnail("attach/" . $temp_file, 180, "");
            }
        }
        echo "{$temp_file} <br/>\n";
        return $temp_file;
    }
    return false;
}
 } else {
     if (preg_match('/Content-Type: /', $line)) {
         $content_type = trim($line);
         $content_type = substr($content_type, 14, strlen($content_type) - 14);
         $content_type = explode(';', $content_type);
         $content_type = $content_type[0];
     }
     if ($content_type == 'multipart/alternative' && preg_match('/boundary="/', $line) && $boundary == '') {
         $boundary = trim($line);
         $boundary = explode('"', $boundary);
         $boundary = $boundary[1];
     }
     if (preg_match('/Subject: /', $line)) {
         $subject = trim($line);
         $subject = substr($subject, 9, strlen($subject) - 9);
         $subject = mb_decode_mimeheader($subject);
         if ($use_phoneemail) {
             $subject = explode($phoneemail_separator, $subject);
             $subject = trim($subject[0]);
             echo $subject . "<br/>";
         }
         if (!ereg($subjectprefix, $subject)) {
             continue;
         }
     }
     if (preg_match('/Date: /', $line)) {
         // of the form '20 Mar 2002 20:32:37'
         $ddate = trim($line);
         $ddate = str_replace('Date: ', '', $ddate);
         if (strpos($ddate, ',')) {
             $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate)));
Example #27
0
 /**
  * Sends Email for Email 2.0
  */
 function email2Send($request)
 {
     global $mod_strings;
     global $app_strings;
     global $current_user;
     global $sugar_config;
     global $locale;
     global $timedate;
     global $beanList;
     global $beanFiles;
     $OBCharset = $locale->getPrecedentPreference('default_email_charset');
     /**********************************************************************
      * Sugar Email PREP
      */
     /* preset GUID */
     $orignialId = "";
     if (!empty($this->id)) {
         $orignialId = $this->id;
     }
     // if
     if (empty($this->id)) {
         $this->id = create_guid();
         $this->new_with_id = true;
     }
     /* satisfy basic HTML email requirements */
     $this->name = $request['sendSubject'];
     $this->description_html = '&lt;html&gt;&lt;body&gt;' . $request['sendDescription'] . '&lt;/body&gt;&lt;/html&gt;';
     /**********************************************************************
      * PHPMAILER PREP
      */
     $mail = new SugarPHPMailer();
     $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
     if (empty($mail->Host) && !$this->isDraftEmail($request)) {
         $this->status = 'send_error';
         if ($mail->oe->type == 'system') {
             echo $app_strings['LBL_EMAIL_ERROR_PREPEND'] . $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND'];
         } else {
             echo $app_strings['LBL_EMAIL_ERROR_PREPEND'] . $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND'];
         }
         return false;
     }
     $subject = $this->name;
     $mail->Subject = from_html($this->name);
     // work-around legacy code in SugarPHPMailer
     if ($_REQUEST['setEditor'] == 1) {
         $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
         $this->description_html = $_REQUEST['description_html'];
     } else {
         $this->description_html = '';
         $this->description = $_REQUEST['sendDescription'];
     }
     // end work-around
     if ($this->isDraftEmail($request)) {
         if ($this->type != 'draft' && $this->status != 'draft') {
             $this->id = create_guid();
             $this->new_with_id = true;
             $this->date_entered = "";
         }
         // if
         $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
         $r1 = $this->db->query($q1);
     }
     // if
     if (isset($request['saveDraft'])) {
         $this->type = 'draft';
         $this->status = 'draft';
         $forceSave = true;
     } else {
         /* Apply Email Templates */
         // do not parse email templates if the email is being saved as draft....
         $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
         $sea = new SugarEmailAddress();
         $object_arr = array();
         if (isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) && ($_REQUEST['parent_type'] == 'Accounts' || $_REQUEST['parent_type'] == 'Contacts' || $_REQUEST['parent_type'] == 'Leads' || $_REQUEST['parent_type'] == 'Users' || $_REQUEST['parent_type'] == 'Prospects')) {
             if (isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
                 $className = $beanList[$_REQUEST['parent_type']];
                 if (isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
                     if (!class_exists($className)) {
                         require_once $beanFiles[$className];
                     }
                     $bean = new $className();
                     $bean->retrieve($_REQUEST['parent_id']);
                     $object_arr[$bean->module_dir] = $bean->id;
                 }
                 // if
             }
             // if
         }
         foreach ($toAddresses as $addrMeta) {
             $addr = $addrMeta['email'];
             $beans = $sea->getBeansByEmailAddress($addr);
             foreach ($beans as $bean) {
                 if (!isset($object_arr[$bean->module_dir])) {
                     $object_arr[$bean->module_dir] = $bean->id;
                 }
             }
         }
         /* template parsing */
         if (empty($object_arr)) {
             $object_arr = array('Contacts' => '123');
         }
         $object_arr['Users'] = $current_user->id;
         $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
         $this->name = EmailTemplate::parse_template($this->name, $object_arr);
         $this->description = EmailTemplate::parse_template($this->description, $object_arr);
         $this->description = html_entity_decode($this->description, ENT_COMPAT, 'UTF-8');
         if ($this->type != 'draft' && $this->status != 'draft') {
             $this->id = create_guid();
             $this->date_entered = "";
             $this->new_with_id = true;
             $this->type = 'out';
             $this->status = 'sent';
         }
     }
     if (isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id'])) {
         $this->parent_id = "";
         $this->parent_type = "";
     }
     // if
     $mail->Subject = $this->name;
     $mail = $this->handleBody($mail);
     $mail->Subject = $this->name;
     $this->description_html = from_html($this->description_html);
     $this->description_html = $this->decodeDuringSend($this->description_html);
     $this->description = $this->decodeDuringSend($this->description);
     /* from account */
     $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
     $replyToName = "";
     if (empty($request['fromAccount'])) {
         $defaults = $current_user->getPreferredEmail();
         $mail->From = $defaults['email'];
         $mail->FromName = $defaults['name'];
         $replyToName = $mail->FromName;
         //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
     } else {
         // passed -> user -> system default
         $ie = new InboundEmail();
         $ie->retrieve($request['fromAccount']);
         $storedOptions = unserialize(base64_decode($ie->stored_options));
         $fromName = "";
         $fromAddress = "";
         $replyToName = "";
         //$replyToAddress = "";
         if (!empty($storedOptions)) {
             $fromAddress = $storedOptions['from_addr'];
             $fromName = from_html($storedOptions['from_name']);
             $replyToAddress = isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "";
             $replyToName = isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "";
         }
         // if
         $defaults = $current_user->getPreferredEmail();
         // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
         // After adding remove below code
         // code to remove
         if ($ie->is_personal) {
             if (empty($replyToAddress)) {
                 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
             }
             // if
             if (empty($replyToName)) {
                 $replyToName = $defaults['name'];
             }
             // if
             //Personal accounts can have a reply_address, which should
             //overwrite the users set default.
             if (!empty($storedOptions['reply_to_addr'])) {
                 $replyToAddress = $storedOptions['reply_to_addr'];
             }
         }
         // end of code to remove
         $mail->From = !empty($fromAddress) ? $fromAddress : $defaults['email'];
         $mail->FromName = !empty($fromName) ? $fromName : $defaults['name'];
         $replyToName = !empty($replyToName) ? $replyToName : $mail->FromName;
     }
     $mail->Sender = $mail->From;
     /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
     if (!empty($replyToAddress)) {
         $mail->AddReplyTo($replyToAddress, $locale->translateCharsetMIME(trim($replyToName), 'UTF-8', $OBCharset));
     } else {
         $mail->AddReplyTo($mail->From, $locale->translateCharsetMIME(trim($mail->FromName), 'UTF-8', $OBCharset));
     }
     // else
     $emailAddressCollection = array();
     // used in linking to beans below
     // handle to/cc/bcc
     foreach ($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
         if (empty($addr_arr['email'])) {
             continue;
         }
         if (empty($addr_arr['display'])) {
             $mail->AddAddress($addr_arr['email'], "");
         } else {
             $mail->AddAddress($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
         }
         $emailAddressCollection[] = $addr_arr['email'];
     }
     foreach ($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
         if (empty($addr_arr['email'])) {
             continue;
         }
         if (empty($addr_arr['display'])) {
             $mail->AddCC($addr_arr['email'], "");
         } else {
             $mail->AddCC($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
         }
         $emailAddressCollection[] = $addr_arr['email'];
     }
     foreach ($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
         if (empty($addr_arr['email'])) {
             continue;
         }
         if (empty($addr_arr['display'])) {
             $mail->AddBCC($addr_arr['email'], "");
         } else {
             $mail->AddBCC($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
         }
         $emailAddressCollection[] = $addr_arr['email'];
     }
     /* parse remove attachments array */
     $removeAttachments = array();
     if (!empty($request['templateAttachmentsRemove'])) {
         $exRemove = explode("::", $request['templateAttachmentsRemove']);
         foreach ($exRemove as $file) {
             $removeAttachments = substr($file, 0, 36);
         }
     }
     /* handle attachments */
     if (!empty($request['attachments'])) {
         $exAttachments = explode("::", $request['attachments']);
         foreach ($exAttachments as $file) {
             $file = trim(from_html($file));
             $file = str_replace("\\", "", $file);
             if (!empty($file)) {
                 //$fileLocation = $this->et->userCacheDir."/{$file}";
                 $fileGUID = substr($file, 0, 36);
                 $fileLocation = $this->et->userCacheDir . "/{$fileGUID}";
                 $filename = substr($file, 36, strlen($file));
                 // strip GUID	for PHPMailer class to name outbound file
                 $mail->AddAttachment($fileLocation, $filename, 'base64', $this->email2GetMime($fileLocation));
                 //$mail->AddAttachment($fileLocation, $filename, 'base64');
                 // only save attachments if we're archiving or drafting
                 if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                     $note = new Note();
                     $note->id = create_guid();
                     $note->new_with_id = true;
                     // duplicating the note with files
                     $note->parent_id = $this->id;
                     $note->parent_type = $this->module_dir;
                     $note->name = $filename;
                     $note->filename = $filename;
                     $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
                     $note->file_mime_type = $this->email2GetMime($fileLocation);
                     if (!copy($fileLocation, $noteFile)) {
                         $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
                     }
                     $note->save();
                 }
             }
         }
     }
     /* handle sugar documents */
     if (!empty($request['documents'])) {
         $exDocs = explode("::", $request['documents']);
         foreach ($exDocs as $docId) {
             $docId = trim($docId);
             if (!empty($docId)) {
                 $doc = new Document();
                 $docRev = new DocumentRevision();
                 $doc->retrieve($docId);
                 $docRev->retrieve($doc->document_revision_id);
                 $filename = $docRev->filename;
                 $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
                 $mime_type = $docRev->file_mime_type;
                 $mail->AddAttachment($fileLocation, $locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
                 // only save attachments if we're archiving or drafting
                 if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                     $note = new Note();
                     $note->id = create_guid();
                     $note->new_with_id = true;
                     // duplicating the note with files
                     $note->parent_id = $this->id;
                     $note->parent_type = $this->module_dir;
                     $note->name = $filename;
                     $note->filename = $filename;
                     $note->file_mime_type = $mime_type;
                     $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
                     if (!copy($fileLocation, $noteFile)) {
                         $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
                     }
                     $note->save();
                 }
             }
         }
     }
     /* handle template attachments */
     if (!empty($request['templateAttachments'])) {
         $exNotes = explode("::", $request['templateAttachments']);
         foreach ($exNotes as $noteId) {
             $noteId = trim($noteId);
             if (!empty($noteId)) {
                 $note = new Note();
                 $note->retrieve($noteId);
                 if (!empty($note->id)) {
                     $filename = $note->filename;
                     $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
                     $mime_type = $note->file_mime_type;
                     if (!$note->embed_flag) {
                         $mail->AddAttachment($fileLocation, $filename, 'base64', $mime_type);
                         // only save attachments if we're archiving or drafting
                         if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                             if ($note->parent_id != $this->id) {
                                 $this->saveTempNoteAttachments($filename, $fileLocation, $mime_type);
                             }
                         }
                         // if
                     }
                     // if
                 } else {
                     //$fileLocation = $this->et->userCacheDir."/{$file}";
                     $fileGUID = substr($noteId, 0, 36);
                     $fileLocation = $this->et->userCacheDir . "/{$fileGUID}";
                     //$fileLocation = $this->et->userCacheDir."/{$noteId}";
                     $filename = substr($noteId, 36, strlen($noteId));
                     // strip GUID	for PHPMailer class to name outbound file
                     $mail->AddAttachment($fileLocation, $locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
                     //If we are saving an email we were going to forward we need to save the attachments as well.
                     if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                         $mimeType = $this->email2GetMime($fileLocation);
                         $this->saveTempNoteAttachments($filename, $fileLocation, $mimeType);
                     }
                     // if
                 }
             }
         }
     }
     /**********************************************************************
      * Final Touches
      */
     /* save email to sugar? */
     $forceSave = false;
     if ($this->type == 'draft' && !isset($request['saveDraft'])) {
         // sending a draft email
         $this->type = 'out';
         $this->status = 'sent';
         $forceSave = true;
     } elseif (isset($request['saveDraft'])) {
         $this->type = 'draft';
         $this->status = 'draft';
         $forceSave = true;
     }
     /**********************************************************************
      * SEND EMAIL (finally!)
      */
     $mailSent = false;
     if ($this->type != 'draft') {
         $mail->prepForOutbound();
         $mail->Body = $this->decodeDuringSend($mail->Body);
         $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
         if (!$mail->Send()) {
             $this->status = 'send_error';
             ob_clean();
             echo $app_strings['LBL_EMAIL_ERROR_PREPEND'] . $mail->ErrorInfo;
             return false;
         }
     }
     if (!(empty($orignialId) || isset($request['saveDraft']) || $this->type == 'draft' && $this->status == 'draft') && ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyAll' || $_REQUEST['composeType'] == 'replyCase') && $orignialId != $this->id) {
         $originalEmail = new Email();
         $originalEmail->retrieve($orignialId);
         $originalEmail->reply_to_status = 1;
         $originalEmail->save();
         $this->reply_to_status = 0;
     }
     // if
     if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
         if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
             $emailFromIe = new InboundEmail();
             $emailFromIe->retrieve($_REQUEST['ieId']);
             $emailFromIe->mailbox = $_REQUEST['mbox'];
             if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
                 if ($emailFromIe->isPop3Protocol()) {
                     $emailFromIe->mark_answered($this->uid, 'pop3');
                 } elseif ($emailFromIe->connectMailserver() == 'true') {
                     $emailFromIe->markEmails($this->uid, 'answered');
                     $emailFromIe->mark_answered($this->uid);
                 }
             }
         }
     }
     if ($forceSave || $this->type == 'draft' || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
         // saving a draft OR saving a sent email
         $decodedFromName = mb_decode_mimeheader($mail->FromName);
         $this->from_addr = "{$decodedFromName} <{$mail->From}>";
         $this->from_addr_name = $this->from_addr;
         $this->to_addrs = $_REQUEST['sendTo'];
         $this->to_addrs_names = $_REQUEST['sendTo'];
         $this->cc_addrs = $_REQUEST['sendCc'];
         $this->cc_addrs_names = $_REQUEST['sendCc'];
         $this->bcc_addrs = $_REQUEST['sendBcc'];
         $this->bcc_addrs_names = $_REQUEST['sendBcc'];
         $this->assigned_user_id = $current_user->id;
         $this->date_sent = $timedate->now();
         ///////////////////////////////////////////////////////////////////
         ////	LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
         if (isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id'])) {
             $this->parent_id = $_REQUEST['parent_id'];
             $this->parent_type = $_REQUEST['parent_type'];
             $q = "SELECT count(*) c FROM emails_beans WHERE  email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
             $r = $this->db->query($q);
             $a = $this->db->fetchByAssoc($r);
             if ($a['c'] <= 0) {
                 if (isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
                     $className = $beanList[$_REQUEST['parent_type']];
                     if (isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
                         if (!class_exists($className)) {
                             require_once $beanFiles[$className];
                         }
                         $bean = new $className();
                         $bean->retrieve($_REQUEST['parent_id']);
                         if ($bean->load_relationship('emails')) {
                             $bean->emails->add($this->id);
                         }
                         // if
                     }
                     // if
                 }
                 // if
             }
             // if
         } else {
             if (!class_exists('aCase')) {
             } else {
                 $c = new aCase();
                 if ($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
                     $c->retrieve($caseId);
                     $c->load_relationship('emails');
                     $c->emails->add($this->id);
                     $this->parent_type = "Cases";
                     $this->parent_id = $caseId;
                 }
                 // if
             }
         }
         // else
         ////	LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
         ///////////////////////////////////////////////////////////////////
         $this->save();
     }
     if (!empty($request['fromAccount'])) {
         if (isset($ie->id) && !$ie->isPop3Protocol()) {
             $sentFolder = $ie->get_stored_options("sentFolder");
             if (!empty($sentFolder)) {
                 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
                 $ie->mailbox = $sentFolder;
                 if ($ie->connectMailserver() == 'true') {
                     $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
                     $returnData = imap_append($ie->conn, $connectString, $data, "\\Seen");
                     if (!$returnData) {
                         $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
                     }
                     // if
                 } else {
                     $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
                 }
                 // else
             } else {
                 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
             }
             // else
         }
         // if
     }
     // if
     return true;
 }
Example #28
0
     }
     $mailsum = count($filtered) - 1;
 }
 if (!isset($_REQUEST['start'])) {
     $_REQUEST['start'] = $mailsum;
 }
 $upperlimit = $_REQUEST['start'];
 $smarty->assign('start', $_REQUEST['start']);
 $webmail_list_page = array();
 for ($i = $upperlimit, $icount_wlp = count($webmail_list_page); $i > 0 && $icount_wlp < $numshow; $i--) {
     if (!empty($_REQUEST['filter'])) {
         $aux = $filtered[$i];
     } else {
         $aux = $webmail_list[$i - 1];
         // Lets decode the Subject before going to list it... otherwise it returns garbage for non-ascii subjects
         $aux['subject'] = mb_decode_mimeheader($aux['subject']);
         $webmaillib->replace_webmail_message($current['accountId'], $user, $aux['realmsgid']);
         list($aux['isRead'], $aux['isFlagged'], $aux['isReplied']) = $webmaillib->get_mail_flags($current['accountId'], $user, $aux['realmsgid']);
     }
     $webmail_list_page[] = $aux;
 }
 $lowerlimit = $i;
 if ($lowerlimit < 0) {
     $lowerlimit = 0;
 }
 $showstart = $mailsum - $upperlimit + 1;
 $showend = $mailsum - $lowerlimit;
 $smarty->assign('showstart', $showstart);
 $smarty->assign('showend', $showend);
 $smarty->assign('total', $mailsum);
 if ($lowerlimit > 0) {
Example #29
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;
}
Example #30
0
 /**
  * Returns the  headers of the specified message in an
  * associative array. Array keys are the header names, array
  * values are the header values. In the case of multiple headers
  * having the same names, eg Received:, the array value will be
  * an indexed array of all the header values.
  *
  * @param  integer $msg_id Message number
  * @return mixed   Either array of headers or false on error
  */
 function getParsedHeaders($msg_id)
 {
     if ($this->_state == NET_POP3_STATE_TRANSACTION) {
         $raw_headers = rtrim($this->getRawHeaders($msg_id));
         $raw_headers = preg_replace("/\r\n[ \t]+/", ' ', $raw_headers);
         // Unfold headers
         $raw_headers = explode("\r\n", $raw_headers);
         foreach ($raw_headers as $value) {
             $name = substr($value, 0, $pos = strpos($value, ':'));
             $value = ltrim(substr($value, $pos + 1));
             // 21/09/08 MatWho Prevent capitalisation problems with Message-ID mail header
             if (preg_match('/message-id/i', $name)) {
                 $name = "Message-ID";
             }
             // Fix Subject encoding
             if ($name == 'Subject') {
                 $subject = str_replace("_", " ", mb_decode_mimeheader($value));
                 $value = $subject;
             }
             if (isset($headers[$name]) and is_array($headers[$name])) {
                 $headers[$name][] = $value;
             } elseif (isset($headers[$name])) {
                 $headers[$name] = array($headers[$name], $value);
             } else {
                 $headers[$name] = $value;
             }
         }
         return $headers;
     }
     return false;
 }