postie with topic post_type using bbpress
-
Hello,
the plugin publish on forum but not in the forum id choosed as category,
for example: if you send subject: topic// -402- Real Topic
it return a discussion in none forum called -402- Real Topic.
So I’ve changed a bit the code of the postie_functions.php.
What I obtain is that
1)now the title is: Real Topic
2)and the post_parent is 402 (id of the forum post) but going on that forum no topic is visualized (instead going directy on page is viewed as child of the forum).Here the code, maybe some can help me to finish this. search for $Treat_as_topic and $Treat_as_topic_id to find the modifications
<?php /* $Id: postie-functions.php 1396810 2016-04-15 19:31:58Z WayneAllen $ */ $Treat_as_topic = 0; $Treat_as_topic_id = NULL; class PostiePostModifiers { var $PostFormat = 'standard'; function apply($postid) { if ($this->PostFormat != 'standard') { set_post_format($postid, $this->PostFormat); } } } if (!function_exists('boolval')) { function boolval($val) { return (bool) $val; } } if (!function_exists('mb_str_replace')) { if (function_exists('mb_split')) { function mb_str_replace($search, $replace, $subject, &$count = 0) { if (!is_array($subject)) { // Normalize $search and $replace so they are both arrays of the same length $searches = is_array($search) ? array_values($search) : array($search); $replacements = array_pad(is_array($replace) ? array_values($replace) : array($replace), count($searches), ''); foreach ($searches as $key => $search) { $parts = mb_split(preg_quote($search), $subject); $count += count($parts) - 1; $subject = implode($replacements[$key], $parts); } } else { // Call mb_str_replace for each subject in array, recursively foreach ($subject as $key => $value) { $subject[$key] = mb_str_replace($search, $replace, $value, $count); } } return $subject; } } else { function mb_str_replace($search, $replace, $subject, &$count = null) { return str_replace($search, $replace, $subject, $count); } } } function postie_environment($force_display = false) { DebugEcho("Postie Version: " . POSTIE_VERSION, $force_display); DebugEcho("WordPress Version: " . get_bloginfo('version'), $force_display); DebugEcho("PHP Version: " . phpversion(), $force_display); DebugEcho("OS: " . php_uname(), $force_display); DebugEcho("POSTIE_DEBUG: " . (IsDebugMode() ? "On" : "Off"), $force_display); DebugEcho("Time: " . date('Y-m-d H:i:s', time()) . " GMT", $force_display); DebugEcho("Error log: " . ini_get('error_log'), $force_display); DebugEcho("TMP dir: " . get_temp_dir(), $force_display); DebugEcho("Postie is in " . plugin_dir_path(__FILE__), $force_display); if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) { DebugEcho("Alternate cron is enabled", $force_display); } if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) { DebugEcho("WordPress cron is disabled. Postie will not run unless you have an external cron set up.", $force_display); } DebugEcho("Cron: " . (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON === true ? "Off" : "On"), $force_display); DebugEcho("Alternate Cron: " . (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON === true ? "On" : "Off"), $force_display); if (defined('WP_CRON_LOCK_TIMEOUT') && WP_CRON_LOCK_TIMEOUT === true) { DebugEcho("Cron lock timeout is:" . WP_CRON_LOCK_TIMEOUT, $force_display); } } function postie_disable_revisions($restore = false) { global $_wp_post_type_features, $_postie_revisions; if (!$restore) { $_postie_revisions = false; if (isset($_wp_post_type_features['post']) && isset($_wp_post_type_features['post']['revisions'])) { $_postie_revisions = $_wp_post_type_features['post']['revisions']; unset($_wp_post_type_features['post']['revisions']); } } else { if ($_postie_revisions) { $_wp_post_type_features['post']['revisions'] = $_postie_revisions; } } } /* this function is necessary for wildcard matching on non-posix systems */ if (!function_exists('fnmatch')) { function fnmatch($pattern, $string) { $pattern = strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']')); return preg_match('/^' . strtr(addcslashes($pattern, '/\\.+^$(){}=!<>|'), array('*' => '.*', '?' => '.?')) . '$/i', $string); } } function postie_log_onscreen($data) { if (php_sapi_name() == "cli") { print( "$data\n"); } else { //flush the buffers while (ob_get_level() > 0) { ob_end_flush(); } print( "
" . htmlspecialchars($data) . "
\n");
}
}function postie_log_error($v) {
postie_log_onscreen($v);
error_log("Postie [error]: $v");
}function postie_log_debug($data) {
error_log("Postie [debug]: $data");
}function EchoError($v) {
postie_log_error($v);
do_action('postie_log_debug', $v);
}function DebugDump($v) {
if (defined('POSTIE_DEBUG') && true == POSTIE_DEBUG) {
postie_log_onscreen(print_r($v, true));
}
do_action('postie_log_debug', print_r($v, true));
}function DebugEcho($v, $force = false) {
if ($force || (defined('POSTIE_DEBUG') && true == POSTIE_DEBUG)) {
postie_log_onscreen($v);
}
do_action('postie_log_debug', $v);
}function tag_Date(&$content, $message_date, $isHtml) {
//don't apply any offset here as it is accounted for later
$html = LoadDOM($content);
if ($html !== false) {
$es = $html->find('text');
//DebugEcho("tag_Date: html " . count($es));
foreach ($es as $e) {
//DebugEcho("tag_Date: " . trim($e->plaintext));
$matches = array();
if (1 === preg_match("/^date:\s?(.*)$/im", trim($e->plaintext), $matches)) {
$possibledate = trim($matches[1]);
DebugEcho("tag_Date: found date tag $matches[1]");
$newdate = strtotime($possibledate);
if (false !== $newdate) {
$t = date("H:i:s", $newdate);
DebugEcho("tag_Date: original time: $t");$format = "Y-m-d";
if ($t != '00:00:00') {
$format.= " H:i:s";
}
$message_date = date($format, $newdate);
$content = str_replace($matches[0], '', $content);
break;
} else {
DebugEcho("tag_Date: failed to parse '$possibledate' ($newdate)");
}
}
}
} else {
DebugEcho("tag_Date: not html");
}
return $message_date;
}function CreatePost($poster, $mimeDecodedEmail, $post_id, &$is_reply, $config, $postmodifiers) {
global $Treat_as_topic_id;
$fulldebug = IsDebugMode();
$fulldebugdump = false;extract($config);
$attachments = array(
"html" => array(), //holds the html for each image
"cids" => array(), //holds the cids for HTML email
"image_files" => array() //holds the files for each image
);if (array_key_exists('message-id', $mimeDecodedEmail->headers)) {
DebugEcho("Message Id is :" . htmlentities($mimeDecodedEmail->headers["message-id"]));
if ($fulldebugdump) {
DebugDump($mimeDecodedEmail);
}
}filter_PreferedText($mimeDecodedEmail, $config['prefer_text_type']);
if ($fulldebugdump) {
DebugDump($mimeDecodedEmail);
}$content = GetContent($mimeDecodedEmail, $attachments, $post_id, $poster, $config);
if ($fulldebug) {
DebugEcho("CreatePost: '$content'");
DebugDump($attachments);
}
if (IsDebugMode()) {
$dname = POSTIE_ROOT . DIRECTORY_SEPARATOR . "test_emails" . DIRECTORY_SEPARATOR;
if (is_dir($dname)) {
$fname = $dname . sanitize_file_name($mimeDecodedEmail->headers["message-id"]);
$file = fopen($fname . ".content.txt ", "w");
fwrite($file, $content);
fclose($file);
}
}$subject = GetSubject($mimeDecodedEmail, $content, $config);
filter_RemoveSignature($content, $config);
if ($fulldebug) {
DebugEcho("post sig: $content");
}$post_excerpt = tag_Excerpt($content, $config);
if ($fulldebug) {
DebugEcho("post excerpt: $content");
}$postAuthorDetails = getPostAuthorDetails($subject, $content, $mimeDecodedEmail);
if ($fulldebug) {
DebugEcho("post author: $content");
}$message_date = NULL;
if (array_key_exists("date", $mimeDecodedEmail->headers) && !empty($mimeDecodedEmail->headers["date"])) {
DebugEcho("date header: {$mimeDecodedEmail->headers['date']}");
$cte = "";
$cs = "";
if (property_exists($mimeDecodedEmail, 'content-transfer-encoding') && array_key_exists('content-transfer-encoding', $mimeDecodedEmail->headers)) {
$cte = $mimeDecodedEmail->headers["content-transfer-encoding"];
}
if (property_exists($mimeDecodedEmail, 'ctype_parameters') && array_key_exists('charset', $mimeDecodedEmail->ctype_parameters)) {
$cs = $mimeDecodedEmail->ctype_parameters["charset"];
}
$message_date = HandleMessageEncoding($cte, $cs, $mimeDecodedEmail->headers["date"], $config['message_encoding'], $config['message_dequote']);
DebugEcho("decoded date: $message_date");
} else {
DebugEcho("date header missing");
}
$message_date = tag_Date($content, $message_date, 'html' == $config['prefer_text_type']);list($post_date, $post_date_gmt, $delay) = tag_Delay($content, $message_date, $config['time_offset']);
if ($fulldebug) {
DebugEcho("post date: $content");
}filter_Ubb2HTML($content);
if ($fulldebug) {
DebugEcho("post ubb: $content");
}//do post type before category to keep the subject line correct
$post_type = tag_PostType($subject, $postmodifiers, $config);
if ($fulldebug) {
DebugEcho("post type: $content");
}$default_categoryid = $config['default_post_category'];
DebugEcho("pre category: $default_categoryid");
$default_categoryid = apply_filters('postie_category_default', $default_categoryid);
DebugEcho("post postie_category_default $default_categoryid");
$post_categories = tag_Categories($subject, $default_categoryid, $config, $post_id);
if ($fulldebug) {
DebugEcho("post category: $content");
}$post_tags = tag_Tags($content, $config['default_post_tags'], 'html' == $config['prefer_text_type']);
if ($fulldebug) {
DebugEcho("post tag: $content");
}$comment_status = tag_AllowCommentsOnPost($content);
if ($fulldebug) {
DebugEcho("post comment: $content");
}$post_status = tag_Status($content, $post_status);
if ($fulldebug) {
DebugEcho("post status: $content");
}//handle CID before linkify
filter_ReplaceImageCIDs($content, $attachments, $config);
if ($fulldebug) {
DebugEcho("post cid: $content");
}if ($config['converturls']) {
$content = filter_Linkify($content, 'html' == $config['prefer_text_type']);
if ($fulldebug) {
DebugEcho("post linkify: $content");
}
}filter_VodafoneHandler($content, $attachments);
if ($fulldebug) {
DebugEcho("post vodafone: $content");
}$customImages = tag_CustomImageField($content, $attachments, $config);
if ($fulldebug) {
DebugEcho("post custom: $content");
}if ($config['reply_as_comment'] == true) {
$id = GetParentPostForReply($subject);
if (empty($id)) {
DebugEcho("Not a reply");
$id = $post_id;
$is_reply = false;
} else {
DebugEcho("Reply detected");
$is_reply = true;
if (true == $config['strip_reply']) {
// strip out quoted content
$lines = explode("\n", $content);
$newContents = '';
foreach ($lines as $line) {
if (preg_match("/^>.*/i", $line) == 0 &&
preg_match("/^(from|subject|to|date):.*?/i", $line) == 0 &&
preg_match("/^-+.*?(from|subject|to|date).*?/i", $line) == 0 &&
preg_match("/^on.*?wrote:$/i", $line) == 0 &&
preg_match("/^-+\s*forwarded\s*message\s*-+/i", $line) == 0) {
$newContents.="$line\n";
}
}
if ((strlen($newContents) <> strlen($content)) && ('html' == $config['prefer_text_type'])) {
DebugEcho("Attempting to fix reply html (before): $newContents");
$newContents = LoadDOM($newContents)->__toString();
DebugEcho("Attempting to fix reply html (after): $newContents");
}
$content = $newContents;
}
wp_delete_post($post_id);
}
} else {
$id = $post_id;
DebugEcho("Replies will not be processed as comments");
}if ($delay != 0 && $post_status == 'publish') {
$post_status = 'future';
}filter_Newlines($content, $config);
if ($fulldebug) {
DebugEcho("post newline: $content");
}filter_Start($content, $config);
if ($fulldebug) {
DebugEcho("post start: $content");
}filter_End($content, $config);
if ($fulldebug) {
DebugEcho("post end: $content");
}//if ($config['prefer_text_type'] == 'plain') {
filter_ReplaceImagePlaceHolders($content, $attachments["html"], $config, $id, $config['image_placeholder'], true);
if ($fulldebug) {
DebugEcho("post body ReplaceImagePlaceHolders: $content");
}if ($post_excerpt) {
filter_ReplaceImagePlaceHolders($post_excerpt, $attachments["html"], $config, $id, "#eimg%#", false);
DebugEcho("excerpt: $post_excerpt");
if ($fulldebug) {
DebugEcho("post excerpt ReplaceImagePlaceHolders: $content");
}
}
//}if (trim($subject) == "") {
$subject = $config['default_title'];
DebugEcho("post parsing subject is blank using: " . $config['default_title']);
}$details = array(
'post_author' => $poster,
'comment_author' => $postAuthorDetails['author'],
'comment_author_url' => $postAuthorDetails['comment_author_url'],
'user_ID' => $postAuthorDetails['user_ID'],
'email_author' => $postAuthorDetails['email'],
'post_date' => $post_date,
'post_date_gmt' => $post_date_gmt,
'post_content' => $content,
'post_title' => $subject,
'post_type' => $post_type, /* Added by Raam Dev <[email protected]> */
'ping_status' => get_option('default_ping_status'),
'post_category' => $post_categories,
'tags_input' => $post_tags,
'comment_status' => $comment_status,
'post_name' => sanitize_title($subject),
'post_excerpt' => $post_excerpt,
'post_parent' => $Treat_as_topic_id,
'ID' => $id,
'customImages' => $customImages,
'post_status' => $post_status
);
update_post_meta( $id, 'forum_id', $Treat_as_topic_id );
return $details;
}/**
* This is the main handler for all of the processing
*/
function PostEmail($poster, $mimeDecodedEmail, $config) {
postie_disable_revisions();
extract($config);/* in order to do attachments correctly, we need to associate the
attachments with a post. So we add the post here, then update it */
$tmpPost = array('post_title' => 'tmptitle', 'post_content' => 'tmpPost', 'post_status' => 'draft');
$post_id = wp_insert_post($tmpPost, true);
if (!is_wp_error($post_id)) {
DebugEcho("tmp post id is $post_id");$is_reply = false;
$postmodifiers = new PostiePostModifiers();$details = CreatePost($poster, $mimeDecodedEmail, $post_id, $is_reply, $config, $postmodifiers);
$details = apply_filters('postie_post', $details);
$details = apply_filters('postie_post_before', $details, $mimeDecodedEmail->headers);DebugEcho(("Post postie_post filter"));
DebugDump($details);if (empty($details)) {
// It is possible that the filter has removed the post, in which case, it should not be posted.
// And if we created a placeholder post (because this was not a reply to an existing post),
// then it should be removed
if (!$is_reply) {
wp_delete_post($post_id);
EchoError("postie_post filter cleared the post, not saving.");
}
} else {
DisplayEmailPost($details);$postid = PostToDB($details, $is_reply, $custom_image_field, $postmodifiers);
if ($confirmation_email != '') {
if ($confirmation_email == 'sender') {
$recipients = array($details['email_author']);
} elseif ($confirmation_email == 'admin') {
$recipients = array(get_option("admin_email"));
} elseif ($confirmation_email == 'both') {
$recipients = array($details['email_author'], get_option("admin_email"));
}
if (null != $postid) {
MailToRecipients($mimeDecodedEmail, $recipients, false, false, $postid);
}
}
}
} else {
EchoError("PostEmail wp_insert_post failed: " . $post_id->get_error_message());
DebugDump($post_id->get_error_messages());
DebugDump($post_id->get_error_data());
}
postie_disable_revisions(true);
DebugEcho("Done");
}/** FUNCTIONS * */
/*
* Added by Raam Dev <[email protected]>
* Adds support for handling Custom Post Types by adding the
* Custom Post Type name to the email subject separated by
* $custom_post_type_delim, e.g. "Movies // My Favorite Movie"
* Also supports setting the Post Format.
*/
function tag_PostType(&$subject, $postmodifiers, $config) {$post_type = $config['post_type'];
$custom_post_type = $config['post_format'];
$separated_subject = array();
$separated_subject[0] = "";
$separated_subject[1] = $subject;$custom_post_type_delim = "https://";
if (strpos($subject, $custom_post_type_delim) !== FALSE) {
// Captures the custom post type in the subject before $custom_post_type_delim
$separated_subject = explode($custom_post_type_delim, $subject);
$custom_post_type = trim(strtolower($separated_subject[0]));
DebugEcho("post type: found possible type '$custom_post_type'");
}$known_post_types = get_post_types();
if (in_array($custom_post_type, array_map('strtolower', $known_post_types))) {
DebugEcho("post type: found type '$post_type'");
$post_type = $custom_post_type;
$subject = trim($separated_subject[1]);
} elseif (in_array($custom_post_type, array_keys(get_post_format_slugs()))) {
DebugEcho("post type: found format '$custom_post_type'");
$postmodifiers->PostFormat = $custom_post_type;
$subject = trim($separated_subject[1]);
}return $post_type;
}function filter_Linkify($text) {
DebugEcho("begin: filter_linkify");
require_once( ABSPATH . WPINC . '/class-oembed.php' );
$oe = _wp_oembed_get_object();$al = new PostieAutolink();
DebugEcho("begin: filter_linkify (html)");
$text = $al->autolink($text, $oe);
DebugEcho("begin: filter_linkify (email)");
return $al->autolink_email($text);
}function LoadDOM($text) {
return str_get_html($text, true, true, DEFAULT_TARGET_CHARSET, false);
}/* we check whether or not the email is a forwards or a redirect. If it is
* a fwd, then we glean the author details from the body of the post.
* Otherwise we get them from the headers
*/function getPostAuthorDetails(&$subject, &$content, &$mimeDecodedEmail) {
$theDate = null;
if (array_key_exists("date", $mimeDecodedEmail->headers) && !empty($mimeDecodedEmail->headers["date"])) {
$theDate = $mimeDecodedEmail->headers['date'];
}
$theEmail = '';
if (array_key_exists("from", $mimeDecodedEmail->headers) && !empty($mimeDecodedEmail->headers["from"])) {
$theEmail = RemoveExtraCharactersInEmailAddress($mimeDecodedEmail->headers["from"]);
}$regAuthor = get_user_by('email', $theEmail);
if ($regAuthor) {
$theAuthor = $regAuthor->user_login;
$theUrl = $regAuthor->user_url;
$theID = $regAuthor->ID;
} else {
$theAuthor = GetNameFromEmail($theEmail);
$theUrl = '';
$theID = '';
}// see if subject starts with Fwd:
$matches = array();
if (preg_match("/(^Fwd:) (.*)/", $subject, $matches)) {
DebugEcho("Fwd: detected");
$subject = trim($matches[2]);
if (preg_match("/\nfrom:(.*?)\n/i", $content, $matches)) {
$thFeAuthor = GetNameFromEmail($matches[1]);
$mimeDecodedEmail->headers['from'] = $theAuthor;
}
//TODO doesn't always work with HTML
if (preg_match("/\ndate:(.*?)\n/i", $content, $matches)) {
$theDate = $matches[1];
DebugEcho("date in Fwd: $theDate");
if (($timestamp = strtotime($theDate)) === false) {
DebugEcho("bad date found: $theDate");
} else {
$mimeDecodedEmail->headers['date'] = $theDate;
}
}// now get rid of forwarding info in the content
$lines = preg_split("/\r\n/", $content);
$newContents = '';
foreach ($lines as $line) {
if (preg_match("/^(from|subject|to|date):.*?/i", $line, $matches) == 0 && preg_match("/^-+\s*forwarded\s*message\s*-+/i", $line, $matches) == 0) {
$newContents.=preg_replace("/\r/", "", $line) . "\n";
}
}
$content = $newContents;
}
$theDetails = array(
'content' => "<div class='postmetadata alt'>On $theDate, $theAuthor" . " posted:</div>",
'emaildate' => $theDate,
'author' => $theAuthor,
'comment_author_url' => $theUrl,
'user_ID' => $theID,
'email' => $theEmail
);
return $theDetails;
}/* we check whether or not the email is a reply to a previously
* published post. First we check whether it starts with Re:, and then
* we see if the remainder matches an already existing post. If so,
* then we add that post id to the details array, which will cause the
* existing post to be overwritten, instead of a new one being
* generated
*/function GetParentPostForReply(&$subject) {
global $wpdb;$id = NULL;
DebugEcho("GetParentPostForReply: Looking for parent '$subject'");
// see if subject starts with Re:
$matches = array();
if (preg_match("/(^Re:)(.*)/i", $subject, $matches)) {
DebugEcho("GetParentPostForReply: Re: detected");
$subject = trim($matches[2]);
// strip out category info into temporary variable
$tmpSubject = $subject;
if (preg_match('/(.+): (.*)/', $tmpSubject, $matches)) {
$tmpSubject = trim($matches[2]);
$matches[1] = array($matches[1]);
} else if (preg_match_all('/\[(.[^\[]*)\]/', $tmpSubject, $matches)) {
$tmpSubject_matches = array();
preg_match("/](.[^\[]*)$/", $tmpSubject, $tmpSubject_matches);
$tmpSubject = trim($tmpSubject_matches[1]);
} else if (preg_match_all('/-(.[^-]*)-/', $tmpSubject, $matches)) {
preg_match("/-(.[^-]*)$/", $tmpSubject, $tmpSubject_matches);
$tmpSubject = trim($tmpSubject_matches[1]);
}
DebugEcho("GetParentPostForReply: tmpSubject: $tmpSubject");
$checkExistingPostQuery = "SELECT ID FROM $wpdb->posts WHERE post_title LIKE %s AND post_status = 'publish' AND comment_status = 'open'";
if ($id = $wpdb->get_var($wpdb->prepare($checkExistingPostQuery, $tmpSubject))) {
if (!empty($id)) {
DebugEcho("GetParentPostForReply: id: $id");
} else {
DebugEcho("GetParentPostForReply: No parent id found");
}
}
} else {
DebugEcho("GetParentPostForReply: No parent found");
}
return $id;
}function postie_ShowReadMe() {
include(POSTIE_ROOT . DIRECTORY_SEPARATOR . "postie_read_me.php");
}/**
* This sets up the configuration menu
*/
function PostieMenu() {
if (function_exists('add_options_page')) {
if (current_user_can('manage_options')) {
add_options_page("Postie", "Postie", 'manage_options', POSTIE_ROOT . "/postie.php", "ConfigurePostie");
}
}
}/**
* This handles actually showing the form. Called by WordPress
*/
function ConfigurePostie() {
include(POSTIE_ROOT . DIRECTORY_SEPARATOR . "config_form.php");
}/**
* This function handles determining the protocol and fetching the mail
* @return array
*/
function FetchMail($server = NULL, $port = NULL, $email = NULL, $password = NULL, $protocol = NULL, $offset = NULL, $test = NULL, $deleteMessages = true, $maxemails = 0, $email_tls = false, $ignoreEmailState = true) {
$emails = array();
if (!$server || !$port || !$email) {
EchoError("Missing Configuration For Mail Server");
return $emails;
}
if ($server == "pop.gmail.com") {
DebugEcho("MAKE SURE POP IS TURNED ON IN SETTING AT Gmail");
}
switch (strtolower($protocol)) {
case 'smtp': //direct
$fd = fopen("php://stdin", "r");
$input = "";
while (!feof($fd)) {
$input .= fread($fd, 1024);
}
fclose($fd);
$emails[0] = $input;
break;
case 'imap':
case 'imap-ssl':
case 'pop3-ssl':
if (!HasIMAPSupport()) {
EchoError("Sorry - you do not have IMAP php module installed - it is required for this mail setting.");
} else {
$emails = IMAPMessageFetch($server, $port, $email, $password, $protocol, $offset, $test, $deleteMessages, $maxemails, $email_tls, $ignoreEmailState);
}
break;
case 'pop3':
default:
$emails = POP3MessageFetch($server, $port, $email, $password, $protocol, $offset, $test, $deleteMessages, $maxemails);
}return $emails;
}/**
* Handles fetching messages from an imap server
*/
function IMAPMessageFetch($server = NULL, $port = NULL, $email = NULL, $password = NULL, $protocol = NULL, $offset = NULL, $test = NULL, $deleteMessages = true, $maxemails = 0, $tls = false, $ignoreMailState = true) {
require_once("postieIMAP.php");
$emails = array();
$mail_server = &PostieIMAP::Factory($protocol);
if ($tls) {
$mail_server->TLSOn();
}
DebugEcho("Connecting to $server:$port ($protocol)" . ($tls ? " with TLS" : ""));
if ($mail_server->connect(trim($server), $port, $email, $password)) {
$msg_count = $mail_server->getNumberOfMessages();
} else {
EchoError("Mail Connection Time Out");
EchoError("Common Reasons: Server Down, Network Issue, Port/Protocol MisMatch ");
EchoError("The Server said:" . $mail_server->error());
$msg_count = 0;
}// loop through messages
for ($i = 1; $i <= $msg_count; $i++) {
$emails[$i] = $mail_server->fetchEmail($i, $ignoreMailState);
if ($deleteMessages) {
$mail_server->deleteMessage($i);
}
if ($maxemails != 0 && $i >= $maxemails) {
DebugEcho("Max emails ($maxemails)");
break;
}
}
if ($deleteMessages) {
$mail_server->expungeMessages();
}
//clean up
$mail_server->disconnect();
return $emails;
}/**
* Retrieves email via POP3
*/
function POP3MessageFetch($server = NULL, $port = NULL, $email = NULL, $password = NULL, $protocol = NULL, $offset = NULL, $test = NULL, $deleteMessages = true, $maxemails = 0) {
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'class-pop3.php');$emails = array();
$pop3 = new POP3();
if (defined('POSTIE_DEBUG')) {
$pop3->DEBUG = POSTIE_DEBUG;
}DebugEcho("Connecting to $server:$port ($protocol)");
if ($pop3->connect(trim($server), $port)) {
$msg_count = $pop3->login($email, $password);
if ($msg_count === false) {
$msg_count = 0;
}
} else {
if (strpos($pop3->ERROR, "POP3: premature NOOP OK, NOT an RFC 1939 Compliant server") === false) {
EchoError("Mail Connection Time Out. Common Reasons: Server Down, Network Issue, Port/Protocol MisMatch");
}
EchoError("The Server said: $pop3->ERROR");
$msg_count = 0;
}
DebugEcho("message count: $msg_count");// loop through messages
//$msgs = $pop3->pop_list();
//DebugEcho("POP3MessageFetch: messages");
//DebugDump($msgs);for ($i = 1; $i <= $msg_count; $i++) {
$m = $pop3->get($i);
if ($m !== false) {
if (is_array($m)) {
$emails[$i] = implode('', $m);
if ($deleteMessages) {
if (!$pop3->delete($i)) {
EchoError("POP3MessageFetch: cannot delete message $i: " . $pop3->ERROR);
$pop3->reset();
exit;
}
}
} else {
DebugEcho("POP3MessageFetch: message $i not an array");
}
} else {
EchoError("POP3MessageFetch: message $i $pop3->ERROR");
}
if ($maxemails != 0 && $i >= $maxemails) {
DebugEcho("Max emails ($maxemails)");
break;
}
}
//clean up
$pop3->quit();
return $emails;
}/**
* This function handles putting the actual entry into the database
*/
function PostToDB($details, $isReply, $customImageField, $postmodifiers) {
$post_ID = 0;
if (!$isReply) {
$post_ID = wp_insert_post($details, true);
if (is_wp_error($post_ID)) {
EchoError("PostToDB Error: " . $post_ID->get_error_message());
DebugDump($post_ID->get_error_messages());
DebugDump($post_ID->get_error_data());
wp_delete_post($details['ID']);
$post_ID = null;
}
//evidently post_category was depricated at some point.
//wp_set_post_terms($post_ID, $details['post_category']);
} else {
$comment = array(
'comment_author' => $details['comment_author'],
'comment_post_ID' => $details['ID'],
'comment_author_email' => $details['email_author'],
'comment_date' => $details['post_date'],
'comment_date_gmt' => $details['post_date_gmt'],
'comment_content' => $details['post_content'],
'comment_author_url' => $details['comment_author_url'],
'comment_author_IP' => '',
'comment_approved' => 1,
'comment_agent' => '',
'comment_type' => '',
'comment_parent' => 0,
'user_id' => $details['user_ID']
);
$comment = apply_filters('postie_comment_before', $comment);
$post_ID = wp_new_comment($comment);
do_action('postie_comment_after', $comment);
}if ($post_ID) {
if ($customImageField) {
DebugEcho("Saving custom image fields");
//DebugDump($details['customImages']);if (count($details['customImages']) > 0) {
$imageField = 1;
foreach ($details['customImages'] as $image) {
add_post_meta($post_ID, 'image', $image);
DebugEcho("Saving custom image 'image$imageField'");
$imageField++;
}
}
}$postmodifiers->apply($post_ID);
do_action('postie_post_after', $details);
}
return $post_ID;
}/**
* This function determines if the mime attachment is on the BANNED_FILE_LIST
* @param string
* @return boolean
*/
function isBannedFileName($filename, $bannedFiles) {
if (empty($filename) || empty($bannedFiles)) {
return false;
}
foreach ($bannedFiles as $bannedFile) {
if (fnmatch($bannedFile, $filename)) {
EchoError("Ignoring attachment: $filename - it is on the banned files list.");
return true;
}
}
return false;
}function GetContent($part, &$attachments, $post_id, $poster, $config) {
extract($config);
//global $charset, $encoding;
DebugEcho('GetContent: ---- start');
$meta_return = '';
if (property_exists($part, "ctype_primary")) {
DebugEcho("GetContent: primary= " . $part->ctype_primary . ", secondary = " . $part->ctype_secondary);
//DebugDump($part);
}DecodeBase64Part($part);
//look for banned file names
if (property_exists($part, 'ctype_parameters') && is_array($part->ctype_parameters) && array_key_exists('name', $part->ctype_parameters)) {
if (isBannedFileName($part->ctype_parameters['name'], $config['banned_files_list'])) {
DebugEcho("GetContent: found banned filename");
return NULL;
}
}if (property_exists($part, "ctype_primary") && $part->ctype_primary == "application" && $part->ctype_secondary == "octet-stream") {
if (property_exists($part, 'disposition') && $part->disposition == "attachment") {
//nothing
} else {
DebugEcho("GetContent: decoding application/octet-stream");
$mimeDecodedEmail = DecodeMIMEMail($part->body);
filter_PreferedText($mimeDecodedEmail, $config['prefer_text_type']);
foreach ($mimeDecodedEmail->parts as $section) {
$meta_return .= GetContent($section, $attachments, $post_id, $poster, $config);
}
}
}if (property_exists($part, "ctype_primary") && $part->ctype_primary == "multipart" && $part->ctype_secondary == "appledouble") {
DebugEcho("GetContent: multipart appledouble");
$mimeDecodedEmail = DecodeMIMEMail("Content-Type: multipart/mixed; boundary=" . $part->ctype_parameters["boundary"] . "\n" . $part->body);
filter_PreferedText($mimeDecodedEmail, $config['prefer_text_type']);
filter_AppleFile($mimeDecodedEmail);
foreach ($mimeDecodedEmail->parts as $section) {
$meta_return .= GetContent($section, $attachments, $post_id, $poster, $config);
}
} else {
$filename = "";
if (property_exists($part, 'ctype_parameters') && is_array($part->ctype_parameters) && array_key_exists('name', $part->ctype_parameters)) {
$filename = $part->ctype_parameters['name'];
} elseif (property_exists($part, 'd_parameters') && is_array($part->d_parameters) && array_key_exists('filename', $part->d_parameters)) {
$filename = $part->d_parameters['filename'];
}
DebugEcho("GetContent: pre sanitize file name '$filename'");
//DebugDump($part);
$filename = sanitize_file_name($filename);
$fileext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));DebugEcho("GetContent: file name '$filename'");
DebugEcho("GetContent: extension '$fileext'");$mimetype_primary = "";
$mimetype_secondary = "";if (property_exists($part, "ctype_primary")) {
$mimetype_primary = strtolower($part->ctype_primary);
}
if (property_exists($part, "ctype_secondary")) {
$mimetype_secondary = strtolower($part->ctype_secondary);
}$typeinfo = wp_check_filetype($filename);
//DebugDump($typeinfo);
if (!empty($typeinfo['type'])) {
DebugEcho("GetContent: secondary lookup found " . $typeinfo['type']);
$mimeparts = explode('/', strtolower($typeinfo['type']));
$mimetype_primary = $mimeparts[0];
$mimetype_secondary = $mimeparts[1];
} else {
DebugEcho("GetContent: secondary lookup failed, checking configured extensions");
if (in_array($fileext, $config['audiotypes'])) {
DebugEcho("GetContent: found audio extension");
$mimetype_primary = 'audio';
$mimetype_secondary = $fileext;
} elseif (in_array($fileext, array_merge($config['video1types'], $config['video2types']))) {
DebugEcho("GetContent: found video extension");
$mimetype_primary = 'video';
$mimetype_secondary = $fileext;
} else {
DebugEcho("GetContent: found no extension");
}
}DebugEcho("GetContent: mimetype $mimetype_primary/$mimetype_secondary");
switch ($mimetype_primary) {
case 'multipart':
DebugEcho("GetContent: multipart: " . count($part->parts));
//DebugDump($part);
filter_PreferedText($part, $config['prefer_text_type']);
foreach ($part->parts as $section) {
//DebugDump($section->headers);
$meta_return .= GetContent($section, $attachments, $post_id, $poster, $config);
}
break;case 'text':
DebugEcho("GetContent: ctype_primary: text");
//DebugDump($part);$charset = "";
if (property_exists($part, 'ctype_parameters') && array_key_exists('charset', $part->ctype_parameters) && !empty($part->ctype_parameters['charset'])) {
$charset = $part->ctype_parameters['charset'];
DebugEcho("GetContent: text charset: $charset");
}$encoding = "";
if (array_key_exists('content-transfer-encoding', $part->headers) && !empty($part->headers['content-transfer-encoding'])) {
$encoding = $part->headers['content-transfer-encoding'];
DebugEcho("GetContent: text encoding: $encoding");
}if ($charset !== '' || $encoding !== '') {
//DebugDump($part);
$part->body = HandleMessageEncoding($encoding, $charset, $part->body, $config['message_encoding'], $config['message_dequote']);
if (!empty($charset)) {
$part->ctype_parameters['charset'] = ""; //reset so we don't double decode
}
//DebugDump($part);
}
if (array_key_exists('disposition', $part) && $part->disposition == 'attachment') {
DebugEcho("GetContent: text Attachement: $filename");
if (!preg_match('/ATT\d\d\d\d\d.txt/i', $filename)) {
$file_id = postie_media_handle_upload($part, $post_id, $poster, $config['generate_thumbnails']);
if (!is_wp_error($file_id)) {
$file = wp_get_attachment_url($file_id);
$icon = chooseAttachmentIcon($file, $mimetype_primary, $mimetype_secondary, $config['icon_set'], $config['icon_size']);
$attachments["html"][$filename] = "" . $icon . $filename . '' . "\n";
DebugEcho("GetContent: text attachment: adding '$filename'");
} else {
EchoError($file_id->get_error_message());
}
} else {
DebugEcho("GetContent: text attachment: skipping '$filename'");
}
} else {//go through each sub-section
if ($mimetype_secondary == 'enriched') {
//convert enriched text to HTML
DebugEcho("GetContent: enriched");
$meta_return .= filter_Etf2HTML($part->body) . "\n";
} elseif ($mimetype_secondary == 'html') {
//strip excess HTML
DebugEcho("GetContent: html");
$meta_return .= filter_CleanHtml($part->body) . "\n";
} elseif ($mimetype_secondary == 'plain') {
DebugEcho("GetContent: plain text");
//DebugDump($part);DebugEcho("GetContent: body text");
if ($config['allow_html_in_body']) {
DebugEcho("GetContent: html allowed");
$meta_return .= $part->body;
//$meta_return = "<div>$meta_return</div>\n";
} else {
DebugEcho("GetContent: html not allowed (htmlentities)");
$meta_return .= htmlentities($part->body);
}
$meta_return = filter_StripPGP($meta_return);
//DebugEcho("meta return: $meta_return");
} else {
DebugEcho("GetContent: text Attachement wo disposition: $filename");
$file_id = postie_media_handle_upload($part, $post_id, $poster);
if (!is_wp_error($file_id)) {
$file = wp_get_attachment_url($file_id);
$icon = chooseAttachmentIcon($file, $mimetype_primary, $mimetype_secondary, $config['icon_set'], $config['icon_size']);
$attachments["html"][$filename] = "" . $icon . $filename . '' . "\n";
} else {
EchoError($file_id->get_error_message());
}
}
}
break;case 'image':
DebugEcho("GetContent: image Attachement: $filename");
$file_id = postie_media_handle_upload($part, $post_id, $poster, $config['generate_thumbnails'], $mimetype_primary, $mimetype_secondary);
if (!is_wp_error($file_id)) {
$addimage = true;
//set the first image we come across as the featured image
if ($config['featured_image'] && !has_post_thumbnail($post_id)) {
DebugEcho("GetContent: featured image: $file_id");
set_post_thumbnail($post_id, $file_id);//optionally skip adding the featured imagea to the post
$addimage = $config['include_featured_image'] || $config['prefer_text_type'] == 'html';
}if ($addimage) {
DebugEcho("GetContent: adding image: $file_id");
$cid = "";
if (array_key_exists('content-id', $part->headers)) {
$cid = trim($part->headers["content-id"], "<>");
DebugEcho("GetContent: found cid: $cid");
}$attachments["html"][$filename] = parseTemplate($file_id, $mimetype_primary, $config['imagetemplate'], $filename);
if (!empty($cid)) {
$file = wp_get_attachment_url($file_id);
$attachments["cids"][$cid] = array($file, count($attachments["html"]) - 1);
DebugEcho("GetContent: CID Attachement: $cid");
}
} else {
DebugEcho("Skipping image $filename as it is the featured image");
}
} else {
EchoError("image error: " . $file_id->get_error_message());
}
break;case 'audio':
//DebugDump($part->headers);
DebugEcho("GetContent: audio Attachement: $filename");
$file_id = postie_media_handle_upload($part, $post_id, $poster, $config['generate_thumbnails']);
if (!is_wp_error($file_id)) {
$file = wp_get_attachment_url($file_id);
$cid = "";
if (array_key_exists('content-id', $part->headers)) {
$cid = trim($part->headers["content-id"], "<>");
DebugEcho("GetContent: audio Attachement cid: $cid");
}
if (in_array($fileext, $config['audiotypes'])) {
DebugEcho("GetContent: using audio template: $mimetype_secondary");
$audioTemplate = $config['audiotemplate'];
} else {
DebugEcho("GetContent: using default audio template: $mimetype_secondary");
$icon = chooseAttachmentIcon($file, $mimetype_primary, $mimetype_secondary, $config['icon_set'], $config['icon_size']);
$audioTemplate = '' . $icon . '{FILENAME}';
}
$attachments["html"][$filename] = parseTemplate($file_id, $mimetype_primary, $audioTemplate, $filename);
} else {
EchoError("audio error: " . $file_id->get_error_message());
}
break;case 'video':
DebugEcho("GetContent: video Attachement: $filename");
$file_id = postie_media_handle_upload($part, $post_id, $poster, $config['generate_thumbnails']);
if (!is_wp_error($file_id)) {
$file = wp_get_attachment_url($file_id);
$cid = "";
if (array_key_exists('content-id', $part->headers)) {
$cid = trim($part->headers["content-id"], "<>");
DebugEcho("GetContent: video Attachement cid: $cid");
}
//DebugDump($part);
if (in_array($fileext, $config['video1types'])) {
DebugEcho("GetContent: using video1 template: $fileext");
$videoTemplate = $config['video1template'];
} elseif (in_array($fileext, $config['video2types'])) {
DebugEcho("GetContent: using video2 template: $fileext");
$videoTemplate = $config['video2template'];
} else {
DebugEcho("GetContent: using default template: $fileext");
$icon = chooseAttachmentIcon($file, $mimetype_primary, $mimetype_secondary, $config['icon_set'], $config['icon_size']);
$videoTemplate = '' . $icon . '{FILENAME}';
}
$attachments["html"][$filename] = parseTemplate($file_id, $mimetype_primary, $videoTemplate, $filename);
//echo "videoTemplate = $videoTemplate\n";
} else {
EchoError($file_id->get_error_message());
}
break;default:
DebugEcho("GetContent: found file type: " . $mimetype_primary);
if (in_array($mimetype_primary, $config['supported_file_types'])) {
//pgp signature - then forget it
if ($mimetype_secondary == 'pgp-signature') {
DebugEcho("GetContent: found pgp-signature - done");
break;
}
$file_id = postie_media_handle_upload($part, $post_id, $poster, $config['generate_thumbnails']);
if (!is_wp_error($file_id)) {
$file = wp_get_attachment_url($file_id);
DebugEcho("GetContent: uploaded $file_id ($file)");
$icon = chooseAttachmentIcon($file, $mimetype_primary, $mimetype_secondary, $config['icon_set'], $config['icon_size']);
DebugEcho("GetContent: default: $icon $filename");
$attachments["html"][$filename] = parseTemplate($file_id, $mimetype_primary, $config['generaltemplate'], $filename, $icon);
if (array_key_exists('content-id', $part->headers)) {
$cid = trim($part->headers["content-id"], "<>");
if ($cid) {
$attachments["cids"][$cid] = array($file, count($attachments["html"]) - 1);
}
} else {
DebugEcho("GetContent: No content-id");
}
} else {
EchoError($file_id->get_error_message());
}
} else {
EchoError("$filename has an unsupported MIME type $mimetype_primary and was not added.");
DebugEcho("GetContent: Not in supported filetype list: '$mimetype_primary'");
DebugDump($config['supported_file_types']);
}
break;
}
}
DebugEcho("GetContent: meta_return: " . substr($meta_return, 0, 500));
DebugEcho("GetContent: ==== end");
return $meta_return;
}function filter_Ubb2HTML(&$text) {
// Array of tags with opening and closing
$tagArray['img'] = array('open' => '<img src="', 'close' => '">');
$tagArray['b'] = array('open' => '<b>', 'close' => '</b>');
$tagArray['i'] = array('open' => '<i>', 'close' => '</i>');
$tagArray['u'] = array('open' => '<u>', 'close' => '</u>');
$tagArray['url'] = array('open' => ' '">\\1');
$tagArray['email'] = array('open' => ' '">\\1');
$tagArray['url=(.*)'] = array('open' => ' '">\\2');
$tagArray['email=(.*)'] = array('open' => ' '">\\2');
$tagArray['color=(.*)'] = array('open' => '<font color="', 'close' => '">\\2</font>');
$tagArray['size=(.*)'] = array('open' => '<font size="', 'close' => '">\\2</font>');
$tagArray['font=(.*)'] = array('open' => '<font face="', 'close' => '">\\2</font>');
// Array of tags with only one part
$sTagArray['br'] = array('tag' => '
');
$sTagArray['hr'] = array('tag' => '<hr>');foreach ($tagArray as $tagName => $replace) {
$tagEnd = preg_replace('/\W/Ui', '', $tagName);
$text = preg_replace("|\[$tagName\](.*)\[/$tagEnd\]|Ui", "$replace[open]\\1$replace[close]", $text);
}
foreach ($sTagArray as $tagName => $replace) {
$text = preg_replace("|\[$tagName\]|Ui", "$replace[tag]", $text);
}
return $text;
}// This function turns Enriched Text into something similar to HTML
// Very basic at the moment, only supports some functionality and dumps the rest
// FIXME: fix colours: <color><param>FFFF,C2FE,0374</param>some text </color>
function filter_Etf2HTML($content) {$search = array(
'/<bold>/',
'/<\/bold>/',
'/<underline>/',
'/<\/underline>/',
'/<italic>/',
'/<\/italic>/',
'/<fontfamily><param>.*<\/param>/',
'/<\/fontfamily>/',
'/<x-tad-bigger>/',
'/<\/x-tad-bigger>/',
'/<bigger>/',
'</bigger>/',
'/<color>/',
'/<\/color>/',
'/<param>.+<\/param>/'
);$replace = array(
'<b>',
'</b>',
'<u>',
'</u>',
'<i>',
'</i>',
'',
'',
'',
'',
'',
'',
'',
'',
''
);
// strip extra line breaks
$content = preg_replace($search, $replace, $content);
return trim($content);
}// This function cleans up HTML in the email
function filter_CleanHtml($content) {
$html = str_get_html($content);
if ($html) {
DebugEcho("filter_CleanHtml: Looking for invalid tags");
foreach ($html->find('script, style, head') as $node) {
DebugEcho("filter_CleanHtml: Removing: " . $node->outertext);
$node->outertext = '';
}
DebugEcho("filter_CleanHtml: " . $html->save());$html->load($html->save());
$b = $html->find('body');
if ($b) {
DebugEcho("filter_CleanHtml: replacing body with div");
$content = "<div>" . $b[0]->innertext . "</div>\n";
}
} else {
DebugEcho("filter_CleanHtml: No HTML found");
}
return $content;
}/**
* Determines if the sender is a valid user.
* @return integer|NULL
*/
function ValidatePoster(&$mimeDecodedEmail, $config) {
extract($config);
$poster = NULL;
$from = "";
if (property_exists($mimeDecodedEmail, "headers") && array_key_exists('from', $mimeDecodedEmail->headers)) {
$from = RemoveExtraCharactersInEmailAddress(trim($mimeDecodedEmail->headers["from"]));
$from = apply_filters("postie_filter_email", $from);
DebugEcho("ValidatePoster: post postie_filter_email $from");$toEmail = '';
if (isset($mimeDecodedEmail->headers["to"])) {
$toEmail = RemoveExtraCharactersInEmailAddress(trim($mimeDecodedEmail->headers["to"]));
}$replytoEmail = '';
if (isset($mimeDecodedEmail->headers["reply-to"])) {
$replytoEmail = RemoveExtraCharactersInEmailAddress(trim($mimeDecodedEmail->headers["reply-to"]));
}$from = apply_filters("postie_filter_email2", $from, $toEmail, $replytoEmail);
DebugEcho("ValidatePoster: post postie_filter_email2 $from");
} else {
DebugEcho("No 'from' header found");
DebugDump($mimeDecodedEmail->headers);
}if (property_exists($mimeDecodedEmail, "headers")) {
$from = apply_filters("postie_filter_email3", $from, $mimeDecodedEmail->headers);
DebugEcho("ValidatePoster: post postie_filter_email3 $from");
}$resentFrom = "";
if (property_exists($mimeDecodedEmail, "headers") && array_key_exists('resent-from', $mimeDecodedEmail->headers)) {
$resentFrom = RemoveExtraCharactersInEmailAddress(trim($mimeDecodedEmail->headers["resent-from"]));
}//See if the email address is one of the special authorized ones
if (!empty($from)) {
DebugEcho("Confirming Access For $from ");
$user = get_user_by('email', $from);
if ($user !== false) {
$user_ID = $user->ID;
}
} else {
$user_ID = "";
}
if (!empty($user_ID)) {
$user = new WP_User($user_ID);
if ($user->has_cap("post_via_postie")) {
DebugEcho("$user_ID has 'post_via_postie' permissions");
$poster = $user_ID;DebugEcho("ValidatePoster: pre postie_author $poster");
$poster = apply_filters("postie_author", $poster);
DebugEcho("ValidatePoster: post postie_author $poster");
} else {
DebugEcho("$user_ID does not have 'post_via_postie' permissions");
$user_ID = "";
}
}
if (empty($user_ID) && ($turn_authorization_off || isEmailAddressAuthorized($from, $authorized_addresses) || isEmailAddressAuthorized($resentFrom, $authorized_addresses))) {
DebugEcho("ValidatePoster: looking up default user $admin_username");
$user = get_user_by('login', $admin_username);
if ($user === false) {
EchoError("Your 'Default Poster' setting '$admin_username' is not a valid WordPress user (2)");
$poster = 1;
} else {
$poster = $user->ID;
DebugEcho("ValidatePoster: pre postie_author (default) $poster");
$poster = apply_filters("postie_author", $poster);
DebugEcho("ValidatePoster: post postie_author (default) $poster");
}
DebugEcho("ValidatePoster: found user '$
- The topic ‘postie with topic post_type using bbpress’ is closed to new replies.