public function check_bounces($db) { $email_address = $this->settings['bounce_email']; // not used $email_username = $this->settings['bounce_username']; $email_password = $this->settings['bounce_password']; $email_host = $this->settings['bounce_host']; $email_port = $this->settings['bounce_port'] ? $this->settings['bounce_port'] : 110; // pop3 $mbox = imap_open('{' . $email_host . ':' . $email_port . '/pop3/novalidate-cert}INBOX', $email_username, $email_password) or die(imap_last_error()); if (!$mbox) { // send email letting them know bounce checking failed? // meh. later. echo 'Failed to connect'; } else { $MC = imap_check($mbox); $result = imap_fetch_overview($mbox, "1:{$MC->Nmsgs}", 0); foreach ($result as $overview) { $this_subject = (string) $overview->subject; //echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from} <br> {$this_subject} <br>\n"; $tmp_file = tempnam('/tmp/', 'newsletter_bounce'); // TODO - tmp files for windows hosting. imap_savebody($mbox, $tmp_file, $overview->msgno); $body = file_get_contents($tmp_file); if (preg_match('/Message-ID:\\s*<?Newsletter-(\\d+)-(\\d+)-([A-Fa-f0-9]{32})/imsU', $body, $matches)) { // we have a newsletter message id, check the hash and mark a bounce. //"message_id" => "Newsletter-$send_id-$member_id-".md5("bounce check for $member_id in send $send_id"), $send_id = (int) $matches[1]; $member_id = (int) $matches[2]; $provided_hash = trim($matches[3]); $real_hash = md5("bounce check for {$member_id} in send {$send_id}"); if ($provided_hash == $real_hash) { $sql = "UPDATE " . _DB_PREFIX . "newsletter_member SET `status` = 4, bounce_time = '" . time() . "' WHERE `member_id` = '" . $member_id . "' AND send_id = '" . $send_id . "' AND `status` = 3 LIMIT 1"; $res = query($sql, $db); imap_delete($mbox, $overview->msgno); } else { // bad hash, report. } } unlink($tmp_file); } imap_expunge($mbox); imap_close($mbox); } }
/** * @param $callback function that is called with parsed mail header + attachments */ function getMail($callback = '', $timeout = 30) { if (!$this->connect()) { echo "ERROR: IMAP connection to " . $this->server . ":" . $this->port . " failed\n"; return false; } $folders = imap_listmailbox($this->handle, '{' . $this->server . ':' . $this->port . '}', '*'); $msginfo = imap_mailboxmsginfo($this->handle); //dp('found '.$msginfo->Nmsgs.' messages in mailbox'); $this->tot_mails = $msginfo->Nmsgs; for ($i = 1; $i <= $this->tot_mails; $i++) { //dp("Downloading ".$i." of ".$this->tot_mails." ..."); //XXX hack because retarded imap_fetchbody() dont allow to fetch the whole message $fp = fopen('php://temp', 'w'); imap_savebody($this->handle, $fp, $i); rewind($fp); $msg = stream_get_contents($fp); fclose($fp); $mime = new MimeReader(); $mime->parseMail($msg); $this->emails[] = $mime->getAsEMail($i); } if (!function_exists($callback)) { throw new \Exception('ERROR callback function ' . $callback . ' not found'); } call_user_func($callback, $this->emails, $this); }
/** * Save Message with MessageNumber to Disk * * @param $save_path * @return bool */ public function saveMessageToDisk($savePath) { $res = imap_savebody($this->stream, $savePath, imap_msgno($this->stream, $this->messageNumber)); return $res; }
/** Get a Message */ function mailGet($i) { // return imap_body($this->_c,$i,FT_PEEK); return imap_savebody($this->_c, 'mail', $i, null, FT_PEEK); }
/** * Read messages from server and save returned emails into DB * * @param resource $mbox created by dre_connect() (by reference) * @param integer the number of messages to process * @return boolean true on success */ function dre_process_messages(&$mbox, $limit) { //return; // Exit, in development... global $Settings; global $dre_messages, $dre_emails, $email_cntr, $del_cntr, $is_cron_mode; // No execution time limit set_max_execution_time(0); $email_cntr = 0; $del_cntr = 0; for ($index = 1; $index <= $limit; $index++) { dre_msg('<hr /><h3>Processing message #' . $index . ':</h3>'); $strbody = ''; $hasAttachment = false; $hasRelated = false; // Save email to hard drive, otherwise attachments may take a lot of RAM if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) { dre_msg(T_('Could not create temporary file.'), true); continue; } imap_savebody($mbox, $tmpMIME, $index); // Create random temp directory for message parts $tmpDirMIME = dre_tempdir(sys_get_temp_dir(), 'b2evo_'); $mimeParser = new mime_parser_class(); $mimeParser->mbox = 0; // Set to 0 for parsing a single message file $mimeParser->decode_headers = 1; $mimeParser->ignore_syntax_errors = 1; $mimeParser->extract_addresses = 0; $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1); if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) { dre_msg(sprintf('MIME message decoding error: %s at position %d.', $mimeParser->error, $mimeParser->error_position), true); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } else { dre_msg('MIME message decoding successful'); if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) { dre_msg(sprintf('MIME message analyse error: %s', $mimeParser->error), true); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // Get message $subject and $post_date from headers (by reference) if (!dre_process_header($parsedMIME, $subject, $post_date)) { // Couldn't process message headers rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // TODO: handle type == "message" recursively // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing if ($parsedMIME['Type'] == 'html') { // Mail is HTML dre_msg('HTML message part saved as ' . $parsedMIME['DataFile']); $html_body = file_get_contents($parsedMIME['DataFile']); foreach ($parsedMIME['Alternative'] as $alternative) { // First try to get HTML alternative (when possible) if ($alternative['Type'] == 'html') { // HTML text dre_msg('HTML alternative message part saved as ' . $alternative['DataFile']); // sam2kb> TODO: we may need to use $html_body here instead $strbody = file_get_contents($alternative['DataFile']); break; // stop after first alternative } elseif ($alternative['Type'] == 'text') { // Plain text dre_msg('Text alternative message part saved as ' . $alternative['DataFile']); $strbody = imap_qprint(file_get_contents($alternative['DataFile'])); break; // stop after first alternative } } } elseif ($parsedMIME['Type'] == 'text') { // Mail is plain text dre_msg('Plain-text message part saved as ' . $parsedMIME['DataFile']); $strbody = imap_qprint(file_get_contents($parsedMIME['DataFile'])); } elseif ($parsedMIME['Type'] == 'delivery-status') { // Mail is delivery-status $strbody = ''; foreach ($decodedMIME[0]['Parts'] as $part) { $strbody .= imap_qprint(file_get_contents($part['BodyFile'])); } } if (count($mimeParser->warnings) > 0) { dre_msg(sprintf('<h4>%d warnings during decode:</h4>', count($mimeParser->warnings))); foreach ($mimeParser->warnings as $k => $v) { dre_msg('Warning: ' . $v . ' at position ' . $k); } } } unlink($tmpMIME); if (empty($html_body)) { // Plain text message dre_msg('Message type: TEXT'); dre_msg('Message body: <pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>'); // Process body. First fix different line-endings (dos, mac, unix), remove double newlines $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody)); } else { // HTML message dre_msg('Message type: HTML'); if (($parsed_message = dre_prepare_html_message($html_body)) === false) { // No 'auth' tag provided, skip to the next message rmdir_r($tmpDirMIME); continue; } list($auth, $content) = $parsed_message; } dre_msg('<b class="green">Success</b>'); $message_text = $content; // Remove content after terminators $content = dre_limit_by_terminators($content); global $Messages; if ($Messages->has_errors()) { // Make it easier for user to find and correct the errors dre_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), true); dre_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), true); $Messages->clear(); rmdir_r($tmpDirMIME); continue; } global $dre_emails, $DB, $localtimenow; dre_msg(sprintf('<h4>Saving the returned email in the database</h4>')); // Insert a returned email's data into DB if ($returned_email = dre_insert_returned_email($content, $message_text, dre_get_headers($decodedMIME))) { dre_msg('Error Type: ' . dre_decode_error_type($returned_email['errtype'])); dre_msg('Error Message: ' . $returned_email['errormsg']); ++$email_cntr; } // Delete temporary directory rmdir_r($tmpDirMIME); if ($Settings->get('repath_delete_emails')) { dre_msg('Marking message for deletion from inbox: ' . $index); imap_delete($mbox, $index); ++$del_cntr; } } // Expunge messages market for deletion imap_expunge($mbox); return true; }
/** * Read messages from server and create posts * * @param resource $mbox created by pbm_connect() (by reference) * @param integer the number of messages to process * @return boolean true on success */ function pbm_process_messages(&$mbox, $limit) { global $Settings; global $pbm_item_files, $pbm_messages, $pbm_items, $post_cntr, $del_cntr, $is_cron_mode; // No execution time limit set_max_execution_time(0); // Are we in test mode? $test_mode_on = $Settings->get('eblog_test_mode'); $post_cntr = 0; $del_cntr = 0; for ($index = 1; $index <= $limit; $index++) { pbm_msg('<hr /><h3>Processing message #' . $index . ':</h3>'); $strbody = ''; $hasAttachment = false; $hasRelated = false; $pbm_item_files = array(); // reset the value for each new Item // Save email to hard drive, otherwise attachments may take a lot of RAM if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) { pbm_msg(T_('Could not create temporary file.'), true); continue; } imap_savebody($mbox, $tmpMIME, $index); // Create random temp directory for message parts $tmpDirMIME = pbm_tempdir(sys_get_temp_dir(), 'b2evo_'); $mimeParser = new mime_parser_class(); $mimeParser->mbox = 0; // Set to 0 for parsing a single message file $mimeParser->decode_headers = 1; $mimeParser->ignore_syntax_errors = 1; $mimeParser->extract_addresses = 0; $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1); if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) { pbm_msg(sprintf('MIME message decoding error: %s at position %d.', $mimeParser->error, $mimeParser->error_position), true); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } else { pbm_msg('MIME message decoding successful'); if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) { pbm_msg(sprintf('MIME message analyse error: %s', $mimeParser->error), true); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // Get message $subject and $post_date from headers (by reference) if (!pbm_process_header($parsedMIME, $subject, $post_date)) { // Couldn't process message headers rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // TODO: handle type == "message" recursively // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing if ($parsedMIME['Type'] == 'html') { // Mail is HTML if ($Settings->get('eblog_html_enabled')) { // HTML posting enabled pbm_msg('HTML message part saved as ' . $parsedMIME['DataFile']); $html_body = file_get_contents($parsedMIME['DataFile']); } foreach ($parsedMIME['Alternative'] as $alternative) { // First try to get HTML alternative (when possible) if ($alternative['Type'] == 'html' && $Settings->get('eblog_html_enabled')) { // HTML text pbm_msg('HTML alternative message part saved as ' . $alternative['DataFile']); // sam2kb> TODO: we may need to use $html_body here instead $strbody = file_get_contents($alternative['DataFile']); break; // stop after first alternative } elseif ($alternative['Type'] == 'text') { // Plain text pbm_msg('Text alternative message part saved as ' . $alternative['DataFile']); $strbody = imap_qprint(file_get_contents($alternative['DataFile'])); break; // stop after first alternative } } } elseif ($parsedMIME['Type'] == 'text') { // Mail is plain text pbm_msg('Plain-text message part saved as ' . $parsedMIME['DataFile']); $strbody = imap_qprint(file_get_contents($parsedMIME['DataFile'])); } // Check for attachments if (!empty($parsedMIME['Attachments'])) { $hasAttachment = true; foreach ($parsedMIME['Attachments'] as $file) { pbm_msg('Attachment: ' . $file['FileName'] . ' stored as ' . $file['DataFile']); } } // Check for inline images if (!empty($parsedMIME['Related'])) { $hasRelated = true; foreach ($parsedMIME['Related'] as $file) { pbm_msg('Related file with content ID: ' . $file['ContentID'] . ' stored as ' . $file['DataFile']); } } if (count($mimeParser->warnings) > 0) { pbm_msg(sprintf('<h4>%d warnings during decode:</h4>', count($mimeParser->warnings))); foreach ($mimeParser->warnings as $k => $v) { pbm_msg('Warning: ' . $v . ' at position ' . $k); } } } unlink($tmpMIME); if (empty($html_body)) { // Plain text message pbm_msg('Message type: TEXT'); pbm_msg('Message body: <pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>'); // Process body. First fix different line-endings (dos, mac, unix), remove double newlines $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody)); // First see if there's an <auth> tag with login and password if (($auth = pbm_get_auth_tag($content)) === false) { // No <auth> tag, let's detect legacy "username:password" on the first line $a_body = explode("\n", $content, 2); // tblue> splitting only into 2 parts allows colons in the user PW // Note: login and password cannot include '<' ! $auth = explode(':', strip_tags($a_body[0]), 2); // Drop the first line with username and password $content = $a_body[1]; } } else { // HTML message pbm_msg('Message type: HTML'); if (($parsed_message = pbm_prepare_html_message($html_body)) === false) { // No 'auth' tag provided, skip to the next message rmdir_r($tmpDirMIME); continue; } list($auth, $content) = $parsed_message; } // TODO: dh> should the password really get trimmed here?! $user_pass = isset($auth[1]) ? trim(remove_magic_quotes($auth[1])) : NULL; $user_login = trim(evo_strtolower(remove_magic_quotes($auth[0]))); if (empty($user_login) || empty($user_pass)) { pbm_msg(sprintf(T_('Please add username and password in message body in format %s.'), '"<auth>username:password</auth>"'), true); rmdir_r($tmpDirMIME); continue; } // Authenticate user pbm_msg('Authenticating user: «' . $user_login . '»'); $pbmUser =& pbm_validate_user_password($user_login, $user_pass); if (!$pbmUser) { pbm_msg(sprintf(T_('Authentication failed for user «%s»'), htmlspecialchars($user_login)), true); rmdir_r($tmpDirMIME); continue; } $pbmUser->get_Group(); // Load group if (!empty($is_cron_mode)) { // Assign current User if we are in cron mode. This is needed in order to check user permissions global $current_User; $current_User = duplicate($pbmUser); } // Activate User's locale locale_activate($pbmUser->get('locale')); pbm_msg('<b class="green">Success</b>'); if ($post_categories = xmlrpc_getpostcategories($content)) { $main_cat_ID = array_shift($post_categories); $extra_cat_IDs = $post_categories; pbm_msg('Extra categories: ' . implode(', ', $extra_cat_IDs)); } else { $main_cat_ID = $Settings->get('eblog_default_category'); $extra_cat_IDs = array(); } pbm_msg('Main category ID: ' . $main_cat_ID); $ChapterCache =& get_ChapterCache(); $pbmChapter =& $ChapterCache->get_by_ID($main_cat_ID, false, false); if (empty($pbmChapter)) { pbm_msg(sprintf(T_('Requested category %s does not exist!'), $main_cat_ID), true); rmdir_r($tmpDirMIME); continue; } $blog_ID = $pbmChapter->blog_ID; pbm_msg('Blog ID: ' . $blog_ID); $BlogCache =& get_BlogCache(); $pbmBlog =& $BlogCache->get_by_ID($blog_ID, false, false); if (empty($pbmBlog)) { pbm_msg(sprintf(T_('Requested blog %s does not exist!'), $blog_ID), true); rmdir_r($tmpDirMIME); continue; } // Check permission: pbm_msg(sprintf('Checking permissions for user «%s» to post to Blog #%d', $user_login, $blog_ID)); if (!$pbmUser->check_perm('blog_post!published', 'edit', false, $blog_ID)) { pbm_msg(T_('Permission denied.'), true); rmdir_r($tmpDirMIME); continue; } if (($hasAttachment || $hasRelated) && !$pbmUser->check_perm('files', 'add', false, $blog_ID)) { pbm_msg(T_('You have no permission to add/upload files.'), true); rmdir_r($tmpDirMIME); continue; } pbm_msg('<b class="green">Success</b>'); // Remove content after terminator $eblog_terminator = $Settings->get('eblog_body_terminator'); if (!empty($eblog_terminator) && ($os_terminator = evo_strpos($content, $eblog_terminator)) !== false) { $content = evo_substr($content, 0, $os_terminator); } $post_title = pbm_get_post_title($content, $subject); // Remove 'title' and 'category' tags $content = xmlrpc_removepostdata($content); // Remove <br> tags from string start and end // We do it here because there might be extra <br> left after deletion of <auth>, <category> and <title> tags $content = preg_replace(array('~^(\\s*<br[\\s/]*>\\s*){1,}~i', '~(\\s*<br[\\s/]*>\\s*){1,}$~i'), '', $content); if ($hasAttachment || $hasRelated) { // Handle attachments if (isset($GLOBALS['files_Module'])) { if ($mediadir = $pbmBlog->get_media_dir()) { if ($hasAttachment) { pbm_process_attachments($content, $parsedMIME['Attachments'], $mediadir, $pbmBlog->get_media_url(), $Settings->get('eblog_add_imgtag'), 'attach'); } if ($hasRelated) { pbm_process_attachments($content, $parsedMIME['Related'], $mediadir, $pbmBlog->get_media_url(), true, 'related'); } } else { pbm_msg(T_('Unable to access media directory. No attachments processed.'), true); } } else { pbm_msg(T_('Files module is disabled or missing!'), true); } } // CHECK and FORMAT content global $Plugins; $renderer_params = array('Blog' => &$pbmBlog, 'setting_name' => 'coll_apply_rendering'); $renderers = $Plugins->validate_renderer_list($Settings->get('eblog_renderers'), $renderer_params); pbm_msg('Applying the following text renderers: ' . implode(', ', $renderers)); // Do some optional filtering on the content // Typically stuff that will help the content to validate // Useful for code display // Will probably be used for validation also $Plugins_admin =& get_Plugins_admin(); $params = array('object_type' => 'Item', 'object_Blog' => &$pbmBlog); $Plugins_admin->filter_contents($post_title, $content, $renderers, $params); pbm_msg('Filtered post content: <pre style="font-size:10px">' . htmlspecialchars($content) . '</pre>'); $context = $Settings->get('eblog_html_tag_limit') ? 'commenting' : 'posting'; $post_title = check_html_sanity($post_title, $context, $pbmUser); $content = check_html_sanity($content, $context, $pbmUser); global $Messages; if ($Messages->has_errors()) { // Make it easier for user to find and correct the errors pbm_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), true); pbm_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), true); $Messages->clear(); rmdir_r($tmpDirMIME); continue; } if ($test_mode_on) { // Test mode pbm_msg('<b class="green">It looks like the post can be successfully saved in the database. However we will not do it in test mode.</b>'); } else { load_class('items/model/_item.class.php', 'Item'); global $pbm_items, $DB, $localtimenow; $post_status = 'published'; pbm_msg(sprintf('<h4>Saving item "%s" in the database</h4>', $post_title)); // INSERT NEW POST INTO DB: $edited_Item = new Item(); $edited_Item->set_creator_User($pbmUser); $edited_Item->set($edited_Item->lasteditor_field, $pbmUser->ID); $edited_Item->set('title', $post_title); $edited_Item->set('content', $content); $edited_Item->set('datestart', $post_date); $edited_Item->set('datemodified', date('Y-m-d H:i:s', $localtimenow)); $edited_Item->set('main_cat_ID', $main_cat_ID); $edited_Item->set('extra_cat_IDs', $extra_cat_IDs); $edited_Item->set('status', $post_status); $edited_Item->set('locale', $pbmUser->locale); $edited_Item->set('renderers', $renderers); // INSERT INTO DB: $edited_Item->dbinsert('through_email'); pbm_msg(sprintf('Item created?: ' . (isset($edited_Item->ID) ? 'yes' : 'no'))); // Execute or schedule notifications & pings: $edited_Item->handle_post_processing(true); if (!empty($pbm_item_files)) { // Attach files $FileCache =& get_FileCache(); $order = 1; foreach ($pbm_item_files as $filename) { pbm_msg(sprintf('Saving file "%s" in the database', $filename)); $pbmFile =& $FileCache->get_by_root_and_path('collection', $pbmBlog->ID, $filename); $pbmFile->meta = 'notfound'; // Save time and don't try to load meta from DB, it's not there anyway $pbmFile->dbsave(); pbm_msg(sprintf('File saved?: ' . (isset($pbmFile->ID) ? 'yes' : 'no'))); pbm_msg(sprintf('Attaching file "%s" to the post', $filename)); // Let's make the link! $pbmLink = new Link(); $pbmLink->set('itm_ID', $edited_Item->ID); $pbmLink->set('file_ID', $pbmFile->ID); $pbmLink->set('position', 'aftermore'); $pbmLink->set('order', $order++); $pbmLink->dbinsert(); pbm_msg(sprintf('File attached?: ' . (isset($pbmLink->ID) ? 'yes' : 'no'))); } } // Save posted items sorted by author user for reports $pbm_items['user_' . $pbmUser->ID][] = $edited_Item; ++$post_cntr; } pbm_msg('Message posting successful'); // Delete temporary directory rmdir_r($tmpDirMIME); if (!$test_mode_on && $Settings->get('eblog_delete_emails')) { pbm_msg('Marking message for deletion from inbox: ' . $index); imap_delete($mbox, $index); ++$del_cntr; } } // Expunge messages marked for deletion imap_expunge($mbox); return true; }
/** * define proxy function for imap_savebody * * @param resource $imap_stream * @param mixed $file * @param int $msg_number * @param string $part_number * @param int $options * @return boolean */ function imap_savebody_alt($imap_stream, $file, $msg_number, $part_number = null, $options = null) { return imap_savebody($imap_stream, $file, $msg_number, $part_number, $options); }
function mailGetPart($i, $part = '1', $file = null) { $this->_open(); return imap_savebody($this->_c, $file, $mnum, $part, FT_INTERNAL | FT_PEEK); }
$attachments[$partid][pos] = $partid + 1; $attachments[$partid][id] = $postid; } } } } if ($attachments) { foreach ($attachments as $attachment) { $filename = '/tmp/' . $attachment[filename]; $filelist[] = str_replace('7z', 'xml', $filename); $file = fopen($filename, 'w'); stream_filter_append($file, 'convert.base64-decode', STREAM_FILTER_WRITE); if (chkconfig($cashimport['use_seen_flag'])) { imap_savebody($ih, $file, $attachment[id], $attachment[pos]); } else { imap_savebody($ih, $file, $attachment[id], $attachment[pos], FT_PEEK); } exec('7za e ' . $filename . ' -p' . $cashimport['7zpasswd'] . ' -o/tmp -y', $debug); fclose($file); } } } } imap_close($ih); } if (!empty($filelist)) { $count = sizeof($filelist); $cash = array(); $time = time(); if (isset($cashimport['copy_dir']) && !empty($cashimport['copy_dir'])) { for ($i = 0; $i < $count; $i++) {
/** * This function saves the attachment to the exact specified location. * * @param string $path * @return bool */ public function saveAs($path) { $dirname = dirname($path); if (file_exists($path)) { if (!is_writable($path)) { return false; } } elseif (!is_dir($dirname) || !is_writable($dirname)) { return false; } if (($filePointer = fopen($path, 'w')) == false) { return false; } switch ($this->encoding) { case 3: //base64 $streamFilter = stream_filter_append($filePointer, 'convert.base64-decode', STREAM_FILTER_WRITE); break; case 4: //quoted-printable $streamFilter = stream_filter_append($filePointer, 'convert.quoted-printable-decode', STREAM_FILTER_WRITE); break; default: $streamFilter = null; } $result = imap_savebody($this->imapStream, $filePointer, $this->messageId, $this->partId ?: 1, FT_UID); if ($streamFilter) { stream_filter_remove($streamFilter); } fclose($filePointer); return $result; }
/** * Scan mailbox to import news. */ private function scanMailbox() { // check available emails $count = imap_num_msg($this->mailbox); $this->report .= sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['inf_msgs'] . '<br />', $count); for ($msg = 1; $msg <= $count; $msg++) { // init $this->header = null; $this->forwarded = null; $this->text = null; $this->html = null; $this->attach = array(); $this->images = array(); // read header $this->readHeader($msg); $this->report .= sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['inf_nummsg'] . '<br />', $msg, $this->header->subject); if ($this->header->Deleted == 'D') { // skip deleted emails $this->report .= ' ' . $GLOBALS['TL_LANG']['tl_zad_sendnews']['inf_del'] . '<br />'; continue; } // read content $this->readContent($msg); // import news $this->importNews(); // do post action if ($this->manager->post_action == 'move') { // move email $res = imap_mail_move($this->mailbox, $msg, $this->manager->move_mailbox); if (!$res) { // error, do nothing $this->log('Can\'t move email ' . $msg . ' to ' . $this->manager->move_mailbox . ' for the sendnews manager \'' . $this->manager->name . '\'', 'ZadSendnewsManager scanMailbox()', TL_ERROR); $this->report .= sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['wrn_move'] . '<br />', $msg, $this->manager->move_mailbox); $this->signalWarning(); } } elseif ($this->manager->post_action == 'log') { // log and delete email $fl = fopen(TL_ROOT . '/system/logs/zad_sendnews_' . $this->manager->id . '.log', 'ab'); if (!$fl) { // error, do nothing $this->log('Can\'t write log file for the sendnews manager \'' . $this->manager->name . '\'', 'ZadSendnewsManager scanMailbox()', TL_ERROR); $this->report .= sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['wrn_open'] . '<br />', $msg); $this->signalWarning(); } else { fwrite($fl, "\n\n###---[[[EMAIL START]]]---###\n"); $res = imap_savebody($this->mailbox, $fl, $msg); if (!$res) { // error, do nothing $this->log('Can\'t log email ' . $msg . ' for the sendnews manager \'' . $this->manager->name . '\'', 'ZadSendnewsManager scanMailbox()', TL_ERROR); $this->report .= sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['wrn_write'] . '<br />', $msg); $this->signalWarning(); } fclose($fl); } imap_delete($this->mailbox, $msg); } else { // delete email imap_delete($this->mailbox, $msg); } } }
function CheckMessage($uid, $subject) { $file = "/tmp/imap-{$uid}.msg"; if (!imap_savebody($GLOBALS["MBXCON"], $file, $uid)) { events("Failed save message {$uid}", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); return false; } $datas = @file_get_contents($file); if (preg_match("#The following addresses failed:\\s+<(.+?)>#is", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#Return Receipt#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); } if (preg_match("#Final-Recipient: rfc822;.+?\\s+Action: delayed#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); } if (preg_match("#delivery temporarily suspended#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); } if (preg_match("#said: 550 5\\.1\\.1 <(.+?)>: Recipient address rejected#is", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#R=E9ponse automatique d'absence du bureau#i", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Je suis absent entre#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Je suis en cong.+?du#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#550\\s+<(.+?)>: User unknown#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#550\\s+<(.+?)>: Recipient address\\s+rejected#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#550 5\\.1\\.1 <(.+?)>: Recipient\\s+address rejected:#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: Host or domain name not found#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<mailto:(.+?)>\\s+The recipient's e-mail address was not found#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 550.+?5\\.1\\.0\\s+Address rejected#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: Recipient address rejected#", $datas, $re)) { if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#YOU DO NOT NEED TO RESEND YOUR MESSAGE#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$overview->uid}:{$overview->uid}"); return; } if (preg_match("#Delivery to the following recipients failed\\.\\s+(.+?)@(.+?)\\s+#", $datas, $re)) { $re[1] = trim("{$re[1]}@{$re[2]}"); if (preg_match("#(.+?)@(.+?)>#", $re[1], $ri)) { $re[1] = "{$ri[1]}@{$ri[2]}"; } @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#[0-9]+ [0-9\\.]+ SPAM is not accepted here#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: Relay access denied#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>\\.\\.\\. User unknown#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#after 0 second\\(s\\):\\s+\\*\\s+(.+?)\\s+#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>\\.\\.\\. sorry, that domain isn't in my list#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#Utilisateur.+?\\((.+?)\\)\\s+non recens#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host\\s+.+?\\[.+?said: 550 5\\.1\\.1 User unknown#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#RCPT TO: <(.+?)>\\s+Received <<< 550 5\\.1\\.1 User unknown#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#chec de la remise aux destinataires suivants\\.\\s+(.+?)\\s+#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>:\\s+[0-9\\.]+ does not like recipient\\.#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host.+?\\s+said: 550.+?5\\.1\\.0 Address rejected#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host.+?said: 550.+?5\\.1\\.0 Address\\s+rejected#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host.+?said: 550 sorry, no\\s+mailbox#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 553 sorry, that\\s+domain isn't#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 550 Requested\\s+action not taken: mailbox unavailable#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)> Recipient not allowed#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 550\\s+.+?5\\.1\\.0 Address rejected#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 550 Sorry, no mailbox here#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 550 unrouteable#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; return true; } if (preg_match("#<(.+?)>: host .+?said: 550 5\\.7\\.1 Message\\s+rejected as spam#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Cette identification n'est &agrav=\\s+e; faire qu'une seule fois\\. Tous vos futurs messages me parviendront direct#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#enlevez moi de votre mailing list#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#the fight against spam requires our outside senders to be recognized#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Our policy in security and the fight against spam requires.+?outside senders to be recognized#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Our policy for security and our willingness to fight against spam messages#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Please click the below link to allow your mail to be transmitted#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Please click on the following link in order to identify yourself to me and to allow your message to reach me#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#The address mail of your correspondent changed#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#<(.+?)>: host .+?said: 550\\s+5\\.1\\.1 User unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<mailto:(.+?)>\\s+L'adresse de messagerie que vous avez entr#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said: 550 5.7.1 Unable\\s+to relay for#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+User's Disk Quota Exceeded#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Delivery failed: Over quota#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Raison : Over quota#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#the recipients email address has changed#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Please note that I have resigned from#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#http:\\/\\/.+?\\.mailinblack.com#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Our policy in security and the fight against spam requires our#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#Veuillez.+?confirmer.+?votre envoi.+?en cliquant sur le lien ci-dessous#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#This mailbox is not used anymore. For any urgent matters, please contact#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#You can now reach following receipients#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#is blocked in my spam folder awaiting your authentication#", $datas, $re)) { @unlink($file); if (imap_mail_move($GLOBALS["MBXCON"], "{$uid}:{$uid}", "INBOX/emailing_read")) { return true; } else { events("INBOX/emailing_read: unable to mode message {$uid}:{$uid} ", imap_last_error(), $GLOBALS["ACCOUNT_IMAP"], __LINE__); } return; } if (preg_match("#<mailto:(.+?)>\\s+L'adresse de messagerie de ce destinataire est introuvable#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Reason: content policy violation#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Out of Office AutoReply#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I am away until#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I am out of office until#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Je suis absent et serai#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I am travelling till#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I will be out of the office#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Votre message est bien arriv=E9#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I am out of the office until#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Je serai absent\\(e\\)#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I AM BACK ON#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Je suis en cong.+?jusqu#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Je suis en cong=E9s jusqu#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Je suis absent\\(e\\) du bureau jusqu#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#I'm out of office until#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#R=E9ponse_automatique_d=27absence_du_bureau#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#Error writing message to safe storage#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#could not be stored to disk#", $datas, $re)) { @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); @unlink($file); return true; } if (preg_match("#<(.+?)>: host .+?said: 571\\s+.+?prohibited#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#failed:\\s+(.+?)\\s+retry time not reached#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: 550 5\\.2\\.1 This\\s+mailbox has been blocked due to inactivity#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-recipient: rfc822; (.+?)\\s+Action: failed\\s+Status: 5\\.1\\.1#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>\\.\\.\\. User is unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: 501 5\\.5\\.4\\s+Unrecognized parameter#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said:\\s+550.+?5\\.1\\.0 Address rejected#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host\\s+.+?said: 550-Invalid recipient#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#\\s+(.+?)@(.+?)\\s+.+?550 5\\.1\\.1 RESOLVER\\.ADR\\.RecipNotFound; not found#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}@{$re['2']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)> was not found in#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: 550\\s+5\\.4\\.1 Relay Access Denied#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said:\\s+550-Callout verification failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#expanded from <(.+?)>\\): Host\\s+or domain name not found\\.#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: Name service error for#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said:\\s+520 5\\.2\\.1 Mailbox Inactive#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said:\\s+550 sorry, no mailbox here#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>.+?: maildir\\s+delivery failed: Sorry#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: rfc822;(.+?)\\s+Action: failed\\s+Status: 5\\.1\\.1#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: rfc822;(.+?)\\s+Action: failed\\s+Status: [0-9\\.]+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)> recipient rejected#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: [0-9]+.+?\\.\\.\\. No such user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+ No such\\s+user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+\\s+\"Unknown User#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+host.+?said: [0-9]+\\s+Requested action not taken#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)> is not a valid mailbox#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said:\\s+[0-9]+ No relaying allowed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>.+?Mailbox does not exist#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said: [0-9]+ Recipient\\s+address rejected#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said: [0-9]+\\s+.+?is not a known user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said: [0-9]+ sorry,#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said:\\s+[0-9]+ Invalid recipient#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host.+?said: [0-9]+\\s+.+?unroutable#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said:\\s+.+?User unknow#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: invalid address#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+ unroutable#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#[0-9]+ [0-9\\.]+\\s+(.+?)\\.\\.\\. User unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>, Recipient unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?\\s+said:.+?No such user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+said: [0-9]+\\s+.+?Recipient address rejected#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#\\s+(.+?)\\s+- no such user here\\.#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+\\s+delivery error#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said:\\s+[0-9\\-\\.]+.+?does not exist#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+ [0-9\\.]+ This\\s+.+?not configured to#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+ Sorry#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#following:\\s+(.+?) \\(user not found#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Original-Recipient: rfc822;(.+?)\\s+Action: failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#failed:\\s+(.+?)\\s+retry timeout exceeded#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+user does not exist#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#failed:\\s+(.+?)\\s+Unrouteable address#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Delevery to the following recipients failed permanently:\\s+\\* (.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Your message could not be delivered to (.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Recipient address: (.+?)\\s+Reason: Remote SMTP server has rejected address#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#had permanent fatal errors .+?\\s+<(.+?)>#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Could not deliver mail to this user\\.\\s+(.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Original-Recipient: <(.+?)>\\s+Action: failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Your mail could not be delivered to the following address\\(es\\):\\s+(.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Recipient address: (.+?)\\s+Reason: Not found in directory#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#L'adresse \"(.+?)\" n'existe plus\\.#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: rfc822;<(.+?)>\\s+Diagnostic-Code: [0-9]+\\s+Action: failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Your message\\s+To:\\s+(.+?)\\s+.+?did not reach the following recipient#s", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#User unknown.+?X-Deliver-To: (.+?)\\s+#s", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#delivery problems\\s+<(.+?)>\tMessage exceeded maximum hop count#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+Sorry, no mailbox here#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#delivery problems\\s+<(.+?)>#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+Cette adresse mail n'existe pas#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#L'adresse (.+?) n'est plus active#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Returned mail: unreachable recipients:(.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#failed:\\s+(.+?)\\s+mailbox is full#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#failed:\\s+(.+?)\\s+\\(.+?\\s+Unrouteable address#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#did not receive this message:\\s+<(.+?)>\\s+Please reply#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+\\s+.+?No such user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#The following address\\(es\\) failed:\\s+(.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Unable to deliver mail.+?recipients.\\s+(.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#out\\.\\s+<(.+?)>:\\s+user is over quota#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+Mailaddress is administratively disabled#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-recipient: rfc822;(.+?)\\s+Action: failed\\s+Status: [0-9\\.]+ \\(Over quota#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#domain '(.+?)' is not an Email domain#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Unknown address error [0-9]+.+?'(.+?)\\.\\.\\. No such user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#The following message to <(.+?)> was undeliverable#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+L'adresse email entr.+?e est inexistante ou erron.+?#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: rfc822;(.+?)\\s+Diagnostic-Code: smtp; [0-9]+ Requested action not taken: mailbox unavailable#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#DELIVERY FAILURE: User .+? \\((.+?)\\)#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Failed to deliver to '<(.+?)>'#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Could not find a gateway for (.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: [0-9]+ No such recipient#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: [0-9]+ [0-9\\.]+ Hop count exceeded#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: [0-9]+ Invalid recipient#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#failed permanently:\\s+(.+?)\\s+Technical#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: host .+?said: [0-9]+\\s+[0-9\\.]+ Message contains invalid header#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#smtp;[0-9]+ Mailbox unavailable or access denied - <(.+?)>#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+.+?fatal: Sorry, I don't accept#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Diagnostic-Code: smtp; [0-9]+ (.+?)\\.\\.\\. No such user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Original-Recipient: rfc822;<(.+?)>\\s+Final-Recipient.+?\\s+Action: failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Unable to deliver message to <(.+?)>\\.#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Originally addressed to (.+?)\\)\\s+User not known#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: rfc822;(.+?)\\s+Diagnostic-Code: smtp;[0-9]+ User unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#RCPT To:<(.+?)>\\s+.+?[0-9]+ [0-9\\.]+ User unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#The email address (.+?) \\(and (.+?)\\) is no longer in use#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; $GLOBALS["FOUND_BAD_MAIL"]["{$re['2']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Unable to deliver message to <(.+?)>#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: rfc822;(.+?)\\s+Diagnostic-Code: smtp; [0-9\\.]+ None of the mail servers#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#[0-9\\.]+, '(.+?)\\.\\.\\. No such user#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: RFC822; (.+?)\\s+Action: failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#X-Greylist: Delayed for [0-9]+:[0-9]+:[0-9]+#", $datas, $re)) { @unlink($file); @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Your message to <(.+?)> was automatically rejected:\\s+Quota exceeded#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>: [0-9]+ [0-9\\.]+ User unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Invalid final delivery userid: (.+?)\\s+#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+vdeliver: Invalid or unknown#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>, sorry#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+.+?:.+?I'm sorry#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+Sorry,#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+The users mailfolder#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Final-Recipient: RFC822; (.+?)\\s+X-Actual-Recipient.+?\\s+Action: failed#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#Remote-Recipient: rfc822;<(.+?)>\\s+Diagnostic-Code: smtp;[0-9]+ SMTP-Deliver:QueuedTooLong#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+Unable to chdir to maildir#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#X-TM-AS-User-Approved-Sender: No.+?To: (.+?)\\s+From:#is", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#\\s+(.+?)\\s+Error Type: SMTP#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+Cet adresse email n'existe pas#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } if (preg_match("#<(.+?)>:\\s+[0-9\\.]+ failed after I sent the message#", $datas, $re)) { @unlink($file); $GLOBALS["FOUND_BAD_MAIL"]["{$re['1']}"] = true; @imap_delete($GLOBALS["MBXCON"], "{$uid}:{$uid}"); return true; } echo "NOT FOUND message {$uid} {$file} \"{$subject}\"\n"; return false; }
public static function check_bounces($debug = false) { $email_username = module_config::c('newsletter_bounce_username', ''); $email_password = module_config::c('newsletter_bounce_password', ''); $email_host = module_config::c('newsletter_bounce_host', ''); $email_port = module_config::c('newsletter_bounce_port', '110'); $email_ssl = module_config::c('newsletter_bounce_ssl', '/ssl'); if (!$email_username || !$email_password || !$email_host || !$email_port) { if ($debug) { echo "No username, password, host or port defined. Please check settings.\n"; } return; } $connect_string = '{' . $email_host . ':' . $email_port . $email_ssl . '/pop3/novalidate-cert}INBOX'; if ($debug) { echo "Connecting using: " . $connect_string . "\n\n"; } $mbox = imap_open($connect_string, $email_username, $email_password, 0, 1); // or die(); if (!$mbox) { // send email letting them know bounce checking failed? // meh. later. echo 'Failed to connect'; echo print_r(imap_errors()); } else { $MC = imap_check($mbox); $result = imap_fetch_overview($mbox, "1:{$MC->Nmsgs}", 0); foreach ($result as $overview) { if ($debug) { $this_subject = (string) $overview->subject; echo "\n\n--------------------------------------------------\nFound an email! \n"; echo " Subject: {$this_subject}\n"; echo " #{$overview->msgno} ({$overview->date}) - From: {$overview->from} \n"; } if (is_dir(_UCM_FOLDER . "/temp/") && is_writable(_UCM_FOLDER . "/temp/")) { $tmp_file = tempnam(_UCM_FOLDER . "/temp/", 'newsletter_bounce'); } else { $tmp_file = tempnam(sys_get_temp_dir(), 'newsletter_bounce'); } imap_savebody($mbox, $tmp_file, $overview->msgno); $body = file_get_contents($tmp_file); $this_is_a_bounce = false; if (preg_match('/Message-ID:\\s*<?Newsletter-(\\d+)-(\\d+)-(\\d+)-([A-Fa-f0-9]{32})/imsU', $body, $matches)) { // we have a newsletter message id, check the hash and mark a bounce. $newsletter_id = (int) $matches[1]; $send_id = (int) $matches[2]; $newsletter_member_id = (int) $matches[3]; $provided_hash = trim($matches[4]); if ($debug) { echo " this is a bounce newsletter. ID: {$newsletter_id} SEND: {$send_id}, Member: {$newsletter_member_id} \n"; } $real_hash = self::generate_bounce_message_id($newsletter_id, $send_id, $newsletter_member_id, true); if ($provided_hash == $real_hash) { $this_is_a_bounce = true; // YAY! valid bounce! // have to update the newsletter_member with an extra bounce_count. //$newsletter_member = get_single('newsletter_member','newsletter_member_id',$newsletter_member_id); //if($newsletter_member && $newsletter_member['newsletter_member_id'] == $newsletter_member_id){ // found the member! increment count. $sql = "UPDATE `" . _DB_PREFIX . "newsletter_member` SET bounce_count = bounce_count + 1 WHERE newsletter_member_id = " . (int) $newsletter_member_id . " LIMIT 1"; query($sql); //} // have to update newsletter_send_member with a bounce timestamp. $sql = "UPDATE " . _DB_PREFIX . "newsletter_send_member SET `status` = " . _NEWSLETTER_STATUS_BOUNCED . ", bounce_time = '" . time() . "' WHERE `newsletter_member_id` = '" . $newsletter_member_id . "' AND send_id = '" . $send_id . "' LIMIT 1"; query($sql); } else { if ($debug) { echo " WOA! Hash doesn't match, this is a big problem. Get in touch with dtbaker. \n"; echo " " . $matches[0] . " with \n"; echo " " . $real_hash . "\n"; } // bad hash, or no hash found, report this so the user can login manually and review the bounced message. } } if (!$this_is_a_bounce) { // didn't find a bounce using message ID hash. // this can be because we're sending through google. // look for the subject fields. if ($debug) { echo ' - no bounce message id found, checking for "delivery failure" message' . "\n"; } if ((preg_match('#Delivery.*Failure#i', $body) || preg_match('#Delivery.*Failed#i', $body) || preg_match('#Failed.*Delivery#i', $body)) && preg_match_all('#Subject: (.*)#', $body, $subject_matches)) { if ($debug) { echo ' - FOUND DELIVERY FAILURE' . "\n"; } // find who this newsletter was sent to $to_emails = array(); if (preg_match_all('#To: (.*)#', $body, $to_matches)) { foreach ($to_matches[1] as $possible_to_email) { // todo: ignore the "To" address of the original sender email in newsletter table, $possible_to_email = str_replace('<', ' ', $possible_to_email); $possible_to_email = str_replace('>', ' ', $possible_to_email); foreach (explode(' ', $possible_to_email) as $token) { if ($debug) { echo ' - parsing email:' . $token . "\n"; } $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL); if ($email !== false) { if ($debug) { echo ' - checking for local member:' . $email . "\n"; } $search_newsletter_member_id = self::member_from_email(array('email' => $email), false); if ($search_newsletter_member_id) { if ($debug) { echo ' - Found Local Member!:' . $email . " (ID: {$search_newsletter_member_id}) \n"; } $to_emails[] = $search_newsletter_member_id; } } } } } if (count($to_emails)) { // we have some to emails. foreach ($subject_matches[1] as $subject) { $subject = trim($subject); if (!strlen($subject)) { continue; } if ($debug) { echo ' - Checking email subject:' . $subject . "\n"; } // find a newsletter that matches this subject in our listing. $newsletters = get_multiple('newsletter_send', array('subject' => $subject)); if (count($newsletters)) { foreach ($newsletters as $newsletter_send) { if ($debug) { echo ' - found a local newsletter send matching this subject' . "\n"; //print_r($newsletter_send); } // see if this to address was in the recipient list. foreach ($to_emails as $to_member_id) { // see if this member exists in this send. $send_members = get_multiple('newsletter_send_member', array('newsletter_member_id' => $to_member_id, 'send_id' => $newsletter_send['send_id'])); if (count($send_members)) { // should really only be one, oh well. foreach ($send_members as $send_member) { if ($send_member['newsletter_member_id'] == $to_member_id) { $this_is_a_bounce = true; $sql = "UPDATE `" . _DB_PREFIX . "newsletter_member` SET bounce_count = bounce_count + 1 WHERE newsletter_member_id = " . (int) $send_member['newsletter_member_id'] . " LIMIT 1"; query($sql); //} // have to update newsletter_send_member with a bounce timestamp. $sql = "UPDATE " . _DB_PREFIX . "newsletter_send_member SET `status` = " . _NEWSLETTER_STATUS_BOUNCED . ", bounce_time = '" . time() . "' WHERE `newsletter_member_id` = '" . $send_member['newsletter_member_id'] . "' AND send_id = '" . $send_member['send_id'] . "' LIMIT 1"; query($sql); if ($debug) { echo ' - FOUND MEMBER TO BOUNCE!' . " (ID: " . $send_member['newsletter_member_id'] . "\n"; } } } } } } } } } } } if ($this_is_a_bounce) { if ($debug) { echo " SUCESS! Bounce recorded. Deleting email from inbox.\n"; } imap_delete($mbox, $overview->msgno); } else { if ($debug) { echo " FAILED! No message ID found in this email. It must not be a bounce from the newsletter system. \n"; } } unlink($tmp_file); } imap_expunge($mbox); imap_close($mbox); } if ($debug) { echo "Bounce checking finished\n"; } }
/** * This function saves the attachment to the exact specified location. * * @param string $path * @return bool */ public function saveAs($path) { $dirName = dirname($path); if (file_exists($path)) { if (!is_writable($path)) { return false; } } elseif (!is_dir($dirName) || !is_writable($dirName)) { return false; } if (($filePointer = fopen($path, 'w')) == false) { return false; } switch ($this->encoding) { case 3: //base64 $streamFilter = stream_filter_append($filePointer, 'convert.base64-decode', STREAM_FILTER_WRITE); break; case 4: //quoted-printable $streamFilter = stream_filter_append($filePointer, 'convert.quoted-printable-decode', STREAM_FILTER_WRITE); break; default: $streamFilter = null; } // Fix an issue causing server to throw an error // See: https://github.com/tedious/Fetch/issues/74 for more details imap_fetchbody($this->imapStream, $this->messageId, $this->partId ?: 1, FT_UID); $result = imap_savebody($this->imapStream, $filePointer, $this->messageId, $this->partId ?: 1, FT_UID); if ($streamFilter) { stream_filter_remove($streamFilter); } fclose($filePointer); return $result; }
<?php echo "Checking with no parameters\n"; imap_savebody(); echo "Checking with incorrect parameter type\n"; imap_savebody(''); imap_savebody(false); require_once dirname(__FILE__) . '/imap_include.inc'; $stream_id = setup_test_mailbox('', 1); imap_savebody($stream_id); $file = dirname(__FILE__) . '/tmpsavebody.txt'; //with URL $z = imap_savebody($stream_id, $file, 1); var_dump($z); echo "Size: " . filesize($file) . "\n"; //With FOPEN $fp = fopen($file, 'w'); $z = imap_savebody($stream_id, $fp, 1); fclose($fp); var_dump($z); echo "Size: " . filesize($file) . "\n"; imap_close($stream_id); @unlink(dirname(__FILE__) . '/tmpsavebody.txt'); require_once 'clean.inc';
$type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); $counter = 1; while (count($info->parts) > 1 && count($info->parts) > $counter) { if ($info->parts[$counter]->ifparameters == 1) { $filename = $info->parts[$counter]->parameters[0]->value; } else { if ($info->parts[$counter]->ifdparameters == 1) { $filename = $info->parts[$counter]->dparameters[0]->value; } } $mimetype = $type[(int) $info->parts[$counter]->type] . '/' . $info->parts[$counter]->subtype; $mimetype = strtolower($mimetype); echo " - File: {$filename} ({$mimetype})... "; $fullfilename = 'tmp/attachments/' . $uid . '/' . $filename; $file = 'tmp/attachments/' . $uid . '/mail.txt'; imap_savebody($inbox, $file, $message->msgno); $parser = new MimeMailParser(); $parser->setPath($file); $attachments = $parser->getAttachmentsAsStreams(); file_put_contents($fullfilename, $attachments[$counter - 1]); echo "done\n"; $package->addFile($filename, $mimetype); $counter++; } // Deposit the package $package->create(); $client = new SWORDAPPClient(); $response = $client->deposit($swordurl, $sworduser, $swordpassword, '', 'tmp/' . $packagefilename, 'http://purl.org/net/sword-types/METSDSpaceSIP', 'application/zip', false, true); // print_r($response); $id = $response->sac_id; $id = str_replace("http://hdl.handle.net/", "http://dspace.swordapp.org/jspui/handle/", $id);
/** * Read messages from server and save returned emails into DB * * @param resource $mbox created by dre_connect() (by reference) * @param integer the number of messages to process * @param boolean TRUE if script is executed by cron * @return boolean true on success */ function dre_process_messages(&$mbox, $limit, $cron = false) { global $Settings, $debug; global $dre_messages, $dre_emails, $email_cntr, $del_cntr, $is_cron_mode; // This may take a very long time if there are many messages; No execution time limit: set_max_execution_time(0); if ($Settings->get('repath_ignore_read')) { // Read status info of all messages in order to know which have already been read: $msg_statuses = imap_fetch_overview($mbox, '1:' . $limit); } $email_cntr = 0; $del_cntr = 0; for ($index = 1; $index <= $limit; $index++) { // Repeat for as many messages as allowed... dre_msg('<hr /><h3>' . sprintf(T_('Processing message %s:'), '#' . $index) . '</h3>', $cron); if ($Settings->get('repath_ignore_read')) { // Check if we can read this message or we should skip this: if (isset($msg_statuses[$index - 1]) && $msg_statuses[$index - 1]->seen == 1) { // Skip this message because it has already been read: dre_msg(T_('Ignoring this message because it has aleady been read.'), $cron); continue; } else { // Mark this message as "Seen" in order to don't read it twice: imap_setflag_full($mbox, $index, '\\Seen'); } } $html_body = ''; $strbody = ''; $hasAttachment = false; $hasRelated = false; // Save email to a temporary file on hard drive, otherwise BIG attachments may take a lot of RAM: if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) { dre_msg(T_('Could not create temporary file.'), $cron); continue; } // Save the whole body of a specific message from the mailbox: imap_savebody($mbox, $tmpMIME, $index); // fp> TODO: soemwhere here we should skip messages that already have the "seen" flag. This should be optional but should be the default. // This will allow to keep the emails in the INBOX without reprocessing them but to easily try them again my marking them unread. // Create random temp directory for message parts: $tmpDirMIME = dre_tempdir(sys_get_temp_dir(), 'b2evo_'); // Instanciate mime_parser.php library: $mimeParser = new mime_parser_class(); $mimeParser->mbox = 0; // Set to 0 for parsing a *single* RFC 2822 message $mimeParser->decode_headers = 1; // Set to 1 if it is necessary to decode message headers that may have non-ASCII characters and use other character set encodings $mimeParser->ignore_syntax_errors = 1; // ignore syntax errors in malformed messages. $mimeParser->extract_addresses = 0; // Associative array to specify parameters for the messagedata parsing and decoding operation. $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1); // STEP 1: Parse and decode message data and retrieve its structure: if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) { // error: dre_msg(sprintf(T_('MIME message decoding error: %s at position %d.'), $mimeParser->error, $mimeParser->error_position), $cron); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } else { // the specified message data was parsed successfully: dre_msg(T_('MIME message decoding successful'), $cron); // STEP 2: Analyze (the first) parsed message to describe its contents: if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) { // error: dre_msg(sprintf(T_('MIME message analyze error: %s'), $mimeParser->error), $cron); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // Get message $subject and $post_date from headers (by reference) if (!dre_process_header($parsedMIME, $subject, $post_date, $cron)) { // Couldn't process message headers: rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // TODO: handle type == "message" recursively // fp> where is type == "message" ??? // yura> I don't find the type == 'message' in dump of $decodedMIME and $parsedMIME // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing // yura> I replaced imap_qprint() with quoted_printable_decode() to avoid notices about invalid quoted-printable sequence // yura> imap_qprint() and quoted_printable_decode() do empty the message text, thus they were deleted. dre_msg(T_('Email Type') . ': ' . $parsedMIME['Type'], $cron); if ($parsedMIME['Type'] == 'html') { // Mail is HTML: if ($debug) { // Display this info only in debug mode: dre_msg(sprintf(T_('HTML message part saved as %s'), $parsedMIME['DataFile']), $cron); } $html_body = file_get_contents($parsedMIME['DataFile']); if (empty($html_body)) { // Try to get a body text from alternative parts if main html body is empty: foreach ($parsedMIME['Alternative'] as $alternative) { // First try to get HTML alternative (when possible) if ($alternative['Type'] == 'html') { // HTML text if ($debug) { // Display this info only in debug mode: dre_msg(sprintf(T_('HTML alternative message part saved as %s'), $alternative['DataFile']), $cron); } $strbody = file_get_contents($alternative['DataFile']); break; // stop after first alternative } elseif ($alternative['Type'] == 'text') { // Plain text if ($debug) { // Display this info only in debug mode: dre_msg(sprintf(T_('Text alternative message part saved as %s'), $alternative['DataFile']), $cron); } $strbody = file_get_contents($alternative['DataFile']); break; // stop after first alternative } } } } elseif ($parsedMIME['Type'] == 'text') { // Mail is plain text: if ($debug) { // Display this info only in debug mode: dre_msg(sprintf(T_('Plain-text message part saved as %s'), $parsedMIME['DataFile']), $cron); } $strbody = file_get_contents($parsedMIME['DataFile']); } elseif ($parsedMIME['Type'] == 'delivery-status') { // Mail is delivery-status: $strbody = $parsedMIME['Response']; } if (count($mimeParser->warnings) > 0) { // Record potential warnings: dre_msg('<h4>' . sprintf(T_('%d warnings during decode:'), count($mimeParser->warnings)) . '</h4>', $cron); foreach ($mimeParser->warnings as $k => $v) { dre_msg(sprintf(T_('Warning: %s at position %s'), $v, $k), $cron); } } } unlink($tmpMIME); if (empty($html_body)) { // Plain-text message dre_msg(sprintf(T_('Message type: %s'), 'TEXT'), $cron); // Process body. First fix different line-endings (dos, mac, unix), remove double newlines $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody)); dre_msg(sprintf(T_('Message body: %s'), '<pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>'), $cron); } else { // HTML message dre_msg(sprintf(T_('Message type: %s'), 'HTML'), $cron); dre_msg(sprintf(T_('Message body (original): %s'), '<pre style="font-size:10px">' . htmlspecialchars($html_body) . '</pre>', $cron)); // Prepare html message body text: $content = dre_prepare_html_message($html_body); dre_msg(sprintf(T_('Message body (processed): %s'), '<pre style="font-size:10px">' . htmlspecialchars($content) . '</pre>', $cron)); } dre_msg('<b class="green">' . T_('MIME Decoding Successful') . '</b>', $cron); $message_text = $content; // Remove content after terminators $content = dre_limit_by_terminators($content); global $Messages; if ($Messages->has_errors()) { // Make it easier for user to find and correct the errors dre_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), $cron); dre_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), $cron); $Messages->clear(); rmdir_r($tmpDirMIME); continue; } global $dre_emails, $DB, $localtimenow; dre_msg('<h4>' . T_('Saving the returned email in the database') . '</h4>', $cron); // Get Headers from Decoded MIME Data: $email_headers = dre_get_headers($decodedMIME); // Get data of the returned email: $email_data = dre_get_email_data($content, $message_text, $email_headers); dre_msg(T_('Email Address') . ': ' . $email_data['address'], $cron); dre_msg(T_('Error Type') . ': ' . dre_decode_error_type($email_data['errtype']), $cron); dre_msg(T_('Error Message') . ': ' . $email_data['errormsg'], $cron); // Insert a returned email's data into DB if (dre_insert_returned_email($email_data)) { ++$email_cntr; } // Delete temporary directory: rmdir_r($tmpDirMIME); // Mark message to be deleted: if ($Settings->get('repath_delete_emails')) { dre_msg(sprintf(T_('Marking message for deletion from inbox: %s'), $index), $cron); imap_delete($mbox, $index); ++$del_cntr; } } // Expunge messages marked for deletion imap_expunge($mbox); return true; }
/** * Save mail body. * @return bool */ public function saveMail($mailId, $filename = 'email.eml') { return imap_savebody($this->getImapStream(), $filename, $mailId, "", FT_UID); }
public static function import_email($ticket_account_id, $import = true, $debug = false) { require_once 'includes/plugin_ticket/cron/rfc822_addresses.php'; require_once 'includes/plugin_ticket/cron/mime_parser.php'; $admins_rel = self::get_ticket_staff_rel(); $created_tickets = array(); $ticket_account_id = (int) $ticket_account_id; $account = self::get_ticket_account($ticket_account_id); if (!$account) { return false; } $email_account_address = $account['email']; $email_username = $account['username']; $email_password = $account['password']; $email_host = $account['host']; $email_port = $account['port']; $reply_from_user_id = $account['default_user_id']; $support_type = (int) $account['default_type']; $subject_regex = $account['subject_regex']; $body_regex = $account['body_regex']; $to_regex = $account['to_regex']; $search_string = $account['search_string']; $mailbox = $account['mailbox']; $imap = (int) $account['imap']; $secure = (int) $account['secure']; $start_date = $account['start_date'] && $account['start_date'] != '0000-00-00' ? $account['start_date'] : false; if (!$email_host || !$email_username) { return false; } // try to connect with ssl first: $ssl = $secure ? '/ssl' : ''; if ($imap) { $host = '{' . $email_host . ':' . $email_port . '/imap' . $ssl . '/novalidate-cert}' . $mailbox; if ($debug) { echo "Connecting to {$host} <br>\n"; } $mbox = imap_open($host, $email_username, $email_password); } else { $host = '{' . $email_host . ':' . $email_port . '/pop3' . $ssl . '/novalidate-cert}' . $mailbox; if ($debug) { echo "Connecting to {$host} <br>\n"; } $mbox = imap_open($host, $email_username, $email_password); } if (!$mbox) { // todo: send email letting them know bounce checking failed? echo 'Failed to connect when checking for support ticket emails.' . imap_last_error(); imap_errors(); return false; } update_insert('ticket_account_id', $account['ticket_account_id'], 'ticket_account', array('last_checked' => time())); $MC = imap_check($mbox); //echo 'Connected'.$MC->Nmsgs; // do a search if $search_results = array(-1); if ($imap && $search_string) { //imap_sort($mbox,SORTARRIVAL,0); // we do a hack to support multiple searches in the imap string. if (strpos($search_string, '||')) { $search_strings = explode('||', $search_string); } else { $search_strings = array($search_string); } $search_results = array(); foreach ($search_strings as $this_search_string) { $this_search_string = trim($this_search_string); if (!$this_search_string) { return false; } if ($debug) { echo "Searching for {$this_search_string} <br>\n"; } $this_search_results = imap_search($mbox, $this_search_string); if ($debug) { echo " -- found " . count($this_search_results) . " results <br>\n"; } $search_results = array_merge($search_results, $this_search_results); } if (!$search_results) { echo "No search results for {$search_string} "; return false; } else { sort($search_results); } } imap_errors(); //print_r($search_results);//imap_close($mbox);return false; $sorted_emails = array(); foreach ($search_results as $search_result) { if ($search_result >= 0) { $result = imap_fetch_overview($mbox, $search_result, 0); } else { //$result = imap_fetch_overview($mbox,"1:100",0); $result = imap_fetch_overview($mbox, "1:" . min(100, $MC->Nmsgs), 0); } foreach ($result as $overview) { if (!isset($overview->subject) && (!isset($overview->date) || !$overview->date)) { continue; } $overview->subject = self::_subject_decode(isset($overview->subject) ? (string) $overview->subject : ''); if ($subject_regex && !preg_match($subject_regex, $overview->subject)) { continue; } if (!isset($overview->date)) { $overview->date = date('Y-m-d H:i:s'); } if ($start_date > 1000) { if (strtotime($overview->date) < strtotime($start_date)) { continue; } } $message_id = isset($overview->message_id) ? (string) $overview->message_id : false; if (!$message_id) { $overview->message_id = $message_id = md5($overview->subject . $overview->date); } //echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from} <br> {$this_subject} <br>\n"; // check this email hasn't been processed before. // check this message hasn't been processed yet. $ticket = get_single('ticket_message', 'message_id', $message_id); if ($ticket) { continue; } // get ready to sort them. $overview->time = strtotime($overview->date); $sorted_emails[] = $overview; } } if (!function_exists('dtbaker_ticket_import_sort')) { function dtbaker_ticket_import_sort($a, $b) { return $a->time > $b->time; } } uasort($sorted_emails, 'dtbaker_ticket_import_sort'); $message_number = 0; foreach ($sorted_emails as $overview) { $message_number++; $message_id = (string) $overview->message_id; if ($debug) { ?> <div style="padding:5px; border:1px solid #EFEFEF; margin:4px;"> <div> <strong><?php echo $message_number; ?> </strong> Date: <strong><?php echo $overview->date; ?> </strong> <br/> Subject: <strong><?php echo htmlspecialchars($overview->subject); ?> </strong> <br/> From: <strong><?php echo htmlspecialchars($overview->from); ?> </strong> To: <strong><?php echo htmlspecialchars($overview->to); ?> </strong> <!-- <a href="#" onclick="document.getElementById('msg_<?php echo $message_number; ?> ').style.display='block'; return false;">view body</a> </div> <div style="display:none; padding:10px; border:1px solid #CCC;" id="msg_<?php echo $message_number; ?> "> <?php // echo htmlspecialchars($results['Data']); ?> --> </div> </div> <?php } if (!$import) { continue; } $tmp_file = tempnam(_UCM_FOLDER . '/temp/', 'ticket'); imap_savebody($mbox, $tmp_file, $overview->msgno); $mail_content = file_get_contents($tmp_file); $mime = new mime_parser_class(); $mime->mbox = 0; $mime->decode_bodies = 1; $mime->ignore_syntax_errors = 1; $parameters = array('Data' => $mail_content); $parse_success = false; if (!$mime->Decode($parameters, $decoded)) { //echo 'MIME message decoding error: '.$mime->error.' at position '.$mime->error_position."\n"; // TODO - send warning email to admin. send_error("Failed to decode this email: " . $mail_content); $parse_success = true; // so it delets the email below if that account setting is setfalse; } else { for ($message = 0; $message < count($decoded); $message++) { if ($mime->Analyze($decoded[$message], $results)) { if (isset($results['From'][0]['address'])) { $from_address = $results['From'][0]['address']; } else { continue; } /*$results: Array ( [Type] => html [Description] => HTML message [Encoding] => iso-8859-1 [Data] => asdfasdf [Alternative] => Array ( [0] => Array ( [Type] => text [Description] => Text message [Encoding] => iso-8859-1 [Data] => asdfasdf ) ) [Subject] => [TICKET:004372] Re: Testing cc and bcc fields... [Date] => Sun, 24 Mar 2013 22:04:49 +1000 [From] => Array ( [0] => Array ( [address] => email@gmail.com [name] => Dave ) ) [To] => Array ( [0] => Array ( [address] => email@dtbaker. [name] => dtbaker Support ) [1] => Array ( [address] => email+test@gmail.com ) ) [Cc] => Array ( [0] => Array ( [address] => email+testcc@gmail.com ) [1] => Array ( [address] => info@email.com.au [name] => Hayley ) ) ) */ if ($to_regex) { $to_match = false; foreach ($results['To'] as $possible_to_address) { if (preg_match($to_regex, $possible_to_address['address'])) { $to_match = true; } } if (!$to_match) { continue; } } // find out which accout this sender is from. if (preg_match('/@(.*)$/', $from_address, $matches)) { // run a hook now to parse the from address. $domain = $matches[1]; // find this sender in the database. // if we cant find this sender/customer in the database // then we add this customer as a "support user" to the default customer for this ticketing system. // based on the "to" address of this message. //store this as an eamil $email_to = ''; $email_to_first = current($results['To']); if ($email_to_first) { $email_to = $email_to_first['address']; } // work out the from and to users. $from_user_id = 0; $to_user_id = 0; // this is admin. leave blank for now i guess. // try to find a user based on this from email address. $sql = "SELECT * FROM `" . _DB_PREFIX . "user` u WHERE u.`email` LIKE '" . mysql_real_escape_string($from_address) . "' ORDER BY `date_created` DESC"; $ticket_user_account = $from_user = qa1($sql); // convert the name if it's encoded strangely: if (isset($results['From'][0]['name']) && strlen($results['From'][0]['name']) && isset($results['Encoding']) && strtolower($results['Encoding']) != 'utf8' && strtolower($results['Encoding']) != 'utf-8') { //$name_decoded = quoted_printable_decode($results['From'][0]['name']); if (function_exists('mb_convert_encoding')) { $name_decoded = mb_convert_encoding($results['From'][0]['name'], 'UTF-8', $results['Encoding']); if (strlen($name_decoded) > 0) { $results['From'][0]['name'] = $name_decoded; } } } // todo! this user may be in the system twice! // eg: once from submitting a ticket - then again when creating that user as a contact under a different customer. // so we find the latest entry and use that... ^^ done! updated the above to sort by date updated. if ($from_user) { $from_user_id = $from_user['user_id']; // woo!!found a user. assign this customer to the ticket. if ($from_user['customer_id']) { //$account['default_customer_id'] = $from_user['customer_id']; } } else { if (module_config::c('ticket_allow_new_from_email', 1)) { // create a user under this account customer because we allow new emails to be created if ($account['default_customer_id']) { // create a new support user! go go! $ticket_user_account = $from_user = array('name' => isset($results['From'][0]['name']) ? $results['From'][0]['name'] : $from_address, 'customer_id' => $account['default_customer_id'], 'email' => $from_address, 'status_id' => 1, 'password' => substr(md5(time() . mt_rand(0, 600)), 3)); global $plugins; $from_user_id = $plugins['user']->create_user($from_user, 'support'); $ticket_user_account['user_id'] = $from_user_id; } else { $ticket_user_account = $from_user = array('name' => isset($results['From'][0]['name']) ? $results['From'][0]['name'] : $from_address, 'customer_id' => -1, 'email' => $from_address, 'status_id' => 1, 'password' => substr(md5(time() . mt_rand(0, 600)), 3)); global $plugins; $from_user_id = $plugins['user']->create_user($from_user, 'support'); $ticket_user_account['user_id'] = $from_user_id; //echo 'Failed - no from account set'; //continue; } } } if (!$from_user_id) { // creating a new user for this ticket. not allowed for spam reasons sometimes. if (module_config::c('ticket_allow_new_from_email', 1)) { // failed to create a user in the database. echo 'Failed - cannot find the from user id'; echo $from_address . ' to ' . var_export($results['To'], true) . ' : subject: ' . $overview->subject . '<hr>'; continue; } else { // new option to ignore these emails and force people to submit new tickets via the web interface // send an autoreply to this user saying that their ticket was not created. $temp_from_user = array('name' => isset($results['From'][0]['name']) ? $results['From'][0]['name'] : $from_address, 'email' => $from_address); module_ticket::send_customer_rejection_alert($temp_from_user, $overview->subject); echo 'Rejecting new tickets'; $parse_success = true; continue; } } $message_type_id = _TICKET_MESSAGE_TYPE_CREATOR; // from an end user. if (strtolower($from_address) == strtolower($email_account_address)) { $message_type_id = _TICKET_MESSAGE_TYPE_ADMIN; // from an admin replying via email. } else { if (strtolower($from_address) == strtolower(module_config::c('ticket_admin_email_alert'))) { $message_type_id = _TICKET_MESSAGE_TYPE_ADMIN; // from an admin replying via email. } else { if (isset($admins_rel[$from_user_id])) { $message_type_id = _TICKET_MESSAGE_TYPE_ADMIN; // from an admin replying via email. } } } $sql = "SELECT * FROM `" . _DB_PREFIX . "user` u WHERE u.`email` LIKE '" . mysql_real_escape_string($email_to) . "'"; $to_user_temp = qa1($sql); if ($to_user_temp) { $to_user_id = $to_user_temp['user_id']; // hack for BCC support (eg: email invoice, bcc goes to our ticket email address). if ($message_type_id == _TICKET_MESSAGE_TYPE_ADMIN) { // swap these around. the email is coming from us to the customer. $ticket_user_account = array('customer_id' => $to_user_temp['customer_id'], 'user_id' => $to_user_temp['user_id']); } } $ticket_id = false; $new_message = true; // check if the subject matches an existing ticket subject. if (preg_match('#\\[TICKET:(\\d+)\\]#i', $overview->subject, $subject_matches) || preg_match('#\\#(\\d+)#', $overview->subject, $subject_matches)) { // found an existing ticket. // find this ticket in the system. $ticket_id = ltrim($subject_matches[1], '0'); // see if it exists. $existing_ticket = get_single('ticket', 'ticket_id', $ticket_id); if ($existing_ticket) { // woot! // search to see if this "from" address is in any of the past ticket messages. $valid_previous_contact = false; if ($message_type_id == _TICKET_MESSAGE_TYPE_ADMIN) { $valid_previous_contact = true; } else { $past_ticket_messages = self::get_ticket_messages($existing_ticket['ticket_id'], true); //foreach($past_ticket_messages as $past_ticket_message){ while ($past_ticket_message = mysql_fetch_assoc($past_ticket_messages)) { $past_header_cache = @unserialize($past_ticket_message['cache']); $past_to_temp = array(); if ($past_ticket_message['to_user_id']) { $past_to_temp = module_user::get_user($past_ticket_message['to_user_id'], false); } else { if ($past_header_cache && isset($past_header_cache['to_email'])) { $past_to_temp['email'] = $past_header_cache['to_email']; } } if (isset($past_to_temp['email']) && strtolower($past_to_temp['email']) == strtolower($from_address)) { $valid_previous_contact = true; break; } foreach (array('to_emails', 'cc_emails', 'bcc_emails') as $header_cache_key) { if ($past_header_cache && isset($past_header_cache[$header_cache_key]) && is_array($past_header_cache[$header_cache_key])) { foreach ($past_header_cache[$header_cache_key] as $to_email_additional) { if (isset($to_email_additional['address']) && strlen($to_email_additional['address']) && strtolower($to_email_additional['address']) == strtolower($from_address)) { $valid_previous_contact = true; break 3; } } } } } } if ($valid_previous_contact) { update_insert('ticket_id', $ticket_id, 'ticket', array('status_id' => _TICKET_STATUS_IN_PROGRESS_ID, 'last_message_timestamp' => strtotime($overview->date))); $new_message = false; } else { // create new message based on this one. // remove the old ticket ID number from subject $ticket_id = false; $overview->subject = str_replace($subject_matches[0], '', $overview->subject); } } else { // fail.. $ticket_id = false; } } else { // we search for this subject, and this sender, to see if they have sent a follow up // before we started the ticketing system. // handy for importing an existing inbox with replies etc.. // check to see if the subject matches any existing subjects. $search_subject1 = trim(preg_replace('#^Re:?\\s*#i', '', $overview->subject)); $search_subject2 = trim(preg_replace('#^Fwd?:?\\s*#i', '', $overview->subject)); $search_subject3 = trim($overview->subject); // find any threads that match this subject, from this user id. $sql = "SELECT * FROM `" . _DB_PREFIX . "ticket` t "; $sql .= " WHERE t.`user_id` = " . (int) $from_user_id . " "; $sql .= " AND ( t.`subject` LIKE '%" . mysql_real_escape_string($search_subject1) . "%' OR "; $sql .= " t.`subject` LIKE '%" . mysql_real_escape_string($search_subject2) . "%' OR "; $sql .= " t.`subject` LIKE '%" . mysql_real_escape_string($search_subject3) . "%') "; $sql .= " ORDER BY ticket_id DESC;"; $match = qa1($sql); if (count($match) && (int) $match['ticket_id'] > 0) { // found a matching email. stoked! // add it in as a reply from the end user. $ticket_id = $match['ticket_id']; update_insert('ticket_id', $ticket_id, 'ticket', array('status_id' => _TICKET_STATUS_IN_PROGRESS_ID, 'last_message_timestamp' => strtotime($overview->date))); $new_message = false; } if (!$ticket_id) { // now we see if any match the "TO" address, ie: it's us replying to the user. // handly from a gmail import. if ($email_to) { $sql = "SELECT * FROM `" . _DB_PREFIX . "user` u WHERE u.`email` LIKE '" . mysql_real_escape_string($email_to) . "'"; $temp_to_user = qa1($sql); if ($temp_to_user && $temp_to_user['user_id']) { // we have sent emails to this user before... // check to see if the subject matches any existing subjects. $sql = "SELECT * FROM `" . _DB_PREFIX . "ticket` t "; $sql .= " WHERE t.`user_id` = " . (int) $temp_to_user['user_id'] . " "; $sql .= " AND ( t.`subject` LIKE '%" . mysql_real_escape_string($search_subject1) . "%' OR "; $sql .= " t.`subject` LIKE '%" . mysql_real_escape_string($search_subject2) . "%' OR "; $sql .= " t.`subject` LIKE '%" . mysql_real_escape_string($search_subject3) . "%') "; $sql .= " ORDER BY ticket_id DESC;"; $match = qa1($sql); if (count($match) && (int) $match['ticket_id'] > 0) { // found a matching email. stoked! // add it in as a reply from the end user. $ticket_id = $match['ticket_id']; update_insert('ticket_id', $ticket_id, 'ticket', array('status_id' => _TICKET_STATUS_IN_PROGRESS_ID, 'last_message_timestamp' => strtotime($overview->date))); $new_message = false; } } } } } if (!$ticket_id) { $ticket_id = update_insert('ticket_id', 'new', 'ticket', array('subject' => $overview->subject, 'ticket_account_id' => $account['ticket_account_id'], 'status_id' => _TICKET_STATUS_NEW_ID, 'user_id' => $ticket_user_account['user_id'], 'customer_id' => $ticket_user_account['customer_id'], 'assigned_user_id' => $reply_from_user_id, 'ticket_type_id' => $support_type, 'last_message_timestamp' => strtotime($overview->date))); } if (!$ticket_id) { echo 'Error creating ticket'; continue; } module_ticket::mark_as_unread($ticket_id); $cache = array('from_email' => $from_address, 'to_email' => $email_to, 'to_emails' => isset($results['To']) && is_array($results['To']) ? $results['To'] : array(), 'cc_emails' => isset($results['Cc']) && is_array($results['Cc']) ? $results['Cc'] : array()); // pull otu the email bodyu. $body = $results['Data']; //if($from_address=='*****@*****.**'){ if (isset($results['Encoding']) && strtolower($results['Encoding']) != 'utf8' && strtolower($results['Encoding']) != 'utf-8') { //mail('*****@*****.**','Ticket import results: Encoding',$results['Encoding']."\n\n".var_export($results,true)); //$body2 = quoted_printable_decode($body); if (function_exists('mb_convert_encoding')) { $body3 = mb_convert_encoding($body, 'UTF-8', $results['Encoding']); //$body3 = mb_convert_encoding($body,'HTML-ENTITIES',$results['Encoding']); //$body4 = iconv_mime_decode($body,ICONV_MIME_DECODE_CONTINUE_ON_ERROR,"UTF-8"); //mail('*****@*****.**','Ticket import results: Converted',$body . "\n\n\n\n\n ------------ " . $body2 . "\n\n\n\n\n ------------ " . $body3); if (strlen($body3) > 0) { $body = $body3; } } } //} // debug if ($results['Type'] == "html") { $is_html = true; } else { // convert body to html, so we can do wrap. $body = nl2br($body); $is_html = true; } // find the alt body. $altbody = ''; if (isset($results['Alternative']) && is_array($results['Alternative'])) { foreach ($results['Alternative'] as $alt_id => $alt) { if ($alt['Type'] == "text") { $altbody = $alt['Data']; // if($from_address=='*****@*****.**'){ if (isset($results['Encoding']) && strtolower($results['Encoding']) != 'utf8' && strtolower($results['Encoding']) != 'utf-8') { //$altbody2 = quoted_printable_decode($altbody); if (function_exists('mb_convert_encoding')) { $altbody3 = mb_convert_encoding($altbody, 'UTF-8', $results['Encoding']); if (strlen($altbody3) > 0) { $altbody = $altbody3; } } } //} break; } } } if (!$altbody) { // should really never happen, but who knows. // edit - i think this happens with godaddy webmailer. $altbody = $body; // todo: strip any html. $altbody = preg_replace('#<br[^>]*>\\n*#imsU', "\n", $altbody); $altbody = strip_tags($altbody); } // pass the body and altbody through a hook so we can modify it if needed. // eg: for envato tickets we strip the header/footer out and check the link to see if the buyer really bought anything. // run_hook(... //echo "<hr>$body<hr>$altbody<hr><br><br><br>"; // save the message! $ticket_message_id = update_insert('ticket_message_id', 'new', 'ticket_message', array('ticket_id' => $ticket_id, 'message_id' => $message_id, 'content' => $altbody, 'htmlcontent' => $body, 'message_time' => strtotime($overview->date), 'message_type_id' => $message_type_id, 'from_user_id' => $from_user_id, 'to_user_id' => $to_user_id, 'cache' => serialize($cache), 'status_id' => _TICKET_STATUS_IN_PROGRESS_ID)); if (isset($results['Related'])) { foreach ($results['Related'] as $related) { if (isset($related['FileName']) && $related['FileName']) { // save as attachment against this email. $attachment_id = update_insert('ticket_message_attachment_id', 'new', 'ticket_message_attachment', array('ticket_id' => $ticket_id, 'ticket_message_id' => $ticket_message_id, 'file_name' => $related['FileName'], 'content_type' => $related['Type'] . (isset($related['SubType']) ? '/' . $related['SubType'] : ''))); $result = file_put_contents('includes/plugin_ticket/attachments/' . $attachment_id . '', $related['Data']); if (!$result) { send_error("Failed to save attachment (named: " . $related['FileName'] . " for this email: \n\n\n\n" . var_export($related, true) . "\n\n\n" . var_export($results, true) . "\n\n\n" . $mail_content); } } } } if (isset($results['Attachments'])) { foreach ($results['Attachments'] as $related) { if (isset($related['FileName']) && $related['FileName']) { // save as attachment against this email. $attachment_id = update_insert('ticket_message_attachment_id', 'new', 'ticket_message_attachment', array('ticket_id' => $ticket_id, 'ticket_message_id' => $ticket_message_id, 'file_name' => $related['FileName'], 'content_type' => $related['Type'] . (isset($related['SubType']) ? '/' . $related['SubType'] : ''))); $result = file_put_contents('includes/plugin_ticket/attachments/' . $attachment_id . '', $related['Data']); if (!$result) { send_error("Failed to save attachment (named: " . $related['FileName'] . " for this email: \n\n\n\n" . var_export($related, true) . "\n\n\n" . var_export($results, true) . "\n\n\n" . $mail_content); } } } } //$new_message && if (!preg_match('#failure notice#i', $overview->subject)) { // we don't sent ticket autoresponders when the from user and to user are teh same if ($from_user_id && $to_user_id && $from_user_id == $to_user_id) { } else { $created_tickets[$ticket_id] = $ticket_id; } } $parse_success = true; } } } } if ($parse_success && $account['delete']) { // remove email from inbox if needed. imap_delete($mbox, $overview->msgno); } unlink($tmp_file); } imap_errors(); //} imap_expunge($mbox); imap_close($mbox); imap_errors(); return $created_tickets; }