<?php

if (!isset($shub_account_id) || !isset($shub_message_id)) {
    exit;
}
if ($shub_account_id && $shub_message_id) {
    $envato = new shub_envato_account($shub_account_id);
    if ($shub_account_id && $envato->get('shub_account_id') == $shub_account_id) {
        $envato_message = new shub_message($envato, false, $shub_message_id);
        $envato_message->output_message_page('popup');
    }
}
if ($shub_account_id && !(int) $shub_message_id) {
    $envato = new shub_envato_account($shub_account_id);
    if ($shub_account_id && $envato->get('shub_account_id') == $shub_account_id) {
        /* @var $groups shub_item[] */
        $groups = $envato->get('groups');
        //print_r($groups);
        ?>
	    <form action="" method="post" enctype="multipart/form-data">
		    <input type="hidden" name="_process" value="send_envato_message">
			<?php 
        wp_nonce_field('send-envato' . (int) $envato->get('shub_account_id'));
        ?>
		    <?php 
        $fieldset_data = array('heading' => array('type' => 'h3', 'title' => 'Compose message'), 'class' => 'tableclass tableclass_form tableclass_full', 'elements' => array('item' => array('title' => __('envato Group', 'support_hub'), 'fields' => array()), 'message' => array('title' => __('message', 'support_hub'), 'field' => array('type' => 'textarea', 'name' => 'message', 'id' => 'envato_compose_message', 'value' => '')), 'type' => array('title' => __('Type', 'support_hub'), 'fields' => array('<input type="radio" name="post_type" id="post_type_wall" value="wall" checked> ', '<label for="post_type_wall">', __('Wall Post', 'support_hub'), '</label>', '<input type="radio" name="post_type" id="post_type_link" value="link"> ', '<label for="post_type_link">', __('Link Post', 'support_hub'), '</label>', '<input type="radio" name="post_type" id="post_type_picture" value="picture"> ', '<label for="post_type_picture">', __('Picture Post', 'support_hub'), '</label>')), 'link' => array('title' => __('Link', 'support_hub'), 'fields' => array(array('type' => 'text', 'name' => 'link', 'id' => 'message_link_url', 'value' => ''), '<div id="envato_link_loading_message"></div>', '<span class="envato-type-link envato-type-option"></span>')), 'link_picture' => array('title' => __('Link Picture', 'support_hub'), 'fields' => array(array('type' => 'text', 'name' => 'link_picture', 'value' => ''), 'Full URL (eg: http://) to the picture to use for this link preview', '<span class="envato-type-link envato-type-option"></span>')), 'link_name' => array('title' => __('Link Title', 'support_hub'), 'fields' => array(array('type' => 'text', 'name' => 'link_name', 'value' => ''), 'Title to use instead of the automatically generated one from the Link page', '<span class="envato-type-link envato-type-option"></span>')), 'link_caption' => array('title' => __('Link Caption', 'support_hub'), 'fields' => array(array('type' => 'text', 'name' => 'link_caption', 'value' => ''), 'Caption to use instead of the automatically generated one from the Link page', '<span class="envato-type-link envato-type-option"></span>')), 'link_description' => array('title' => __('Link Description', 'support_hub'), 'fields' => array(array('type' => 'text', 'name' => 'link_description', 'value' => ''), 'Description to use instead of the automatically generated one from the Link page', '<span class="envato-type-link envato-type-option"></span>')), 'picture' => array('title' => __('Picture', 'support_hub'), 'fields' => array('<input type="file" name="picture" value="">', '<span class="envato-type-picture envato-type-option"></span>')), 'schedule' => array('title' => __('Schedule', 'support_hub'), 'fields' => array(array('type' => 'date', 'name' => 'schedule_date', 'value' => ''), array('type' => 'time', 'name' => 'schedule_time', 'value' => ''), ' ', sprintf(__('Currently: %s', 'support_hub'), date('c')), ' (Leave blank to send now, or pick a date in the future.)')), 'debug' => array('title' => __('Debug', 'support_hub'), 'field' => array('type' => 'check', 'name' => 'debug', 'value' => '1', 'checked' => false, 'help' => 'Show debug output while posting the message'))));
        foreach ($groups as $item_id => $group) {
            $fieldset_data['elements']['item']['fields'][] = '<div id="envato_compose_group_select">' . '<input type="checkbox" name="compose_group_id[' . $item_id . ']" value="1" checked> ' . '<img src="//graph.envato.com/' . $item_id . '/picture"> ' . htmlspecialchars($group->get('item_name')) . '</div>';
        }
        echo shub_module_form::generate_fieldset($fieldset_data);
        ?>
    public function load_latest_item_data($debug = false)
    {
        // serialise this result into envato_data.
        if (!$this->account) {
            echo 'No envato account linked, please try again';
            return;
        }
        $api = $this->account->get_api();
        $network_key = $this->get('network_key');
        if (!$network_key) {
            echo 'No envato item id found';
            return;
        }
        // we keep a record of the last message received so we know where to stop checking the feed
        $last_message_received = (int) $this->get('last_message');
        if ($debug) {
            echo "Getting the latest 60 comments for item: " . $network_key . " (last message in database is from " . shub_print_date($last_message_received, true) . ")<br>\n";
        }
        $newest_message_received = 0;
        $endpoint = 'v1/discovery/search/search/comment?term=&item_id=' . $network_key . '&sort_by=newest&page_size=60';
        $api_result = $api->api($endpoint);
        if ($debug) {
            echo "API Result took :" . $api_result['took'] . ' seconds and produced ' . count($api_result['matches']) . ' results';
        }
        $count = 0;
        if (isset($api_result['matches']) && is_array($api_result['matches'])) {
            //foreach($api_result['matches'] as $item_message){
            while ($api_result['matches']) {
                $item_message = array_pop($api_result['matches']);
                if (!$item_message['id']) {
                    continue;
                }
                $message_time = strtotime($item_message['last_comment_at']);
                $newest_message_received = max($newest_message_received, $message_time);
                if ($message_time <= $last_message_received) {
                    continue;
                }
                // all done here.
                // check if we have this message in our database already.
                $envato_message = new shub_message($this->account, $this, false);
                $envato_message->load_by_network_key($item_message['id'], $item_message, 'item_comment', $debug);
                $count++;
                if ($debug) {
                    ?>
					<div>
					<pre> Imported message ID: <?php 
                    echo $envato_message->get('network_key');
                    ?>
 </pre>
					</div>
				<?php 
                }
            }
        }
        SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'envato', 'Imported  ' . $count . ' new messages into database');
        if ($debug) {
            echo " imported {$count} new item comments <br>";
        }
        $this->update('last_message', $newest_message_received);
        $this->update('last_checked', time());
    }
    public function admin_ajax()
    {
        if (check_ajax_referer('support-hub-nonce', 'wp_nonce')) {
            // todo: don't overwrite default superglobals, run stripslashes every time before we use the content, because another plugin might be stripslashing already
            $_POST = stripslashes_deep($_POST);
            $_GET = stripslashes_deep($_GET);
            $_REQUEST = stripslashes_deep($_REQUEST);
            $action = isset($_REQUEST['action']) ? str_replace('support_hub_', '', $_REQUEST['action']) : false;
            switch ($action) {
                case 'modal':
                    // open a modal popup with the message in it (similar to pages/message.php)
                    if (isset($_REQUEST['network']) && isset($_REQUEST['message_id']) && (int) $_REQUEST['message_id'] > 0) {
                        $network = isset($_GET['network']) ? $_GET['network'] : false;
                        $message_id = isset($_GET['message_id']) ? (int) $_GET['message_id'] : false;
                        $message_comment_id = isset($_GET['message_comment_id']) ? (int) $_GET['message_comment_id'] : false;
                        if ($network && isset($this->message_managers[$network]) && $message_id > 0) {
                            $shub_extension_message = $this->message_managers[$network]->get_message(false, false, $message_id);
                            if ($shub_extension_message->get('shub_message_id') == $message_id) {
                                extract(array("shub_account_id" => $shub_extension_message->get('account')->get('shub_account_id'), "shub_message_id" => $message_id, "shub_message_comment_id" => $message_comment_id));
                                include trailingslashit(SupportHub::getInstance()->dir) . 'extensions/' . $network . '/' . $network . '_message.php';
                            } else {
                                echo 'Failed to load message from database';
                            }
                        } else {
                            echo 'Failed network message ID';
                        }
                    } else {
                        echo 'Failed network params';
                    }
                    break;
                case 'next-continuous-message':
                    if (!empty($_SESSION['_shub_search_rules'])) {
                        //$_SESSION['_shub_search_rules'] = array($this_search, $order, $message_ids);
                        $this_search = $_SESSION['_shub_search_rules'][0];
                        $message_ids = $_SESSION['_shub_search_rules'][2];
                        $this_search['not_in'] = $message_ids;
                        SupportHub::getInstance()->load_all_messages($this_search, $_SESSION['_shub_search_rules'][1], 5);
                        $all_messages = SupportHub::getInstance()->all_messages;
                        foreach ($all_messages as $all_message) {
                            $message_ids[] = $all_message['shub_message_id'];
                        }
                        // this is used in class-support-hub.php to load the next batch of messages.
                        $_SESSION['_shub_search_rules'][2] = $message_ids;
                        $myListTable = new SupportHubMessageList(array('screen' => 'shub_inbox'));
                        $myListTable->set_layout_type('continuous');
                        $myListTable->set_data($all_messages);
                        $myListTable->prepare_items();
                        if ($myListTable->has_items()) {
                            $myListTable->display_rows();
                        } else {
                            echo '<div class="no-items" style="text-align:center">';
                            $myListTable->no_items();
                            echo '</div>';
                        }
                    }
                    break;
                case 'set-answered':
                    if (isset($_REQUEST['network']) && isset($this->message_managers[$_REQUEST['network']]) && !empty($_REQUEST['shub_message_id'])) {
                        $shub_extension_message = $this->message_managers[$_REQUEST['network']]->get_message(false, false, $_REQUEST['shub_message_id']);
                        if ($shub_extension_message->get('shub_message_id') == $_REQUEST['shub_message_id']) {
                            if (!headers_sent()) {
                                header('Content-type: text/javascript');
                            }
                            // we hide the element and provide an 'undo' placeholder in its place.
                            // if it's a row we just hide it, if it's a div we slide it up nicely.
                            if (isset($_REQUEST['last_active']) && $_REQUEST['last_active'] != $shub_extension_message->get('last_active')) {
                                // a new message was received without updating the page.
                                // todo: ajax the shit out of live message updates instead of waiting for action.
                                // todo: do this check on bulk actions as well.
                                ?>
                                alert('There is an update to this message. Please refresh the page to see.');
                                <?php 
                            } else {
                                $shub_extension_message->update('shub_status', _shub_MESSAGE_STATUS_ANSWERED);
                                ?>
                                var element = jQuery('.shub_extension_message[data-message-id=<?php 
                                echo (int) $_REQUEST['shub_message_id'];
                                ?>
]');
                                var element_action = element.prev('.shub_extension_message_action').first();
                                element_action.find('.action_content').html('Message Archived. <a href="#" class="shub_message_action" data-action="set-unanswered" data-post="<?php 
                                echo esc_attr(json_encode(array('network' => $_REQUEST['network'], 'shub_message_id' => (int) $_REQUEST['shub_message_id'])));
                                ?>
">Undo</a>');
                                if(element.is('div')){
                                element.slideUp(function(){element.remove();});
                                element_action.slideDown();
                                }else{
                                element.remove();
                                element_action.show();
                                }
                                element_action.data('undo-type','answered');
                                <?php 
                            }
                        }
                    }
                    break;
                case 'set-unanswered':
                    if (isset($_REQUEST['network']) && isset($this->message_managers[$_REQUEST['network']]) && !empty($_REQUEST['shub_message_id'])) {
                        $shub_extension_message = $this->message_managers[$_REQUEST['network']]->get_message(false, false, $_REQUEST['shub_message_id']);
                        if ($shub_extension_message->get('shub_message_id') == $_REQUEST['shub_message_id']) {
                            $shub_extension_message->update('shub_status', _shub_MESSAGE_STATUS_UNANSWERED);
                            if (!headers_sent()) {
                                header('Content-type: text/javascript');
                            }
                            // we hide the element and provide an 'undo' placeholder in its place.
                            // if it's a row we just hide it, if it's a div we slide it up nicely.
                            ?>
                            var element = jQuery('.shub_extension_message[data-message-id=<?php 
                            echo (int) $_REQUEST['shub_message_id'];
                            ?>
]');
                            var element_action = element.prev('.shub_extension_message_action').first();
                            element_action.find('.action_content').html('Message Moved to Inbox. <a href="#" class="shub_message_action" data-action="set-answered" data-post="<?php 
                            echo esc_attr(json_encode(array('network' => $_REQUEST['network'], 'shub_message_id' => (int) $_REQUEST['shub_message_id'])));
                            ?>
">Undo</a>');
                            if(element.is('div')){
                            element.slideUp(function(){element.remove();});
                            element_action.slideDown();
                            }else{
                            element.remove();
                            element_action.show();
                            }
                            element_action.data('undo-type','unanswered');
                            <?php 
                        }
                    }
                    break;
                case 'send-message-reply':
                    /*
                    sample post data:
                        action:support_hub_send-message-reply
                        wp_nonce:dfd377374d
                        message:test
                        account-id:1
                        message-id:246
                        network:envato
                        debug:1
                    */
                    if (isset($_REQUEST['network']) && isset($this->message_managers[$_REQUEST['network']]) && !empty($_REQUEST['account-id']) && !empty($_REQUEST['message-id'])) {
                        $shub_extension_message = $this->message_managers[$_REQUEST['network']]->get_message(false, false, $_REQUEST['message-id']);
                        if ($shub_extension_message->get('shub_message_id') == $_REQUEST['message-id']) {
                            $return = array('message' => '', 'error' => false, 'shub_outbox_id' => false);
                            if (isset($_REQUEST['last_active']) && $_REQUEST['last_active'] != $shub_extension_message->get('last_active')) {
                                $return['error'] = true;
                                $return['message'] = 'There is an update to this message. Please refresh the page to see.';
                            } else {
                                $message = isset($_POST['message']) && $_POST['message'] ? $_POST['message'] : '';
                                $account_id = $_REQUEST['account-id'];
                                $debug = isset($_POST['debug']) && (int) $_POST['debug'] > 0 ? true : false;
                                if ($message) {
                                    // we have a message and a message manager.
                                    // time to queue this baby into the outbox and send it swimming
                                    // what the hell did I just write? I need sleep!
                                    $outbox = new SupportHubOutbox();
                                    $outbox->create_new();
                                    if ($outbox->get('shub_outbox_id')) {
                                        if ($debug) {
                                            ob_start();
                                        }
                                        $extra_data = array();
                                        foreach ($_POST as $key => $val) {
                                            if (strpos($key, 'extra-') !== false) {
                                                $extra_data[substr($key, 6)] = $val;
                                            }
                                        }
                                        $outbox->update_outbox_data(array('debug' => $debug, 'extra' => $extra_data));
                                        $message_comment_id = $shub_extension_message->queue_reply($account_id, $message, $debug, $extra_data, $outbox->get('shub_outbox_id'));
                                        if (!$message_comment_id) {
                                            $return['message'] .= 'Failed to queue comment reply in database.';
                                            $return['error'] = true;
                                        } else {
                                            // successfully queued. do we archive?
                                            if (!empty($_POST['archive'])) {
                                                $shub_extension_message->update('shub_status', _shub_MESSAGE_STATUS_ANSWERED);
                                            }
                                        }
                                        $outbox->update(array('shub_extension' => $_REQUEST['network'], 'shub_account_id' => $account_id, 'shub_message_id' => $_REQUEST['message-id'], 'shub_message_comment_id' => $message_comment_id));
                                        if ($debug) {
                                            // send the message straight away and show any debug output
                                            echo $outbox->send_queued(true);
                                            $return['message'] .= ob_get_clean();
                                            // dont send an shub_outbox_id in debug mode
                                            // this will keep the 'message' window open and not shrink it down so we can better display debug messages.
                                        } else {
                                            //set_message( _l( 'message sent and conversation archived.' ) );
                                            $return['shub_outbox_id'] = $outbox->get('shub_outbox_id');
                                        }
                                    }
                                }
                            }
                            if (!headers_sent()) {
                                header('Content-type: text/javascript');
                            }
                            echo json_encode($return);
                            exit;
                        }
                    }
                    break;
                case 'queue-watch':
                    // find out how many pending messages exist and display that result back to the browser.
                    // along with outbox_ids so we can update the UI when it is sent
                    $this->send_outbox_messages();
                    $pending = SupportHubOutbox::get_pending();
                    $failed = SupportHubOutbox::get_failed();
                    $return = array();
                    if (!headers_sent()) {
                        header('Content-type: text/javascript');
                    }
                    $return['outbox_ids'] = array();
                    foreach ($pending as $message) {
                        $return['outbox_ids'][] = array('shub_outbox_id' => $message['shub_outbox_id'], 'shub_status' => $message['shub_status']);
                    }
                    foreach ($failed as $message) {
                        $return['outbox_ids'][] = array('shub_outbox_id' => $message['shub_outbox_id'], 'shub_status' => $message['shub_status']);
                    }
                    echo json_encode($return);
                    break;
                case 'resend_outbox_message':
                    $shub_outbox_id = !empty($_REQUEST['shub_outbox_id']) ? (int) $_REQUEST['shub_outbox_id'] : false;
                    if ($shub_outbox_id) {
                        if (!headers_sent()) {
                            header('Content-type: text/javascript');
                        }
                        $pending = new SupportHubOutbox($shub_outbox_id);
                        if ($pending->get('shub_outbox_id') == $shub_outbox_id) {
                            ob_start();
                            echo $pending->send_queued(true);
                            $return = array('message' => 'Message Resent. Please refresh the page. ' . ob_get_clean());
                            echo json_encode($return);
                        }
                        exit;
                    }
                    break;
                case 'delete_outbox_message':
                    $shub_outbox_id = !empty($_REQUEST['shub_outbox_id']) ? (int) $_REQUEST['shub_outbox_id'] : false;
                    if ($shub_outbox_id) {
                        if (!headers_sent()) {
                            header('Content-type: text/javascript');
                        }
                        // remove the comment from the database.
                        $pending = new SupportHubOutbox($shub_outbox_id);
                        if ($pending->get('shub_outbox_id') == $shub_outbox_id) {
                            shub_delete_from_db('shub_message_comment', 'shub_message_comment_id', $pending->get('shub_message_comment_id'));
                            $pending->delete();
                            $return = array('message' => 'Deleted Successfully. Please re-load the page.');
                            echo json_encode($return);
                        }
                        exit;
                    }
                    break;
                case 'request_extra_details':
                    if (!empty($_REQUEST['network']) && isset($this->message_managers[$_REQUEST['network']])) {
                        if (!headers_sent()) {
                            header('Content-type: text/javascript');
                        }
                        $debug = isset($_POST['debug']) && $_POST['debug'] ? $_POST['debug'] : false;
                        $response = array();
                        $extra_ids = isset($_REQUEST['extra_ids']) && is_array($_REQUEST['extra_ids']) ? $_REQUEST['extra_ids'] : array();
                        $account_id = isset($_REQUEST['accountId']) ? (int) $_REQUEST['accountId'] : (isset($_REQUEST['account-id']) ? (int) $_REQUEST['account-id'] : false);
                        $message_id = isset($_REQUEST['messageId']) ? (int) $_REQUEST['messageId'] : (isset($_REQUEST['message-id']) ? (int) $_REQUEST['message-id'] : false);
                        if (empty($extra_ids)) {
                            $response['message'] = 'Please request at least one Extra Detail';
                        } else {
                            $shub_message = new shub_message(false, false, $message_id);
                            if ($message_id && $shub_message->get('shub_message_id') == $message_id) {
                                // build the message up
                                $message = SupportHubExtra::build_message(array('network' => $_REQUEST['network'], 'account_id' => $account_id, 'message_id' => $message_id, 'extra_ids' => $extra_ids));
                                $response['message'] = $message;
                                //							if($debug)ob_start();
                                //							$shub_message->send_reply( $shub_message->get('envato_id'), $message, $debug );
                                //							if($debug){
                                //								$response['message'] = ob_get_clean();
                                //							}else {
                                //								$response['redirect'] = 'admin.php?page=support_hub_main';
                                //							}
                            }
                        }
                        echo json_encode($response);
                        exit;
                    }
                    break;
            }
            // pass off the ajax handling to our media managers:
            foreach ($this->message_managers as $name => $message_manager) {
                if ($message_manager->handle_ajax($action, $this)) {
                    // success!
                }
            }
        }
        exit;
    }
 public function extra_send_message($message, $network, $account_id, $message_id)
 {
     // save this message in the database as a new comment.
     // set the 'private' flag so we know this comment has been added externally to the API scrape.
     $shub_message = new shub_message(false, false, $message_id);
     $existing_comments = $shub_message->get_comments();
     shub_update_insert('shub_message_comment_id', false, 'shub_message_comment', array('shub_message_id' => $shub_message->get('shub_message_id'), 'private' => 1, 'message_text' => $message, 'time' => time(), 'shub_user_id' => !empty($_SESSION['shub_oauth_envato']['shub_user_id']) ? $_SESSION['shub_oauth_envato']['shub_user_id'] : $shub_message->get('shub_user_id')));
     // mark the main message as unread so it appears at the top.
     $shub_message->update('shub_status', _shub_MESSAGE_STATUS_UNANSWERED);
     $shub_message->update('last_active', time());
     // todo: update the 'summary' to reflect this latest message?
     $shub_message->update('summary', $message);
     // todo: post a "Thanks for providing information, we will reply soon" message on Envato comment page
 }
<?php

if (!isset($shub_account_id) || !isset($shub_message_id)) {
    exit;
}
if ($shub_account_id && $shub_message_id) {
    $ucm = new shub_ucm_account($shub_account_id);
    if ($shub_account_id && $ucm->get('shub_account_id') == $shub_account_id) {
        $ucm_message = new shub_message($ucm, false, $shub_message_id);
        $ucm_message->output_message_page('popup');
    }
}