/**
  * Webhook parser class method for SendGrid.
  */
 public function webhook_parser()
 {
     if (empty($_SERVER['HTTP_USER_AGENT']) || !empty($_SERVER['HTTP_USER_AGENT']) && 0 !== strpos($_SERVER['HTTP_USER_AGENT'], 'SendGrid')) {
         return;
     }
     if (empty($_POST) || empty($_POST['headers'])) {
         return;
     }
     bp_rbe_log('- SendGrid webhook received -');
     // Format email headers to fit RBE spec.
     $temp = explode("\n", $_POST['headers']);
     $headers = array();
     foreach ($temp as $line) {
         $colun = strpos($line, ':');
         if (false === $colun) {
             continue;
         }
         $key = substr($line, 0, $colun);
         $headers[$key] = stripslashes(trim(substr($line, $colun + 1)));
     }
     $data = array('headers' => $headers, 'to_email' => BP_Reply_By_Email_Parser::get_header($headers, 'To'), 'from_email' => BP_Reply_By_Email_Parser::get_header($headers, 'From'), 'content' => $_POST['text'], 'subject' => $_POST['subject']);
     $parser = BP_Reply_By_Email_Parser::init($data, 1);
     if (is_wp_error($parser)) {
         do_action('bp_rbe_no_match', $parser, $data, 1, false);
     }
     bp_rbe_log('- Webhook parsing completed -');
     die;
 }
 /**
  * Webhook parser class method for Mandrill.
  */
 public function webhook_parser()
 {
     if (empty($_SERVER['CONTENT_TYPE']) || !empty($_SERVER['CONTENT_TYPE']) && 'application/json' !== $_SERVER['CONTENT_TYPE']) {
         return;
     }
     if (!empty($_SERVER['HTTP_USER_AGENT']) && 'Postmark' !== $_SERVER['HTTP_USER_AGENT']) {
         return;
     }
     bp_rbe_log('- Postmark webhook received -');
     $response = file_get_contents('php://input');
     if (empty($response)) {
         bp_rbe_log('- Postmark webhook response failed -');
     }
     $response = json_decode($response);
     // Format email headers to fit RBE spec.
     $headers = array();
     foreach ($response->Headers as $header) {
         $headers[$header->Name] = $header->Value;
     }
     // Postmark separates parsed email headers; add them back for RBE parsing.
     $headers['From'] = $response->From;
     $headers['To'] = $response->To;
     $data = array('headers' => $headers, 'to_email' => $response->To, 'from_email' => $response->From, 'content' => $response->TextBody, 'subject' => $response->Subject);
     $parser = BP_Reply_By_Email_Parser::init($data, 1);
     if (is_wp_error($parser)) {
         do_action('bp_rbe_no_match', $parser, $data, 1, false);
     }
     bp_rbe_log('- Webhook parsing completed -');
     die;
 }
 /**
  * Webhook parser class method for SparkPost.
  */
 public function webhook_parser()
 {
     if (empty($_SERVER['CONTENT_TYPE']) || !empty($_SERVER['CONTENT_TYPE']) && 'application/json' !== $_SERVER['CONTENT_TYPE']) {
         return;
     }
     if (false === isset($_SERVER['HTTP_X_MESSAGESYSTEMS_WEBHOOK_TOKEN'])) {
         return;
     }
     bp_rbe_log('- SparkPost webhook received -');
     // SparkPost auth token verification.
     if (defined('BP_RBE_SPARKPOST_WEBHOOK_TOKEN') && !empty($_SERVER['HTTP_X_MESSAGESYSTEMS_WEBHOOK_TOKEN'])) {
         // Make sure auth token matches; if it doesn't, bail!
         if (constant('BP_RBE_SPARKPOST_WEBHOOK_TOKEN') !== $_SERVER['HTTP_X_MESSAGESYSTEMS_WEBHOOK_TOKEN']) {
             bp_rbe_log('SparkPost token verification failed.');
             die;
         }
     }
     $response = file_get_contents('php://input');
     if (empty($response)) {
         bp_rbe_log('- SporkPost webhook response failed -');
     }
     $response = json_decode($response);
     $i = 1;
     foreach ($response as $item) {
         // Format email headers to fit RBE spec.
         $headers = array();
         foreach ($item->msys->relay_message->content->headers as $header) {
             $headers = array_merge($headers, (array) $header);
         }
         $data = array('headers' => $headers, 'to_email' => $item->msys->relay_message->rcpt_to, 'from_email' => $item->msys->relay_message->friendly_from, 'content' => $item->msys->relay_message->content->text, 'subject' => $item->msys->relay_message->content->subject);
         $parser = BP_Reply_By_Email_Parser::init($data, $i);
         if (is_wp_error($parser)) {
             do_action('bp_rbe_no_match', $parser, $data, $i, false);
         }
         ++$i;
     }
     bp_rbe_log('- Webhook parsing completed -');
     die;
 }
/**
 * Logs no match errors during RBE parsing.
 *
 * Also sends a failure message back to the original sender for feedback
 * purposes if enabled.
 *
 * @since 1.0-RC3
 *
 * @uses bp_rbe_log() Logs error messages in a custom log
 * @param object $parser The WP_Error object.
 * @param array $data {
 *     An array of arguments.
 *
 *     @type array $headers Email headers.
 *     @type string $to_email The 'To' email address.
 *     @type string $from_email The 'From' email address.
 *     @type string $content The email body content.
 *     @type string $subject The email subject line.
 *     @type bool $is_html Whether the email content is HTML or not.
 * }
 * @param int $i The current message number
 * @param resource|bool $imap The IMAP connection if passed. Boolean false if not.
 */
function bp_rbe_log_no_matches($parser, $data, $i, $imap)
{
    $log = $message = false;
    $type = is_wp_error($parser) ? $parser->get_error_code() : false;
    // log messages based on the type
    switch ($type) {
        /** RBE **********************************************************/
        case 'no_address_tag':
            $log = __('error - no address tag could be found', 'bp-rbe');
            break;
        case 'no_user_id':
            $log = __('error - no user ID could be found', 'bp-rbe');
            $sitename = wp_specialchars_decode(get_blog_option(bp_get_root_blog_id(), 'blogname'), ENT_QUOTES);
            $message = sprintf(__('Hi there,

You tried to use the email address - %s - to reply by email.  Unfortunately, we could not find this email address in our system.

This can happen in a couple of different ways:
* You have configured your email client to reply with a custom "From:" email address.
* You read email addressed to more than one account inside of a single Inbox.

Make sure that, when replying by email, your "From:" email address is the same as the address you\'ve registered at %s.

If you have any questions, please let us know.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_header($data['headers'], 'From'), $sitename);
            break;
        case 'user_is_spammer':
            $log = __('notice - user is marked as a spammer.  reply not posted!', 'bp-rbe');
            break;
        case 'no_params':
            $log = __('error - no parameters were found', 'bp-rbe');
            break;
        case 'no_reply_body':
            $log = __('error - body message for reply was empty', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your reply could not be posted because we could not find the "%s" marker in the body of your email.

In the future, please make sure you reply *above* this line for your comment to be posted on the site.

For reference, your entire reply was:

"%s".

If you have any questions, please let us know.', 'bp-rbe'), bp_rbe_get_marker(), $data['content']);
            break;
            /** ACTIVITY *****************************************************/
        /** ACTIVITY *****************************************************/
        case 'root_activity_deleted':
            $log = __('error - root activity update was deleted before this could be posted', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your reply:

"%s"

Could not be posted because the activity entry you were replying to no longer exists.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
        case 'root_or_parent_activity_deleted':
            $log = __('error - root or parent activity update was deleted before this could be posted', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your reply:

"%s"

Could not be posted because the activity entry you were replying to no longer exists.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
            /** GROUP FORUMS *************************************************/
        /** GROUP FORUMS *************************************************/
        case 'user_not_group_member':
            $log = __('error - user is not a member of the group. forum reply not posted.', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your forum reply:

"%s"

Could not be posted because you are no longer a member of this group.  To comment on the forum thread, please rejoin the group.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
        case 'user_banned_from_group':
            $log = __('notice - user is banned from group. forum reply not posted.', 'bp-rbe');
            break;
        case 'new_forum_topic_empty':
            $log = __('error - body message for new forum topic was empty', 'bp-rbe');
            $message = __('Hi there,

We could not post your new forum topic by email because we could not find any text in the body of the email.

In the future, please make sure to type something in your email! :)

If you have any questions, please let us know.', 'bp-rbe');
            break;
        case 'forum_reply_exists':
            $log = __('error - forum reply already exists in topic', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your forum reply:

"%s"

Could not be posted because you have already posted the same message in the forum topic you were attempting to reply to.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
        case 'forum_reply_fail':
            $log = __('error - forum topic was deleted before reply could be posted', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your forum reply:

"%s"

Could not be posted because the forum topic you were replying to no longer exists.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
        case 'forum_topic_fail':
            $log = __('error - forum topic failed to be created', 'bp-rbe');
            // this is a pretty generic message...
            $message = sprintf(__('Hi there,

Your forum topic titled "%s" could not be posted due to an error.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), $data['subject']);
            break;
            /** PRIVATE MESSAGES *********************************************/
            // most likely a spammer trying to infiltrate an existing PM thread
        /** PRIVATE MESSAGES *********************************************/
        // most likely a spammer trying to infiltrate an existing PM thread
        case 'private_message_not_in_thread':
            $log = __('error - user is not a part of the existing PM conversation', 'bp-rbe');
            break;
        case 'private_message_thread_deleted':
            $log = __('error - private message thread was deleted by all parties before this could be posted', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your private message reply:

"%s"

Could not be posted because the private message thread you were replying to no longer exists.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
        case 'private_message_fail':
            $log = __('error - private message failed to post', 'bp-rbe');
            $message = sprintf(__('Hi there,

Your reply:

"%s"

Could not be posted due to an error.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
            break;
            // 3rd-party plugins can filter the two variables below to add their own logs and email messages.
        // 3rd-party plugins can filter the two variables below to add their own logs and email messages.
        default:
            $log = apply_filters('bp_rbe_extend_log_no_match', $log, $type, $data, $i, $imap);
            $message = apply_filters('bp_rbe_extend_log_no_match_email_message', $message, $type, $data, $i, $imap);
            break;
    }
    // internal logging
    if ($log) {
        bp_rbe_log(sprintf(__('Message #%d: %s', 'bp-rbe'), $i, $log));
    }
    // failure message to author
    // if you want to turn off failure messages, use the filter below
    if (apply_filters('bp_rbe_enable_failure_message', true) && $message) {
        $to = BP_Reply_By_Email_Parser::get_header($data['headers'], 'From');
        if (!empty($to)) {
            $sitename = wp_specialchars_decode(get_blog_option(bp_get_root_blog_id(), 'blogname'), ENT_QUOTES);
            $subject = sprintf(__('[%s] Your Reply By Email message could not be posted', 'bp-rbe'), $sitename);
            // temporarily remove RBE mail filter by wiping out email querystring
            add_filter('bp_rbe_querystring', '__return_false');
            // send email
            wp_mail($to, $subject, $message);
            // add it back
            remove_filter('bp_rbe_querystring', '__return_false');
        }
    }
}
    /**
     * Setup our extension's failure message to send back to the sender.
     *
     * @param mixed $message
     * @param string $type Type of error message
     * @param array $data {
     *     An array of arguments.
     *
     *     @type array $headers Email headers.
     *     @type string $content The email body content.
     *     @type string $subject The email subject line.
     *     @type int $user_id The user ID who sent the email.
     *     @type bool $is_html Whether the email content is HTML or not.
     *     @type int $i The email message number.
     * }
     * @param int $i The message number from the inbox loop
     * @param resource $connection The current IMAP connection. Chances are you probably don't have to do anything with this!
     * @return string|bool Could be a string or boolean false.
     */
    public function failure_message_to_sender($message, $type, $data, $i, $imap)
    {
        switch ($type) {
            case 'bp_doc_parent_comment_deleted':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted because the parent comment you were replying to no longer exists.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bp_doc_parent_comment_spam':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted because the parent comment you were replying to was marked as spam.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bp_doc_parent_comment_unapproved':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted because the parent comment you were replying was unapproved.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bp_doc_comment_change_to_noone':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted because the comment setting for this group document recently changed to "No One".
This means that no other comments can be posted for the group document in question.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bp_doc_user_not_admin_mod':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted because the comment setting for this group document recently changed to "Admin and moderators only".
Since you are not a group administrator or a group moderator, this means your comment could be posted.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bp_doc_user_not_member':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted because you are no longer a member of this group.  To comment on this group document, please rejoin the group.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bp_doc_new_comment_fail':
                $message = sprintf(__('Hi there,

Your comment to the group document:

"%s"

Could not be posted due to an error.

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
        }
        return $message;
    }
    /**
     * Setup our extension's failure message to send back to the sender.
     *
     * @param mixed $message
     * @param string $type Type of error message
     * @param array $data {
     *     An array of arguments.
     *
     *     @type array $headers Email headers.
     *     @type string $content The email body content.
     *     @type string $subject The email subject line.
     *     @type int $user_id The user ID who sent the email.
     *     @type bool $is_html Whether the email content is HTML or not.
     *     @type int $i The email message number.
     * }
     * @param int $i The message number from the inbox loop
     * @param resource $connection The current IMAP connection. Chances are you probably don't have to do anything with this!
     * @return string|bool Could be a string or boolean false.
     */
    public function failure_message_to_sender($message, $type, $data, $i, $imap)
    {
        switch ($type) {
            /** REPLIES *****************************************************/
            case 'bbp_reply_permissions':
                $message = sprintf(__('Hi there,

Unfortunately, your reply to the forum topic could not be posted because it appears that you do not have the ability to post replies.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bbp_reply_flood':
                $message = sprintf(__('Hi there,

Unfortunately, your reply to the forum topic could not be posted because it appears that you are trying to post too often.  Please wait a few minutes and try again.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bbp_reply_duplicate':
                $message = sprintf(__('Hi there,

Unfortunately, your reply to the forum topic could not be posted because it appears you have already made the same reply.

Here is a copy of your reply:

"%s"

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bbp_reply_blacklist':
                $message = sprintf(__('Hi there,

Unfortunately, your reply to the forum topic could not be posted because the content of your message was automatically marked as spam.

Here is a copy of your reply that was marked as spam:

"%s"

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
            case 'bbp_reply_error':
                $message = sprintf(__('Hi there,

Unfortunately, your reply to the forum topic could not be posted due to an error.

Here is a copy of your attempted reply:

"%s"

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], true, $i));
                break;
                /** TOPICS *****************************************************/
            /** TOPICS *****************************************************/
            case 'bbp_topic_permissions':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because it appears that you do have the ability to post topics.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_edit_topic_forum_category':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because the forum you are attempting to post in is a forum category.  Forum categories cannot contain topics.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_edit_topic_forum_closed':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because the forum you are trying to post in is closed and no new topics can be created there.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_edit_topic_forum_private':
            case 'bbp_edit_topic_forum_hidden':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because it appears that you do not have access to that forum.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_topic_flood':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because it appears that you are trying to post too often.  Please wait a few minutes and try again.

We are sorry for the inconvenience, but you will need to repost the following message:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_topic_duplicate':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because it appears you already created this topic before.

Here is a copy of your attempted topic:

"%s"', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_topic_blacklist':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted because the content of your message was automatically marked as spam.

Here is a copy of your topic that was marked as spam:

"%s"

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
            case 'bbp_topic_error':
                $message = sprintf(__('Hi there,

Unfortunately, your new forum topic could not be posted due to an error.

Here is a copy of your attempted topic:

"%s"

We apologize for any inconvenience this may have caused.', 'bp-rbe'), BP_Reply_By_Email_Parser::get_body($data['content'], $data['is_html'], false, $i));
                break;
        }
        return $message;
    }
 /**
  * Clears static properties after reaching the end of parsing.
  *
  * This is to prevent any lingering properties when used in a loop.
  */
 protected static function clear_properties()
 {
     self::$headers = array();
     self::$querystring = '';
     self::$user = false;
     self::$content = '';
     self::$subject = '';
     self::$is_html = false;
 }
 /**
  * Webhook parser class method for Mandrill.
  */
 public function webhook_parser()
 {
     if (empty($_SERVER['HTTP_X_MANDRILL_SIGNATURE'])) {
         return;
     }
     if (!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Mandrill-Webhook/') === false) {
         return;
     }
     if (empty($_POST) || empty($_POST['mandrill_events'])) {
         return;
     }
     bp_rbe_log('- Mandrill webhook received -');
     // mandrill signature verification
     if (defined('BP_RBE_MANDRILL_WEBHOOK_URL') && defined('BP_RBE_MANDRILL_WEBHOOK_KEY')) {
         $signed_data = constant('BP_RBE_MANDRILL_WEBHOOK_URL');
         $signed_data .= 'mandrill_events';
         $signed_data .= stripslashes($_POST['mandrill_events']);
         $webhook_key = constant('BP_RBE_MANDRILL_WEBHOOK_KEY');
         $signature = base64_encode(hash_hmac('sha1', $signed_data, $webhook_key, true));
         // check if generated signature matches Mandrill's
         if ($signature !== $_SERVER['HTTP_X_MANDRILL_SIGNATURE']) {
             bp_rbe_log('Mandrill signature verification failed.');
             die;
         }
     }
     // get parsed content
     $response = json_decode(stripslashes($_POST['mandrill_events']));
     // log JSON errors if present
     if (json_last_error() != JSON_ERROR_NONE) {
         switch (json_last_error()) {
             case JSON_ERROR_DEPTH:
                 bp_rbe_log('json error: - Maximum stack depth exceeded');
                 break;
             case JSON_ERROR_STATE_MISMATCH:
                 bp_rbe_log('json error: - Underflow or the modes mismatch');
                 break;
             case JSON_ERROR_CTRL_CHAR:
                 bp_rbe_log('json error: - Unexpected control character found');
                 break;
             case JSON_ERROR_SYNTAX:
                 bp_rbe_log('json error: - Syntax error, malformed JSON');
                 break;
             case JSON_ERROR_UTF8:
                 bp_rbe_log('json error: - Malformed UTF-8 characters, possibly incorrectly encoded');
                 break;
             default:
                 bp_rbe_log('json error: - Unknown error');
                 break;
         }
         die;
         // ready to start the parsing!
     } else {
         $i = 1;
         foreach ($response as $item) {
             $data = array('headers' => $item->msg->headers, 'to_email' => $item->msg->email, 'from_email' => $item->msg->from_email, 'content' => $item->msg->text, 'subject' => $item->msg->subject);
             $parser = BP_Reply_By_Email_Parser::init($data, $i);
             if (is_wp_error($parser)) {
                 do_action('bp_rbe_no_match', $parser, $data, $i, false);
             }
             ++$i;
         }
         bp_rbe_log('- Webhook parsing completed -');
         die;
     }
 }
 /**
  * The main method we use to parse an IMAP inbox.
  */
 public function run()
 {
     // $instance must be initialized before we go on!
     if (self::$instance === false) {
         return false;
     }
     // If safe mode isn't on, then let's set the execution time to unlimited
     if (!ini_get('safe_mode')) {
         set_time_limit(0);
     }
     // Try to connect
     $connect = $this->connect();
     if (!$connect) {
         return false;
     }
     // Total duration we should keep the IMAP stream alive for in seconds
     $duration = bp_rbe_get_execution_time();
     bp_rbe_log('--- Keep alive for ' . $duration / 60 . ' minutes ---');
     bp_rbe_remove_imap_lock();
     // Mark the current timestamp, mark the future time when we should close the IMAP connection;
     // Do our parsing until $future > $now; re-mark the timestamp at end of loop... rinse and repeat!
     for ($now = time(), $future = time() + $duration; $future > $now; $now = time()) {
         // Get number of messages
         $message_count = imap_num_msg($this->connection);
         // If there are messages in the inbox, let's start parsing!
         if ($message_count != 0) {
             // According to this:
             // http://www.php.net/manual/pl/function.imap-headerinfo.php#95012
             // This speeds up rendering the email headers... could be wrong
             imap_headers($this->connection);
             bp_rbe_log('- Checking inbox -');
             // Loop through each email message
             for ($i = 1; $i <= $message_count; ++$i) {
                 // flush object cache if necessary
                 //
                 // we only flush the cache if the default object cache is in use
                 // why? b/c the default object cache is only meant for single page loads and
                 // since RBE runs in the background, we need to flush the object cache so WP
                 // will do a direct DB query for the next data fetch
                 if (!wp_using_ext_object_cache()) {
                     wp_cache_flush();
                 }
                 self::$html = false;
                 $content = self::body_parser($this->connection, $i);
                 $headers = $this->get_mail_headers($this->connection, $i);
                 $data = array('headers' => $headers, 'to_email' => BP_Reply_By_Email_Parser::get_header($headers, 'To'), 'from_email' => BP_Reply_By_Email_Parser::get_header($headers, 'From'), 'content' => $content, 'is_html' => self::$html, 'subject' => imap_utf8(BP_Reply_By_Email_Parser::get_header($headers, 'Subject')));
                 $parser = BP_Reply_By_Email_Parser::init($data, $i);
                 if (is_wp_error($parser)) {
                     //do_action( 'bp_rbe_imap_no_match', $this->connection, $i, $headers, $parser->get_error_code() );
                     do_action('bp_rbe_no_match', $parser, $data, $i, $this->connection);
                 }
                 // do something during the loop
                 // we mark the message for deletion here via this hook
                 do_action('bp_rbe_imap_loop', $this->connection, $i);
                 // unset some variables at the end of the loop
                 unset($content, $headers, $data, $parser);
             }
             // do something after the loop
             do_action('bp_rbe_imap_after_loop', $this->connection);
         }
         // stop the loop if necessary
         if (bp_rbe_should_stop()) {
             if ($this->close()) {
                 bp_rbe_log('--- Manual termination of connection confirmed! Kaching! ---');
             } else {
                 bp_rbe_log('--- Error - invalid connection during manual termination ---');
             }
             remove_action('shutdown', 'bp_rbe_spawn_inbox_check');
             exit;
         }
         // Give IMAP server a break
         sleep(10);
         // If the IMAP connection is down, reconnect
         if (!imap_ping($this->connection)) {
             bp_rbe_log('-- IMAP connection is down, attempting to reconnect... --');
             if (bp_rbe_is_connecting(array('clearcache' => true))) {
                 bp_rbe_log('--- RBE is already attempting to connect - stopping connection attempt ---');
                 continue;
             }
             // add lock marker before connecting
             bp_rbe_add_imap_lock();
             // attempt to reconnect
             $reopen = BP_Reply_By_Email_Connect::init(array('reconnect' => true), $this->connection);
             if ($reopen) {
                 bp_rbe_log('-- Reconnection successful! --');
             } else {
                 bp_rbe_log('-- Reconnection failed! :( --');
                 bp_rbe_log('Cannot connect: ' . imap_last_error());
                 // cleanup RBE after failure
                 bp_rbe_cleanup();
                 remove_action('shutdown', 'bp_rbe_spawn_inbox_check');
                 exit;
             }
         }
         // Unset some variables to clear some memory
         unset($message_count);
     }
     if ($this->close()) {
         bp_rbe_log('--- Closing current connection automatically ---');
     } else {
         bp_rbe_log('--- Invalid connection during close time ---');
     }
     // autoconnect is off
     if (1 !== (int) bp_rbe_get_setting('keepaliveauto', array('refetch' => true))) {
         remove_action('shutdown', 'bp_rbe_spawn_inbox_check');
         // sleep a bit before autoconnecting again
     } else {
         sleep(5);
     }
     exit;
 }