public function api($endpoint, $method = false, $params = array())
 {
     $headers = array('user-agent' => 'SupportHub WP Plugin', 'timeout' => 20);
     //$headers['headers'] = array('Authorization' => $this->_api_key,);
     $params['auth'] = $this->_api_key;
     if ($params) {
         $headers['body'] = $params;
         $response = wp_remote_post($this->_api_url . (strpos($this->_api_url, '?') ? '&' : '?') . "endpoint={$endpoint}&method={$method}", $headers);
     } else {
         $response = wp_remote_get($this->_api_url . (strpos($this->_api_url, '?') ? '&' : '?') . "endpoint={$endpoint}&method={$method}", $headers);
     }
     if (is_array($response) && isset($response['body']) && isset($response['response']['code']) && $response['response']['code'] == 200) {
         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'API Call: ' . $endpoint . '/' . $method, $response['body']);
         $header = $response['headers'];
         $body = @json_decode($response['body'], true);
         if (!$body) {
             SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'ucm', 'API Error, unable to JSON decode: ' . $endpoint . ' ' . (isset($response['response']['code']) ? $response['response']['code'] . ' / ' : '') . (isset($response['body']) ? $response['body'] : ''));
         }
         return $body;
     } else {
         if (is_array($response) && isset($response['response']['code']) && $response['response']['code']) {
             SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'ucm', 'API Error: ' . $endpoint . ' ' . (isset($response['response']['code']) ? $response['response']['code'] . ' / ' : '') . (isset($response['body']) ? $response['body'] : ''), $response);
         } else {
             if (is_wp_error($response)) {
                 SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'ucm', 'API Error: ' . $endpoint . ' ' . $response->get_error_message(), $response);
             }
         }
     }
     return false;
 }
 public function page_assets($from_master = false)
 {
     if (!$from_master) {
         SupportHub::getInstance()->inbox_assets();
     }
     wp_register_style('support-hub-bbpress-css', plugins_url('extensions/bbpress/shub_bbpress.css', _DTBAKER_SUPPORT_HUB_CORE_FILE_), array(), '1.0.0');
     wp_enqueue_style('support-hub-bbpress-css');
     wp_register_script('support-hub-bbpress', plugins_url('extensions/bbpress/shub_bbpress.js', _DTBAKER_SUPPORT_HUB_CORE_FILE_), array('jquery'), '1.0.0');
     wp_enqueue_script('support-hub-bbpress');
 }
Exemple #3
0
		<?php 
_e('Support Hub Message', 'support_hub');
?>
	</h2>

    <div id="shub_table_inline">
        <div id="shub_table_contents">
        <?php 
// output same content that should be displayed in our modal popup.
$network = isset($_GET['network']) ? $_GET['network'] : false;
$shub_message_id = isset($_GET['message_id']) ? (int) $_GET['message_id'] : false;
if ($network && isset($this->message_managers[$network]) && $shub_message_id > 0) {
    $shub_extension_message = $this->message_managers[$network]->get_message(false, false, $shub_message_id);
    if ($shub_extension_message->get('shub_message_id') == $shub_message_id) {
        $shub_account_id = $shub_extension_message->get('account')->get('shub_account_id');
        include trailingslashit(SupportHub::getInstance()->dir) . 'extensions/' . $network . '/' . $network . '_message.php';
    }
}
?>
        </div>
    </div>


    <script type="text/javascript">
        jQuery(function () {
            ucm.social.init();
            <?php 
foreach ($this->message_managers as $message_id => $message_manager) {
    $message_manager->init_js();
}
?>
    public function load_latest_item_data($debug = false)
    {
        // serialise this result into account_data.
        if (!$this->account) {
            echo 'No bbpress account linked, please try again';
            return;
        }
        $api = $this->account->get_api();
        $network_key = $this->get('network_key');
        if (!$network_key) {
            echo 'No bbpress forum id found';
            return;
        }
        // first we seed the cache with the latest bbpress replies and topics
        // we do this because it's not possible to filter based on "post_parent" through the WordPress API (SILLY!)
        // so this saves us calling getPost() a lot of times.
        $filter_replies = array('post_type' => 'reply', 'number' => 100, 'post_status' => 'publish');
        $api_result_latest_replies = $this->account->get_api_cache($filter_replies);
        $api_result_latest_replies = $api_result_latest_replies ? $api_result_latest_replies : $api->getPosts($filter_replies);
        $filter_topics = array('post_type' => 'topic', 'number' => 100, 'post_status' => 'publish');
        $api_result_latest_topics = $this->account->get_api_cache($filter_topics);
        $api_result_latest_topics = $api_result_latest_topics ? $api_result_latest_topics : $api->getPosts($filter_topics);
        // loop through our latest replies and see if any of them are from a thread that sits under this forum
        // COMPLETELY THE REVERSE WAY THAT WE SHOULD BE DOING IT! rar!
        $forum_topics = array();
        foreach ($api_result_latest_topics as $forum_topic) {
            if ($forum_topic['post_parent'] == $network_key) {
                $forum_topic['timestamp'] = $forum_topic['post_date']->timestamp;
                // yay! this reply is part of a topic that is part of this forum. keep it.
                if (!isset($forum_topics[$forum_topic['post_id']])) {
                    $forum_topics[$forum_topic['post_id']] = $forum_topic;
                }
                if (!isset($forum_topics[$forum_topic['post_id']]['replies'])) {
                    $forum_topics[$forum_topic['post_id']]['replies'] = array();
                }
                // we need to add our main forum_topic onto the replies array so that all messages go into the 'comments' database table.
                $forum_topics[$forum_topic['post_id']]['replies'][] = $forum_topic;
            }
        }
        foreach ($api_result_latest_replies as $forum_reply) {
            // find its parent and see if it is from this forum.
            $found_parent = false;
            foreach ($api_result_latest_topics as $forum_topic) {
                if ($forum_topic['post_id'] == $forum_reply['post_parent']) {
                    $found_parent = $forum_topic;
                    break;
                }
            }
            if (!$found_parent) {
                $api_result_parent = $api->getPost($forum_reply['post_parent']);
                if ($api_result_parent) {
                    $found_parent = $api_result_parent;
                    $api_result_latest_topics[] = $api_result_parent;
                    // add to cache so we hopefully dont have to hit it again if it's a popular topic
                }
            }
            if ($found_parent) {
                // found a parent post, check if it's part of this forum.
                if ($found_parent['post_parent'] == $network_key) {
                    $found_parent['timestamp'] = $found_parent['post_date']->timestamp;
                    $forum_reply['timestamp'] = $forum_reply['post_date']->timestamp;
                    // yay! this reply is part of a topic that is part of this forum. keep it.
                    if (!isset($forum_topics[$found_parent['post_id']])) {
                        $forum_topics[$found_parent['post_id']] = $found_parent;
                    }
                    if (!isset($forum_topics[$found_parent['post_id']]['replies'])) {
                        $forum_topics[$found_parent['post_id']]['replies'] = array();
                    }
                    $forum_topics[$found_parent['post_id']]['replies'][] = $found_parent;
                    $forum_topics[$found_parent['post_id']]['replies'][] = $forum_reply;
                    if (!isset($forum_topics[$found_parent['post_id']]['timestamp'])) {
                        $forum_topics[$found_parent['post_id']]['timestamp'] = $found_parent['timestamp'];
                    }
                    $forum_topics[$found_parent['post_id']]['timestamp'] = max($forum_reply['post_date']->timestamp, $forum_topics[$found_parent['post_id']]['timestamp']);
                }
                /*echo date('Y-m-d',$forum_reply['post_date']->timestamp);
                		echo " <a href='".$forum_reply['link']."'>'".$forum_reply['link'].'</a> ';
                		echo $forum_reply['post_content'];
                		echo "Parent is: ";
                		echo date('Y-m-d',$found_parent['post_date']->timestamp);
                		echo " <a href='".$found_parent['link']."'>'".$found_parent['link'].'</a> ';
                		echo '<hr>';*/
            } else {
            }
        }
        uasort($forum_topics, function ($a, $b) {
            return $a['timestamp'] < $b['timestamp'];
        });
        // cache them for any other bbpress forum calls that are run during the same cron job process.
        $this->account->set_api_cache($filter_replies, $api_result_latest_replies);
        $this->account->set_api_cache($filter_topics, $api_result_latest_topics);
        // 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 replies for forum: " . $network_key . " (last message in database is from " . shub_print_date($last_message_received, true) . ")<br>\n";
        }
        $newest_message_received = 0;
        SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'bbpress', 'Found total of ' . count($forum_topics) . " forum topics from API calls");
        $count = 0;
        foreach ($forum_topics as $forum_topic) {
            $message_time = $forum_topic['timestamp'];
            $newest_message_received = max($newest_message_received, $message_time);
            if ($message_time <= $last_message_received) {
                break;
            }
            // all done here.
            $bbpress_message = new shub_bbpress_message($this->account, $this, false);
            $bbpress_message->load_by_bbpress_id($forum_topic['post_id'], $forum_topic, 'forum_topic', $debug);
            $count++;
            SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'bbpress', 'Imported forum topic ID ' . $bbpress_message->get('network_key') . " with " . count($forum_topic['replies']) . ' replies');
            if ($debug) {
                ?>
				<div>
				<pre> Imported forum topic ID: <?php 
                echo $bbpress_message->get('network_key');
                ?>
 with <?php 
                echo count($forum_topic['replies']);
                ?>
 replies. </pre>
				</div>
			<?php 
            }
        }
        // get user, return envato_codes in meta
        SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'bbpress', 'Completed Cron Import: ' . $count . ' new forum topics');
        if ($debug) {
            echo " imported {$count} new forum comments <br>";
        }
        $this->update('last_message', $newest_message_received);
        $this->update('last_checked', time());
    }
 public function refresh_token()
 {
     $url = $this->get_token_url();
     $parameters = array();
     $parameters['grant_type'] = "refresh_token";
     $parameters['refresh_token'] = $this->token['refresh_token'];
     $parameters['redirect_uri'] = $this->_redirect_url;
     $parameters['client_id'] = $this->_client_id;
     $parameters['client_secret'] = $this->_client_secret;
     $fields_string = '';
     foreach ($parameters as $key => $value) {
         $fields_string .= $key . '=' . urlencode($value) . '&';
     }
     try {
         $response = $this->get_url($url, $fields_string, false, false);
     } catch (EnvatoException $e) {
         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'envato', 'OAuth API Fail', $e->__toString());
         return false;
     }
     $new_token = json_decode($response, true);
     $this->token['access_token'] = $new_token['access_token'];
     return $this->token['access_token'];
 }
define('_SUPPORT_HUB_LOG_ERROR', 2);
define('_SUPPORT_HUB_LINK_REQUEST_EXTRA', 'shrequestextra');
define('_SUPPORT_HUB_LINK_REWRITE_PREFIX', 'shublnk');
define('_SUPPORT_HUB_PASSWORD_FIELD_FUZZ', '-password-');
define('_DTBAKER_SUPPORT_HUB_CORE_FILE_', __FILE__);
// Include core files that do all the magic
require_once 'classes/class-support-hub.php';
require_once 'classes/class-support-hub-table.php';
require_once 'classes/class-support-hub-extension.php';
require_once 'classes/class-support-hub-account.php';
require_once 'classes/class-support-hub-message.php';
require_once 'classes/class-support-hub-item.php';
require_once 'classes/class-support-hub-outbox.php';
require_once 'classes/class-support-hub-product.php';
require_once 'classes/class-support-hub-user.php';
require_once 'classes/class-support-hub-extra.php';
require_once 'classes/ucm.database.php';
require_once 'classes/ucm.form.php';
require_once 'vendor/autoload.php';
// include the different network plugins:
// these plugins hook on 'shub_init' to add their instance to the global 'message_manager' variable
// 3rd party plugins can hook into shub_init to add their own 'message_manager'
$base_extensions = array('envato', 'twitter', 'facebook', 'google', 'bbpress', 'ucm');
foreach ($base_extensions as $base_extension) {
    if (file_exists(__DIR__ . '/extensions/' . $base_extension . '/init.' . $base_extension . '.php')) {
        require_once __DIR__ . '/extensions/' . $base_extension . '/init.' . $base_extension . '.php';
    }
}
// commence the awesome:
SupportHub::getInstance(_DTBAKER_SUPPORT_HUB_CORE_FILE_);
Exemple #7
0
}
?>
            </select>
            </span>
            <span>
            <label for="simple_inbox-search-product"><?php 
_e('Product:', 'support_hub');
?>
</label>
            <select id="simple_inbox-search-product" name="search[shub_product_id]">
                <option value=""><?php 
_e('All', 'support_hub');
?>
</option>
                <?php 
foreach (SupportHub::getInstance()->get_products() as $product) {
    ?>
                    <option value="<?php 
    echo $product['shub_product_id'];
    ?>
"<?php 
    echo isset($search['shub_product_id']) && $search['shub_product_id'] == $product['shub_product_id'] ? ' selected' : '';
    ?>
><?php 
    echo esc_attr($product['product_name']);
    ?>
</option>
                <?php 
}
?>
            </select>
									</div>
									<br/><br/>

									<table class="wp-list-table widefat fixed striped">
										<thead>
										<tr>
											<th>Enabled</th>
											<th>UCM Product</th>
											<th>Support Hub Product</th>
											<th>Last Checked</th>
											<th>Action</th>
										</tr>
										</thead>
										<tbody>
										<?php 
                    $products = SupportHub::getInstance()->get_products();
                    foreach ($data['items'] as $product_id => $product_data) {
                        ?>
											<tr>
												<td>
													<input type="checkbox" name="item[<?php 
                        echo $product_id;
                        ?>
]" class="check_item"
													       value="1" <?php 
                        echo $shub_ucm_account->is_item_active($product_id) ? ' checked' : '';
                        ?>
>
                                                    <input type="hidden" name="item_name[<?php 
                        echo $product_id;
                        ?>
    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 static function handle_request_extra()
 {
     if (isset($_REQUEST[_SUPPORT_HUB_LINK_REQUEST_EXTRA]) && !empty($_REQUEST[_SUPPORT_HUB_LINK_REQUEST_EXTRA])) {
         // 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);
         // verify this extra link is valid.
         $bits = explode(':', $_REQUEST[_SUPPORT_HUB_LINK_REQUEST_EXTRA]);
         if (count($bits) == 5) {
             $network = $bits[0];
             $account_id = (int) $bits[1];
             $message_id = (int) $bits[2];
             $extra_ids = explode(',', $bits[3]);
             $legit_hash = self::build_message_hash($network, $account_id, $message_id, $extra_ids);
             if ($legit_hash == $_REQUEST[_SUPPORT_HUB_LINK_REQUEST_EXTRA]) {
                 // woo we have a legit hash. continue.
                 if (!session_id()) {
                     if (headers_sent()) {
                         echo "Warning: session headers already sent, unable to proceed, please report this error.";
                         exit;
                     }
                     session_start();
                 }
                 // user has landed on this page from a tweet or item comment
                 // we have to verify their identify first in order to provide the form and then do futher stuff.
                 // pass this off in an action to grab any login/verification from the various networks.
                 $login_status = false;
                 $SupportHub = SupportHub::getInstance();
                 ob_start();
                 include $SupportHub->get_template('shub_external_header.php');
                 if (isset($SupportHub->message_managers[$network])) {
                     // todo: offer them another way to login to the system.
                     // e.g. someone might want to login using Facebook to access their Envato feed
                     // if the email matches between accounts this should be possible
                     // if no match is found then we can just show a not found error.
                     // but for now we only allow login from the network we started with.
                     // ooooooooooo maybe we can have the generic extra_process_login method show a list of available login methods? and the individual networks can override this if needed
                     // hmm.. ideas ideas..
                     $login_status = $SupportHub->message_managers[$network]->extra_process_login($network, $account_id, $message_id, $extra_ids);
                 } else {
                     die('Invalid message manager');
                 }
                 if ($login_status) {
                     // the user is logged in and their identity has been verified by one of the 3rd party plugins.
                     // we can now safely accept their additoinal information and append it to this ticket.
                     $extras = self::get_all_extras();
                     $extra_previous_data = isset($_POST['extra']) && is_array($_POST['extra']) ? $_POST['extra'] : array();
                     $extra_previous_data_errors = array();
                     $extra_previous_data_validated = array();
                     $extra_previous_notes = isset($_POST['extra_notes']) ? $_POST['extra_notes'] : '';
                     // check if the user is submitting extra information:
                     $has_data_error = false;
                     $missing_required_information = false;
                     // todo, work out which fields are required, maybe mark them in the original request along with $extra_ids ?
                     foreach ($extras as $extra_id => $extra) {
                         if (!in_array($extra->get('shub_extra_id'), $extra_ids)) {
                             unset($extras[$extra_id]);
                         } else {
                             // this extra is to be shown on the page. load in any existing data for this extra item.
                             // todo: hmm nah, dont re-show that information here in the form, the form is only for adding new information.
                             // only show information that was an error and needs to be corrected again before submission/save.
                             //$extra_data = $extra->get_data($network, $account_id, $message_id);
                             if (isset($extra_previous_data[$extra_id]) && is_string($extra_previous_data[$extra_id])) {
                                 $status = array('success' => true);
                                 // validate the data, we have to filter it because Twitter might want to validate a Purchase code against the envato plugin.
                                 $status = apply_filters('shub_extra_validate_data', $status, $extra, $extra_previous_data[$extra_id], $network, $account_id, $message_id);
                                 if ($status && $status['success']) {
                                     // all good ready to save!
                                     $extra_previous_data_validated[$extra_id] = !empty($status['data']) ? $status : $extra_previous_data[$extra_id];
                                     // doing it this way so we can save additional details such as license code verification
                                 } else {
                                     $has_data_error = true;
                                     $extra_previous_data_errors[$extra_id] = isset($status['message']) ? $status['message'] : 'Error';
                                 }
                             } else {
                                 // todo: figureo ut if this field ismissing?
                                 if (!empty($extra_previous_notes) || !empty($extra_previous_data)) {
                                     $missing_required_information = true;
                                 }
                             }
                         }
                     }
                     if (!$has_data_error && (!empty($extra_previous_notes) || !empty($extra_previous_data_validated))) {
                         // user has input something
                         // build up the private message to store in the system
                         $message = '';
                         foreach ($extras as $extra_id => $extra) {
                             if (isset($extra_previous_data_validated[$extra_id])) {
                                 $message .= $extra->add_message_segment($extra_previous_data_validated[$extra_id]);
                             }
                         }
                         if (!empty($extra_previous_notes)) {
                             $message .= '<p>' . shub_forum_text($extra_previous_notes) . '</p>';
                             $extra_previous_notes = false;
                         }
                         // pass it through to the message managers to store this information!
                         // (e.g. envato module will validate the 'purchase_code' and return a possible error)
                         foreach ($extras as $extra_id => $extra) {
                             if (isset($extra_previous_data_validated[$extra_id])) {
                                 $status = $SupportHub->message_managers[$network]->extra_save_data($extra, $extra_previous_data_validated[$extra_id], $network, $account_id, $message_id);
                                 unset($extra_previous_data[$extra_id]);
                             }
                         }
                         // all done! save our message in the db
                         $SupportHub->message_managers[$network]->extra_send_message($message, $network, $account_id, $message_id);
                         // redirect browser to a done page.
                         header("Location: " . $_SERVER['REQUEST_URI'] . '&done');
                         exit;
                     }
                     include $SupportHub->get_template('shub_extra_request_form.php');
                 } else {
                     // we display the login form during request_extra_login()
                 }
                 include $SupportHub->get_template('shub_external_footer.php');
                 echo ob_get_clean();
                 exit;
             }
         }
     }
 }
 public function update_purchase_history()
 {
     $tokens = shub_get_multiple('shub_envato_oauth', array('shub_user_id' => $this->shub_user_id));
     // find the latest token for this user, per account.
     $account_tokens = array();
     // if any of them have expired, refresh the token from the api
     foreach ($tokens as $token) {
         if (!$token['shub_account_id']) {
             continue;
         }
         if (!isset($account_tokens[$token['shub_account_id']]) || $token['expire_time'] > $account_tokens[$token['shub_account_id']]['expire_time']) {
             $account_tokens[$token['shub_account_id']] = $token;
         }
     }
     foreach ($account_tokens as $account_token) {
         $shub_envato_account = new shub_envato_account($account_token['shub_account_id']);
         // found the account, pull in the API and build the url
         $api = $shub_envato_account->get_api();
         $api->set_manual_token($account_token);
         if ($account_token['expire_time'] <= time()) {
             // renew this token!
             $new_access_token = $api->refresh_token();
             if ($new_access_token) {
                 shub_update_insert('shub_envato_oauth_id', $account_token['shub_envato_oauth_id'], 'shub_envato_oauth', array('access_token' => $new_access_token, 'expire_time' => time() + 3600));
             } else {
                 echo 'Token refresh failed';
                 return false;
             }
         }
         $api_result = $api->api('v1/market/private/user/username.json', array(), false);
         $api_result_email = $api->api('v1/market/private/user/email.json', array(), false);
         if ($api_result && !empty($api_result['username'])) {
             $this->add_unique_meta('envato_username', $api_result['username']);
         }
         if ($api_result_email && !empty($api_result_email['email'])) {
             $email = trim(strtolower($api_result_email['email']));
             // todo: not sure if best to update users eamail , if they change email accounts and stuff
             $this->update('user_email', $email);
         }
         $api_result_purchase_history = $api->api('v2/market/buyer/purchases', array(), false);
         // store this purchase history in our db for later use.
         if ($api_result_purchase_history && !empty($api_result_purchase_history['buyer']['id']) && !empty($api_result_purchase_history['buyer']['username']) && $api_result_purchase_history['buyer']['username'] == $api_result['username']) {
             // we have the buyer ID! yay! this is better than a username.
             $this->add_unique_meta('envato_user_id', $api_result_purchase_history['buyer']['id']);
             if (!empty($api_result_purchase_history['purchases']) && is_array($api_result_purchase_history['purchases'])) {
                 foreach ($api_result_purchase_history['purchases'] as $purchase) {
                     if (!empty($purchase['item']['id'])) {
                         // todo: beg envato to add the purchase code to this output so we can link it together correctly.
                         // find out which shub product this is for
                         // if we cannot find one then we create one. this helps when new items are made.
                         $existing_products = SupportHub::getInstance()->get_products();
                         // check if this item exists already
                         $exists = false;
                         foreach ($existing_products as $existing_product) {
                             if (isset($existing_product['product_data']['envato_item_id']) && $existing_product['product_data']['envato_item_id'] == $purchase['item']['id']) {
                                 $exists = $existing_product['shub_product_id'];
                             }
                         }
                         $newproduct = new SupportHubProduct();
                         if (!$exists) {
                             $newproduct->create_new();
                         } else {
                             $newproduct->load($exists);
                         }
                         if (!$newproduct->get('product_name')) {
                             $newproduct->update('product_name', $purchase['item']['name']);
                         }
                         $existing_product_data = $newproduct->get('product_data');
                         if (!is_array($existing_product_data)) {
                             $existing_product_data = array();
                         }
                         if (empty($existing_product_data['envato_item_id'])) {
                             $existing_product_data['envato_item_id'] = $purchase['item']['id'];
                         }
                         if (empty($existing_product_data['envato_item_data'])) {
                             $existing_product_data['envato_item_data'] = $purchase['item'];
                         }
                         if (empty($existing_product_data['image'])) {
                             $existing_product_data['image'] = $purchase['item']['thumbnail_url'];
                         }
                         if (empty($existing_product_data['url'])) {
                             $existing_product_data['url'] = $purchase['item']['url'];
                         }
                         $newproduct->update('product_data', $existing_product_data);
                         if ($newproduct->get('shub_product_id')) {
                             // product has been added
                             // time to add it to the purchase db
                             // check if this already exists in the db
                             $existing_purchase = shub_get_single('shub_envato_purchase', array('purchase_code'), array($purchase['code']));
                             if (!$existing_purchase) {
                                 $shub_envato_purchase_id = shub_update_insert('shub_envato_purchase_id', false, 'shub_envato_purchase', array('shub_user_id' => $this->get('shub_user_id'), 'shub_product_id' => $newproduct->get('shub_product_id'), 'purchase_time' => strtotime($purchase['sold_at']), 'envato_user_id' => $api_result_purchase_history['buyer']['id'], 'purchase_code' => $purchase['code'], 'api_type' => 'buyer/purchases', 'purchase_data' => json_encode($purchase)));
                             } else {
                                 if (!$existing_purchase['shub_user_id']) {
                                     shub_update_insert('shub_envato_purchase_id', $existing_purchase['shub_envato_purchase_id'], 'shub_envato_purchase', array('shub_user_id' => $this->get('shub_user_id')));
                                 }
                                 $shub_envato_purchase_id = $existing_purchase['shub_envato_purchase_id'];
                             }
                             if ($shub_envato_purchase_id) {
                                 // we have a purchase in the db
                                 // add or update the support expiry based on this purchase history.
                                 // work out when this purchase support expires
                                 // this is the expiry date returned in the api or just 6 months from the original purchase date.
                                 $support_expiry_time = strtotime("+6 months", strtotime($purchase['sold_at']));
                                 // todo - check for this expiry time in the new api results.
                                 $existing_support = shub_get_single('shub_envato_support', array('shub_envato_purchase_id'), array($shub_envato_purchase_id));
                                 if ($existing_support && empty($existing_support['shub_user_id'])) {
                                     shub_update_insert('shub_envato_support_id', $existing_support['shub_envato_support_id'], 'shub_envato_support', array('shub_user_id' => $this->get('shub_user_id')));
                                 }
                                 if ($existing_support && $existing_support['shub_envato_support_id'] && $existing_support['start_time'] == strtotime($purchase['sold_at'])) {
                                     // check the existing support expiry matches the one we have in the database.
                                     if ($existing_support['end_time'] < $support_expiry_time) {
                                         // we have a support extension!
                                         $shub_envato_support_id = shub_update_insert('shub_envato_support_id', $existing_support['shub_envato_support_id'], 'shub_envato_support', array('end_time' => $support_expiry_time, 'api_type' => 'buyer/purchases', 'support_data' => json_encode($purchase)));
                                     }
                                 } else {
                                     // we are adding a new support entry
                                     $shub_envato_support_id = shub_update_insert('shub_envato_support_id', false, 'shub_envato_support', array('shub_user_id' => $this->get('shub_user_id'), 'shub_product_id' => $newproduct->get('shub_product_id'), 'shub_envato_purchase_id' => $shub_envato_purchase_id, 'start_time' => strtotime($purchase['sold_at']), 'end_time' => $support_expiry_time, 'api_type' => 'buyer/purchases', 'support_data' => json_encode($purchase)));
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return true;
 }
    public function load_latest_item_data($debug = false)
    {
        // serialise this result into ucm_data.
        if (!$this->account) {
            echo 'No ucm account linked, please try again';
            return;
        }
        $api = $this->account->get_api();
        $ucm_product_id = $this->get('network_key');
        if (!$ucm_product_id) {
            echo 'No ucm product 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');
        // dont want to import ALL tickets, so we pick a 20 day limit if we haven't done this yet
        if (!$last_message_received) {
            $last_message_received = strtotime('-20 days');
        }
        //        $last_message_received = false;
        SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'Loading latest tickets for product (' . $ucm_product_id . ') "' . $this->get('product_name') . '" modified since ' . shub_print_date($last_message_received, true));
        // find any messages from this particular UCM product that have been updated since our last scrape time.
        $tickets = $api->api('ticket', 'list', array('search' => array('faq_product_id' => $ucm_product_id, 'time_from' => $last_message_received, 'status_id' => 0)));
        if ($debug) {
            echo "Getting the latest tickets for product: " . $ucm_product_id . " (last message in database is from " . shub_print_date($last_message_received, true) . ")<br>\n";
        }
        $newest_message_received = 0;
        $count = 0;
        if (isset($tickets['reply_options'])) {
            $this->account->save_account_data(array('reply_options' => $tickets['reply_options']));
        }
        if (isset($tickets['tickets'])) {
            foreach ($tickets['tickets'] as $ticket) {
                $message_time = $ticket['last_message_timestamp'];
                $newest_message_received = max($newest_message_received, $message_time);
                //if($message_time <= $last_message_received)break; // all done here.
                $ucm_message = new shub_ucm_message($this->account, $this, false);
                $ucm_message->load_by_network_key($ticket['ticket_id'], $ticket, 'ticket', $debug);
                $count++;
                if ($debug) {
                    ?>
                    <div>
                        <pre> Imported Ticket ID: <?php 
                    echo $ucm_message->get('network_key');
                    ?>
                            with <?php 
                    echo $ticket['message_count'];
                    ?>
 message. </pre>
                    </div>
                    <?php 
                }
            }
        } else {
            SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'ucm', 'Failed to get a reply from the API for product ' . $ucm_product_id . ' "', $tickets);
        }
        // get user, return envato_codes in meta
        SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'Imported  ' . $count . ' product tickets into database (from a total of ' . count($tickets['tickets']) . ' returned by the api)');
        if ($debug) {
            echo " imported {$count} new product tickets <br>";
        }
        $this->update('last_message', $newest_message_received);
        $this->update('last_checked', time());
    }
 public function send_queued_comment_reply($bbpress_message_comment_id, $shub_outbox, $debug = false)
 {
     $comments = $this->get_comments();
     if (isset($comments[$bbpress_message_comment_id]) && !empty($comments[$bbpress_message_comment_id]['message_text'])) {
         $api = $this->account->get_api();
         //$item_data = $this->get('item')->get('item_data');
         $bbpress_post_data = $this->get('shub_data');
         $bbpress_id = $this->get('network_key');
         if ($debug) {
             echo "Sending a reply to bbPress Topic ID: {$bbpress_id} <br>\n";
         }
         $outbox_data = $shub_outbox->get('message_data');
         if ($outbox_data && isset($outbox_data['extra']) && is_array($outbox_data['extra'])) {
             $extra_data = $outbox_data['extra'];
         } else {
             $extra_data = array();
         }
         $api_result = false;
         try {
             $extra_data['api'] = 1;
             $api_result = $api->newPost('Reply to: ' . (isset($bbpress_post_data['post_title']) ? $bbpress_post_data['post_title'] : 'Post'), $comments[$bbpress_message_comment_id]['message_text'], array('post_type' => 'reply', 'post_parent' => $bbpress_id, 'custom_fields' => array(array('key' => 'support_hub', 'value' => json_encode($extra_data)))));
             SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'bbpress', 'API Result: ', $api_result);
         } catch (Exception $e) {
             SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'bbpress', 'API Error: ', $e);
             if ($debug) {
                 echo "API Error: " . $e;
             }
         }
         if ((int) $api_result > 0) {
             shub_update_insert('shub_message_comment_id', $bbpress_message_comment_id, 'shub_message_comment', array('network_key' => $api_result, 'time' => time()));
             return true;
         } else {
             echo "Failed to send comment, check debug log.";
             print_r($api_result);
             return false;
         }
         /*if((int) $api_result > 0){
                         // we have a post id for our reply!
                         // add this reply to the 'comments' array of our existing 'message' object.
         
                         // grab the updated post details for both the parent topic and the newly created reply:
                         $parent_topic = $api->getPost($this->get('network_key'));
                         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'bbpress', 'API Result: ', $api_result);
                         $reply_post = $api->getPost($api_result);
                         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'bbpress', 'API Result: ', $api_result);
         
                         if($parent_topic && $parent_topic['post_id'] == $this->get('network_key') && $reply_post && $reply_post['post_id'] == $api_result && $reply_post['post_parent'] == $this->get('network_key')){
                             // all looks hunky dory
                             $comments = $this->get('comments');
                             if(!is_array($comments))$comments = array();
                             array_unshift($comments, $reply_post);
                             $parent_topic['replies'] = $comments;
                             // save this updated data to the db
                             $this->load_by_bbpress_id($this->get('network_key'),$parent_topic,$this->get('shub_type'),$debug);
                             $existing_messages = $this->get_comments();
                             foreach($existing_messages as $existing_message){
                                 if(!$existing_message['user_id'] && $existing_message['message_text'] == $comments[$bbpress_message_comment_id]['message_text']){
                                     shub_update_insert('shub_message_comment_id',$existing_message['shub_message_comment_id'],'shub_message_comment',array(
                                         'user_id' => get_current_user_id(),
                                     ));
                                 }
                             }
                             $this->update('shub_status', _shub_MESSAGE_STATUS_ANSWERED);
                         }
         
                     }*/
     }
     return false;
 }
 public function get_api_user_to_id($ucm_user_data)
 {
     //print_r($ucm_user_data);exit;
     $comment_user = new SupportHubUser_ucm();
     if (!empty($ucm_user_data['email'])) {
         $comment_user->load_by('user_email', trim(strtolower($ucm_user_data['email'])));
     }
     if (!$comment_user->get('shub_user_id')) {
         // didn't find one yet.
         // find by envato username?
         if (isset($ucm_user_data['envato']['user'])) {
             $first = current($ucm_user_data['envato']['user']);
             if ($first && !empty($first['envato_username'])) {
                 if ($comment_user->load_by_meta('envato_username', strtolower($first['envato_username']))) {
                     // found! yay!
                     SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'Found a user based on envato username.', array('username' => $first['envato_username'], 'found_user_id' => $comment_user->get('shub_user_id')));
                 }
             }
         }
     }
     if (isset($ucm_user_data['envato']['purchases']) && is_array($ucm_user_data['envato']['purchases'])) {
         // find a matching user account with these purchases.
         foreach ($ucm_user_data['envato']['purchases'] as $purchase) {
             if (!empty($purchase['license_code'])) {
                 // pull in the license code using the envato module if it's enabled.
                 if (isset(SupportHub::getInstance()->message_managers['envato'])) {
                     $result = SupportHub::getInstance()->message_managers['envato']->pull_purchase_code(false, $purchase['license_code'], array(), $comment_user->get('shub_user_id'));
                     if ($result && !empty($result['shub_user_id'])) {
                         $comment_user->load($result['shub_user_id']);
                         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'Found a user based on license code.', array('license_code' => $purchase['license_code'], 'found_user_id' => $comment_user->get('shub_user_id')));
                         break;
                     }
                 }
             }
         }
     }
     if (!$comment_user->get('shub_user_id')) {
         // find a match based on email.
         if (!empty($ucm_user_data['email'])) {
             $comment_user->load_by('user_email', trim(strtolower($ucm_user_data['email'])));
         }
     }
     if (!$comment_user->get('shub_user_id')) {
         // no existing matches yet, create a new user with the above meta values so that we can find them again in the future.
         $comment_user->create_new();
     }
     // now we add/update various meta/values of the user if anything is missing.
     if (!empty($ucm_user_data['email']) && !$comment_user->get('user_email')) {
         $comment_user->update('user_email', trim(strtolower($ucm_user_data['email'])));
     }
     if (isset($ucm_user_data['envato']['user'])) {
         $first = current($ucm_user_data['envato']['user']);
         if ($first && !empty($first['envato_username']) && !$comment_user->get_meta('envato_username', strtolower($first['envato_username']))) {
             $comment_user->add_meta('envato_username', strtolower($first['envato_username']));
             if (!$comment_user->get('user_username')) {
                 $comment_user->update('user_username', strtolower($first['envato_username']));
             }
         }
     }
     if (isset($ucm_user_data['envato']['purchases'])) {
         foreach ($ucm_user_data['envato']['purchases'] as $purchase) {
             if (!empty($purchase['license_code']) && !$comment_user->get_meta('envato_license_code', strtolower($purchase['license_code']))) {
                 $comment_user->add_meta('envato_license_code', strtolower($purchase['license_code']));
             }
         }
     }
     if (!empty($ucm_user_data['name'])) {
         if (empty($ucm_user_data['last_name'])) {
             $bits = explode(" ", $ucm_user_data['name']);
             $ucm_user_data['name'] = array_shift($bits);
             $ucm_user_data['last_name'] = implode(" ", $bits);
         }
     }
     if (!$comment_user->get('user_fname') && !empty($ucm_user_data['name'])) {
         $comment_user->update('user_fname', $ucm_user_data['name']);
     }
     if (!$comment_user->get('user_lname') && !empty($ucm_user_data['last_name'])) {
         $comment_user->update('user_lname', $ucm_user_data['last_name']);
     }
     $comment_user->update_user_data($ucm_user_data);
     return $comment_user->get('shub_user_id');
 }
 public function pull_purchase_code($api, $purchase_code, $api_raw_data = array(), $existing_shub_user_id = false)
 {
     $purchase_code = strtolower(preg_replace('#([a-z0-9]{8})-?([a-z0-9]{4})-?([a-z0-9]{4})-?([a-z0-9]{4})-?([a-z0-9]{12})#', '$1-$2-$3-$4-$5', $purchase_code));
     // todo: add documentation that it needs to be named "Purchase Code"
     // todo: add a default extra value called Purchase Code.
     if (strlen($purchase_code) != 36) {
         return false;
     }
     // check existing purchase code and return that if it's cached
     $existing_purchase = shub_get_single('shub_envato_purchase', 'purchase_code', $purchase_code);
     if ($existing_purchase && $existing_purchase['shub_envato_purchase_id']) {
         // if there is a matching support id, grab that cached support data, add shub_user_id do it and return it
         // this matches our return data below.
         // if we don't find this then we continue below and call the API again to get fresh data.
         $existing_support = shub_get_single('shub_envato_support', array('shub_envato_purchase_id'), array($existing_purchase['shub_envato_purchase_id']));
         if ($existing_support && $existing_support['shub_user_id'] && $existing_support['support_data']) {
             $return = @json_decode($existing_support['support_data'], true);
             if ($return) {
                 $return['shub_user_id'] = $existing_support['shub_user_id'];
                 return $return;
             }
         }
     }
     $accounts = array();
     if (!$api) {
         // loop through accounts and try an API call on each one.
         $accounts = $this->get_accounts();
     }
     do {
         if ($accounts) {
             // grab an API from this account.
             $account = array_shift($accounts);
             $shub_envato_account = new shub_envato_account($account['shub_account_id']);
             // found the account, pull in the API and build the url
             $api = $shub_envato_account->get_api();
         }
         if (!$api) {
             break;
         }
         //            $result = $api->api('v1/market/private/user/verify-purchase:' . $purchase_code . '.json');
         $result = $api->api('v2/market/author/sale?code=' . $purchase_code);
         /*
                     {
                       "amount": "12.60",
                       "sold_at": "2015-08-18T21:30:02+10:00",
                       "item": {
                         "id": 1299019,
                         "name": "WooCommerce Australia Post Shipping Calculator",
                         "description": ...
                         "site": "codecanyon.net",
                         "classification": "wordpress/ecommerce/woocommerce/shipping",
                         "classification_url": "http://codecanyon.net/category/wordpress/ecommerce/woocommerce/shipping",
                         "price_cents": 1800,
                         "number_of_sales": 1054,
                         "author_username": "******",
                         "author_url": "http://codecanyon.net/user/dtbaker",
                         "author_image": "https://0.s3.envato.com/files/111547951/dtbaker-php-scripts-wordpress-themes-and-plugins.png",
                         "url": "http://codecanyon.net/item/woocommerce-australia-post-shipping-calculator/1299019",
                         "thumbnail_url": "https://0.s3.envato.com/files/15047665/thumb.png",
                         "summary": "High Resolution: No, Compatible With: WooCommerce 2.3.x, Software Version: WordPress 4.2, WordPress 4.1, WordPress 4.0, WordPress 3.9, WordPress 3.8, WordPress 3.7",
                         "rating": {
                           "rating": 3.82,
                           "count": 49
                         },
                         "updated_at": "2015-08-13T12:34:59+10:00",
                         "published_at": "2012-01-15T17:59:18+11:00",
                         "trending": false,
                         "previews": {
                           "landscape_preview": {
                             "landscape_url": "https://image-cc.s3.envato.com/files/15047663/preview.jpg"
                           }
                         }
                       },
                       "license": "Regular License",
                       "code": "c77ff344-9be4-4ba1-9e50-ce92e37c33e0",
                       "support_amount": ""
                     }
                     }*/
         if ($result && !empty($result['item']) && !empty($result['item']['id'])) {
             // valid purchase code.
             // what is the username attached to this purchase result?
             $envato_username = $result['buyer'];
             // find this user in our system.
             $shub_user = new SupportHubUser_Envato();
             if ($existing_shub_user_id) {
                 $shub_user->load($existing_shub_user_id);
             } else {
                 $shub_user->load_by_meta('envato_username', strtolower($envato_username));
             }
             if (!$shub_user->get('shub_user_id')) {
                 // no users exists in our system with this username.
                 // add a new one.
                 $shub_user->create_new();
             }
             if (!$shub_user->get('user_username')) {
                 $shub_user->update('user_username', $envato_username);
             }
             $shub_user->add_unique_meta('envato_username', strtolower($envato_username));
             // find out which product this purchase code is relating to
             $existing_products = SupportHub::getInstance()->get_products();
             // check if this item exists already
             $exists = false;
             foreach ($existing_products as $existing_product) {
                 if (isset($existing_product['product_data']['envato_item_id']) && $existing_product['product_data']['envato_item_id'] == $result['item']['id']) {
                     $exists = $existing_product['shub_product_id'];
                 }
             }
             $newproduct = new SupportHubProduct();
             if (!$exists) {
                 $newproduct->create_new();
             } else {
                 $newproduct->load($exists);
             }
             if (!$newproduct->get('product_name')) {
                 $newproduct->update('product_name', $result['item']['name']);
             }
             $existing_product_data = $newproduct->get('product_data');
             if (!is_array($existing_product_data)) {
                 $existing_product_data = array();
             }
             if (empty($existing_product_data['envato_item_id'])) {
                 $existing_product_data['envato_item_id'] = $result['item']['id'];
             }
             if (empty($existing_product_data['envato_item_data'])) {
                 // get these item details from api
                 $existing_product_data['envato_item_data'] = $result['item'];
                 if (empty($existing_product_data['image'])) {
                     $existing_product_data['image'] = $result['item']['thumbnail_url'];
                 }
                 if (empty($existing_product_data['url'])) {
                     $existing_product_data['url'] = $result['item']['url'];
                 }
             }
             $newproduct->update('product_data', $existing_product_data);
             if ($newproduct->get('shub_product_id')) {
             }
             $shub_envato_purchase_id = false;
             // store this in our purchase code database so we can access it easier later on
             $existing_purchase = shub_get_single('shub_envato_purchase', 'purchase_code', $purchase_code);
             if (!$existing_purchase) {
                 // see if we can find an existing purchase by this user at the same time, without a purchase code.
                 // (because results from the purchase api do not contian purchase codes)
                 $possible_purchases = shub_get_multiple('shub_envato_purchase', array('shub_user_id' => $shub_user->get('shub_user_id'), 'shub_product_id' => $newproduct->get('shub_product_id'), 'purchase_time' => strtotime($result['sold_at'])));
                 foreach ($possible_purchases as $possible_purchase) {
                     if (empty($possible_purchases['purchase_code'])) {
                         // this purchase came from the other api and doesn't have a purchase code.
                         // add it in!
                         $shub_envato_purchase_id = shub_update_insert('shub_envato_purchase_id', $possible_purchase['shub_envato_purchase_id'], 'shub_envato_purchase', array('purchase_code' => $purchase_code, 'api_time' => time()));
                         if (empty($possible_purchases['purchase_data'])) {
                             $raw_purchase_data = array_merge(array('author/sale' => $result), is_array($api_raw_data) ? $api_raw_data : array());
                             $shub_envato_purchase_id = shub_update_insert('shub_envato_purchase_id', $possible_purchase['shub_envato_purchase_id'], 'shub_envato_purchase', array('purchase_data' => json_encode($raw_purchase_data)));
                         }
                     }
                 }
             } else {
                 // we do have an existing purchase.
                 $shub_envato_purchase_id = $existing_purchase['shub_envato_purchase_id'];
                 //                    if (empty($existing_purchase['shub_user_id'])) {
                 shub_update_insert('shub_envato_purchase_id', $shub_envato_purchase_id, 'shub_envato_purchase', array('shub_user_id' => $shub_user->get('shub_user_id'), 'shub_product_id' => $newproduct->get('shub_product_id'), 'purchase_time' => strtotime($result['sold_at'])));
                 //                    }
             }
             if (!$shub_envato_purchase_id) {
                 // add new one
                 $raw_purchase_data = array_merge(array('author/sale' => $result), is_array($api_raw_data) ? $api_raw_data : array());
                 $shub_envato_purchase_id = shub_update_insert('shub_envato_purchase_id', false, 'shub_envato_purchase', array('shub_user_id' => $shub_user->get('shub_user_id'), 'shub_product_id' => $newproduct->get('shub_product_id'), 'envato_user_id' => 0, 'api_time' => time(), 'api_type' => 'author/sale', 'purchase_time' => strtotime($result['sold_at']), 'purchase_code' => $purchase_code, 'purchase_data' => json_encode($raw_purchase_data)));
             }
             if ($shub_envato_purchase_id) {
                 // support expiry time is 6 months from the purchase date, or as specified by the api result.
                 if (strtotime($result['sold_at']) < strtotime("2015-09-01")) {
                     $support_expiry_time = strtotime("+6 months", strtotime("2015-09-01"));
                 } else {
                     $support_expiry_time = strtotime("+6 months", strtotime($result['sold_at']));
                 }
                 if (!empty($result['supported_until'])) {
                     $support_expiry_time = strtotime($result['supported_until']);
                 }
                 $existing_support = shub_get_single('shub_envato_support', array('shub_envato_purchase_id'), array($shub_envato_purchase_id));
                 if ($existing_support && empty($existing_support['shub_user_id'])) {
                     shub_update_insert('shub_envato_support_id', $existing_support['shub_envato_support_id'], 'shub_envato_support', array('shub_user_id' => $shub_user->get('shub_user_id')));
                 }
                 if ($existing_support && $existing_support['shub_envato_support_id'] && $existing_support['start_time'] == strtotime($result['sold_at'])) {
                     // check the existing support expiry matches the one we have in the database.
                     if ($existing_support['end_time'] < $support_expiry_time) {
                         // we have a support extension!
                         $shub_envato_support_id = shub_update_insert('shub_envato_support_id', $existing_support['shub_envato_support_id'], 'shub_envato_support', array('end_time' => $support_expiry_time, 'api_type' => 'author/sale', 'support_data' => json_encode($result)));
                     }
                 } else {
                     // we are adding a new support entry
                     $shub_envato_support_id = shub_update_insert('shub_envato_support_id', false, 'shub_envato_support', array('shub_user_id' => $shub_user->get('shub_user_id'), 'shub_product_id' => $newproduct->get('shub_product_id'), 'shub_envato_purchase_id' => $shub_envato_purchase_id, 'api_type' => 'author/sale', 'start_time' => strtotime($result['sold_at']), 'end_time' => $support_expiry_time, 'support_data' => json_encode($result)));
                 }
             }
             $result['shub_user_id'] = $shub_user->get('shub_user_id');
             return $result;
         }
     } while (count($accounts));
     // if we get here it means the API request failed or it's an invalid purchase code.
     // log it in our database so we can at least re-check it at a later point in time or show it as failed in the UI somehow.
     $existing_purchase = shub_get_single('shub_envato_purchase', 'purchase_code', $purchase_code);
     if (!$existing_purchase) {
         $shub_envato_purchase_id = shub_update_insert('shub_envato_purchase_id', false, 'shub_envato_purchase', array('shub_user_id' => $existing_shub_user_id, 'shub_product_id' => 0, 'envato_user_id' => 0, 'api_type' => 'fail', 'purchase_time' => 0, 'purchase_code' => $purchase_code, 'purchase_data' => ''));
     }
     return false;
 }
 public function get_api_user($wp_user_id)
 {
     if (!(int) $wp_user_id) {
         return false;
     }
     // seed the cache with the latest existing user details.
     // generally the posts will come from recent users so it's quicker to get this bulk list of recent users and loop through that, compared to hitting the API for each user details on each forum post.
     $filter_user = array('number' => 100);
     $api = $this->get_api();
     try {
         //$api_user = $api->getUser($wp_user_id,array('username','basic','envato_codes')); print_r($api_user); exit;
         $api_result_latest_users = $this->get_api_cache($filter_user);
         if (!$api_result_latest_users) {
             $api_users = $api->getUsers($filter_user, array('basic', 'envato_codes'));
             $api_result_latest_users = array();
             foreach ($api_users as $api_user) {
                 $api_result_latest_users[$api_user['user_id']] = $api_user;
             }
             unset($api_users);
         }
         $this->set_api_cache($filter_user, $api_result_latest_users);
         // if this user doesn't exist in the latest listing we grab it
         if (!isset($api_result_latest_users[$wp_user_id])) {
             $api_user = $api->getUser($wp_user_id, array('basic', 'envato_codes'));
             if ($api_user && $api_user['user_id'] == $wp_user_id) {
                 $api_result_latest_users[$api_user['user_id']] = $api_user;
             }
         }
         $this->set_api_cache($filter_user, $api_result_latest_users);
     } catch (Exception $e) {
         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'bbpress', 'API Error during get_api_user() : ' . $e->getMessage());
     }
     return isset($api_result_latest_users[$wp_user_id]) ? $api_result_latest_users[$wp_user_id] : false;
 }
 public function run_cron($debug = false)
 {
     // we pull in the buyer/sales API results so we can link these up with item comments to determine if a buyer has purchase the item or not
     // this is the only reliable way to do this because no purchase information is available via the comments API search
     // hopefully they include some "has purchased" or "is supported" information in the comments search so we can speed things up a little bit.
     $this->update('last_checked', time());
     $this->update_author_sale_history($debug, false);
     // confirm the token every so often.
     $last_token_confirmation = $this->get('last_token_refresh');
     if (!$last_token_confirmation || $last_token_confirmation < time() - 86400) {
         if (!$this->confirm_token()) {
             SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'envato', 'Cookie Error: Failed to confirm Envato account cookie. The cookie must have expired. Please put a new cookie into the settings area.');
         }
         $this->save_account_data(array('last_token_refresh', time()));
     }
 }
 public function run_cron($debug = false)
 {
     if ($debug) {
         echo "Starting ucm Cron Job \n";
     }
     $accounts = $this->get_accounts();
     foreach ($accounts as $account) {
         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'Running Cron Job On Account: ' . $account['shub_account_id']);
         $shub_ucm_account = new shub_ucm_account($account['shub_account_id']);
         $shub_ucm_account->run_cron($debug);
         $products = $shub_ucm_account->get('items');
         /* @var $products shub_ucm_item[] */
         foreach ($products as $product) {
             SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'ucm', 'Running Cron Job On Item: ' . $product->get('shub_item_id'));
             $product->run_cron($debug);
         }
     }
     if ($debug) {
         echo "Finished ucm Cron Job \n";
     }
 }
 public function single_row($item)
 {
     switch ($this->layout_type) {
         case 'continuous':
         case 'inline':
             if (is_array($item) && !empty($item['shub_extension']) && ($message_manager = SupportHub::getInstance()->message_managers[$item['shub_extension']])) {
                 echo '<div class="shub_extension_message_action"><div class="action_content"></div></div>';
                 echo '<div';
                 echo ' class="shub_extension_message"';
                 echo ' data-network="' . $message_manager->id . '"';
                 echo ' data-message-id="' . $item['shub_message_id'] . '"';
                 echo '>';
                 // show the same content from output_message_page() page from the modal popup, but give it a minimal view so it doesn't look too cluttered on the page
                 $message = $message_manager->get_message(false, false, $item['shub_message_id']);
                 $message->output_message_page('inline');
                 echo '</div>';
             } else {
                 echo '<hr>';
                 echo 'Invalid item. Please report bug to dtbaker. <br>';
                 print_r($item);
                 echo '<hr>';
             }
             break;
         default:
             echo '<tr class="shub_extension_message_action"><td class="action_content" colspan="' . $this->get_column_count() . '"></td></tr>';
             echo '<tr';
             if (is_array($item) && !empty($item['shub_extension']) && ($message_manager = SupportHub::getInstance()->message_managers[$item['shub_extension']])) {
                 echo ' class="shub_extension_message ';
                 echo $this->row_count++ % 2 ? 'alternate' : '';
                 echo ' "';
                 echo ' data-network="' . $message_manager->id . '"';
                 echo ' data-message-id="' . $item['shub_message_id'] . '"';
             }
             echo '>';
             $this->single_row_columns($item);
             echo '</tr>';
             break;
     }
 }
 public function send_queued($force = false)
 {
     if ($this->shub_outbox_id) {
         // check the status of it.
         // todo - find any ones that are stuck in 'SENDING' status for too long and send those as well.
         if ($force || $this->get('shub_status') == _SHUB_OUTBOX_STATUS_QUEUED) {
             $managers = SupportHub::getInstance()->message_managers;
             if (!empty($this->shub_extension) && isset($managers[$this->shub_extension]) && $managers[$this->shub_extension]->is_enabled()) {
                 // find the message manager responsible for this message and fire off the reply.
                 $message = $managers[$this->shub_extension]->get_message(false, false, $this->shub_message_id);
                 if ($message->get('shub_message_id') == $this->shub_message_id) {
                     SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'sending', 'Starting Send: ' . $this->shub_message_id);
                     // todo: look at adding a better "lock" so we don't sent duplicate messages between the QUEUE/SENDING get/update
                     $this->update('shub_status', _SHUB_OUTBOX_STATUS_SENDING);
                     // sweet! we're here, send the reply.
                     ob_start();
                     $status = $message->send_queued_comment_reply($this->shub_message_comment_id, $this, true);
                     $errors = ob_get_clean();
                     if ($status) {
                         // success! it worked! flag it as sent.
                         // todo: remove from this table? not sure.
                         $this->update('shub_status', _SHUB_OUTBOX_STATUS_SENT);
                     } else {
                         $this->update('shub_status', _SHUB_OUTBOX_STATUS_FAILED);
                         SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_ERROR, 'sending', 'Failed to Send: ' . $this->shub_message_id . ': error: ' . $errors);
                     }
                     SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'sending', 'Finished Send: ' . $this->shub_message_id);
                     return $errors;
                 }
             }
         }
     }
     return false;
 }
    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 output_message_page($type = 'inline')
    {
        $message_id = $this->get('shub_message_id');
        if ($message_id && $this->get('shub_account_id')) {
            if ('popup' == $type) {
                $this->mark_as_read();
            }
            // icon for this account.
            $icons = SupportHub::getInstance()->message_managers[$this->network]->get_friendly_icon('shub_message_account_icon');
            // icon for the linked product
            $shub_product_id = $this->get_product_id();
            $product_data = array();
            $item_data = array();
            $bbpress_item = $this->get('item');
            if (!$shub_product_id && $bbpress_item) {
                $shub_product_id = $bbpress_item->get('shub_product_id');
                $item_data = $bbpress_item->get('item_data');
                if (!is_array($item_data)) {
                    $item_data = array();
                }
            }
            if ($shub_product_id) {
                $shub_product = new SupportHubProduct();
                $shub_product->load($shub_product_id);
                $product_data = $shub_product->get('product_data');
            }
            if ($shub_product_id && !empty($product_data['image'])) {
                if (!empty($product_data['url'])) {
                    $icons .= '<a href="' . esc_attr($product_data['url']) . '" target="_blank">';
                }
                $icons .= '<img src="' . esc_attr($product_data['image']) . '" class="shub_message_account_icon">';
                if (!empty($product_data['url'])) {
                    $icons .= '</a>';
                }
            }
            ?>

            <div class="message_edit_form" data-network="<?php 
            echo $this->network;
            ?>
">
                <section class="message_sidebar">
                    <nav>
                        <?php 
            if ($this->get('shub_status') == _shub_MESSAGE_STATUS_ANSWERED) {
                ?>
                            <a href="#" class="shub_message_action btn btn-default btn-xs button shub_button_loading"
                               data-action="set-unanswered" data-post="<?php 
                echo esc_attr(json_encode(array('network' => $this->network, 'shub_message_id' => $message_id, 'last_activity' => $this->get('last_active'))));
                ?>
"><?php 
                _e('Inbox');
                ?>
</a>
                        <?php 
            } else {
                ?>
                            <a href="#" class="shub_message_action btn btn-default btn-xs button shub_button_loading"
                               data-action="set-answered" data-post="<?php 
                echo esc_attr(json_encode(array('network' => $this->network, 'shub_message_id' => $message_id, 'last_activity' => $this->get('last_active'))));
                ?>
"><?php 
                _e('Archive');
                ?>
</a>
                        <?php 
            }
            ?>
                        <span class="responsive_sidebar_summary">
                        <?php 
            echo $icons;
            // todo - what other details need to show in mobile view?
            ?>
                        </span>

                        <a href="#" class="shub_view_full_message_sidebar btn btn-default btn-xs button alignright"><?php 
            _e('More Details');
            ?>
</a>
                    </nav>
                    <header>
                        <a href="<?php 
            echo $this->get_link();
            ?>
" class="social_view_external btn btn-default btn-xs button" target="_blank"><?php 
            _e('View Comment');
            ?>
</a>
                        <?php 
            if ($this->get('shub_status') == _shub_MESSAGE_STATUS_ANSWERED) {
                ?>
                            <a href="#" class="shub_message_action btn btn-default btn-xs button shub_button_loading"
                               data-action="set-unanswered" data-post="<?php 
                echo esc_attr(json_encode(array('network' => $this->network, 'shub_message_id' => $message_id, 'last_activity' => $this->get('last_active'))));
                ?>
"><?php 
                _e('Inbox');
                ?>
</a>
                        <?php 
            } else {
                ?>
                            <a href="#" class="shub_message_action btn btn-default btn-xs button shub_button_loading"
                               data-action="set-answered" data-post="<?php 
                echo esc_attr(json_encode(array('network' => $this->network, 'shub_message_id' => $message_id, 'last_activity' => $this->get('last_active'))));
                ?>
"><?php 
                _e('Archive');
                ?>
</a>
                        <?php 
            }
            ?>
                    </header>
                    <aside class="message_sidebar">
                        <?php 
            echo $icons;
            echo '<br/>';
            // this method does all the magic of getting the linked user ids and other messages
            $data = $this->get_message_sidebar_data($product_data, $item_data);
            if (!empty($data['message_details'])) {
                ?>
                            <div class="message_sidebar_details">
                            <?php 
                foreach ($data['message_details'] as $message_details) {
                    ?>
                                <div>
                                    <strong><?php 
                    echo htmlspecialchars($message_details[0]);
                    ?>
:</strong>
                                    <?php 
                    echo $message_details[1];
                    ?>
                                </div>
                                <?php 
                }
                ?>
                            </div>
                            <?php 
            }
            if (!empty($data['extra_datas'])) {
                ?>
                            <div class="message_sidebar_extra_data">
                            <?php 
                foreach ($data['extra_datas'] as $extra_data) {
                    if (isset($extras[$extra_data->get('shub_extra_id')])) {
                        ?>
                                    <div>
                                        <strong><?php 
                        echo htmlspecialchars($extras[$extra_data->get('shub_extra_id')]->get('extra_name'));
                        ?>
:</strong>
                                        <?php 
                        switch ($extras[$extra_data->get('shub_extra_id')]->get('field_type')) {
                            case 'encrypted':
                                echo '(encrypted)';
                                break;
                            default:
                                echo shub_forum_text($extra_data->get('extra_value'), false);
                        }
                        ?>
                                    </div>
                                    <?php 
                    }
                }
                ?>
                            </div>
                            <?php 
            }
            if (!empty($data['user_bits'])) {
                ?>
                            <ul class="linked_user_details"> <?php 
                foreach ($data['user_bits'] as $user_bit) {
                    ?>
                                    <li><strong><?php 
                    echo $user_bit[0];
                    ?>
:</strong> <?php 
                    echo $user_bit[1];
                    ?>
</li>
                                    <?php 
                }
                ?>
                            </ul>
                            <?php 
            }
            if (!empty($data['other_messages'])) {
                ?>
                            <div class="shub_other_messages">
                                <strong><?php 
                echo sprintf(_n('%d Other Message:', '%d Other Messages:', count($data['other_messages']), 'support_hub'), count($data['other_messages']));
                ?>
</strong><br/>
                                <ul>
                                    <?php 
                foreach ($data['other_messages'] as $other_message) {
                    ?>
                                        <li>
                                            <span class="other_message_time"><?php 
                    echo shub_pretty_date($other_message['time']);
                    ?>
</span>
                                            <span class="other_message_status"><?php 
                    if (isset($other_message['message_status'])) {
                        switch ($other_message['message_status']) {
                            case _shub_MESSAGE_STATUS_ANSWERED:
                                echo '<span class="message_status_archived">Archived</span>';
                                break;
                            case _shub_MESSAGE_STATUS_UNANSWERED:
                                echo '<span class="message_status_inbox">Inbox</span>';
                                break;
                            case _shub_MESSAGE_STATUS_HIDDEN:
                                echo '<span class="message_status_hidden">Hidden</span>';
                                break;
                            default:
                                echo 'UNKNOWN?';
                        }
                    }
                    ?>
                                            </span>
                                            <span class="other_message_network">
                                                <?php 
                    echo $other_message['icon'];
                    ?>
                                            </span>
                                            <br/>
                                            <a href="<?php 
                    echo esc_attr($other_message['link']);
                    ?>
" target="_blank" class="shub_modal"
                                               data-network="<?php 
                    echo esc_attr($other_message['network']);
                    ?>
"
                                               data-message_id="<?php 
                    echo (int) $other_message['message_id'];
                    ?>
"
                                               data-message_comment_id="<?php 
                    echo isset($other_message['message_comment_id']) ? (int) $other_message['message_comment_id'] : '';
                    ?>
"
                                               data-modaltitle="<?php 
                    echo esc_attr($other_message['summary']);
                    ?>
"><?php 
                    echo esc_html($other_message['summary']);
                    ?>
</a>
                                        </li>
                                        <?php 
                }
                ?>
                                </ul>
                                </div>
                            <?php 
            }
            do_action('supporthub_message_header', $this->network, $this);
            ?>

                    </aside>
                </section>
                <section class="message_content">
                    <?php 
            // we display the first "primary" message (from the ucm_message table) followed by comments from the ucm_message_comment table.
            //$this->full_message_output(true);
            $this->output_message_list();
            ?>
                </section>
                <section class="message_request_extra">
                    <?php 
            SupportHubExtra::form_request_extra(array('network' => $this->network, 'account-id' => $this->get('shub_account_id'), 'message-id' => $message_id));
            ?>
                </section>
            </div>

        <?php 
        }
    }
Exemple #23
0
<div class="wrap">
	<h2>
		<?php 
_e('Support Hub Settings', 'support_hub');
?>
	</h2>
	<?php 
// find out what tab we're on.
// is it the main tab or one of the individual plugin settings pages.
$SupportHub = SupportHub::getInstance();
$tab = isset($_REQUEST['tab']) ? $_REQUEST['tab'] : false;
?>
	<h2 class="nav-tab-wrapper woo-nav-tab-wrapper">
		<a href="?page=support_hub_settings" class="nav-tab <?php 
echo !$tab ? ' nav-tab-active' : '';
?>
"><?php 
_e('General', 'support_hub');
?>
</a>
		<a href="?page=support_hub_settings&amp;tab=products" class="nav-tab <?php 
echo $tab == 'products' ? ' nav-tab-active' : '';
?>
"><?php 
_e('Products', 'support_hub');
?>
</a>
		<a href="?page=support_hub_settings&amp;tab=extra" class="nav-tab <?php 
echo $tab == 'extra' ? ' nav-tab-active' : '';
?>
"><?php 
 public function load_by_network_key($network_key, $message_data, $type, $debug = false)
 {
     switch ($type) {
         case 'item_comment':
             $existing = shub_get_single('shub_message', 'network_key', $network_key);
             if ($existing) {
                 // load it up.
                 $this->load($existing['shub_message_id']);
             }
             if ($message_data && isset($message_data['id']) && $message_data['id'] == $network_key) {
                 if (!$existing) {
                     $this->create_new();
                 }
                 $this->update('shub_account_id', $this->account->get('shub_account_id'));
                 $this->update('shub_item_id', $this->item->get('shub_item_id'));
                 $comments = $message_data['conversation'];
                 $this->update('title', $comments[0]['content']);
                 $this->update('summary', $comments[count($comments) - 1]['content']);
                 $this->update('last_active', strtotime($message_data['last_comment_at']));
                 $this->update('shub_type', $type);
                 $this->update('shub_data', $message_data);
                 $this->update('shub_link', $message_data['url'] . '/' . $message_data['id']);
                 $this->update('network_key', $network_key);
                 SupportHub::getInstance()->log_data(_SUPPORT_HUB_LOG_INFO, 'envato', 'Updating message ' . $network_key . ' from API.', array('Current Comment Count: ' => count($this->get_comments()), 'New Comment Count: ' => count($comments), 'Current Status: ' => $this->get('shub_status')));
                 if ($this->get('shub_status') != _shub_MESSAGE_STATUS_HIDDEN) {
                     // we have to decide if we're updating the message status from answered to unanswered.
                     // if this message status is already answered and the existing comment count matches the new comment count then we don't update the status
                     // this is because we insert a placeholder "comment" into the db while the API does the push, and when we read again a few minutes later it overwrites this placeholder comment, so really it's not a new comment coming in just the one we posted through the API that takes a while to come back through.
                     if ($this->get('shub_status') == _shub_MESSAGE_STATUS_ANSWERED && count($comments) == count($this->get_comments())) {
                         // don't do anything
                     } else {
                         // comment count is different
                         $this->update('shub_status', _shub_MESSAGE_STATUS_UNANSWERED);
                     }
                 }
                 $this->update('comments', $comments);
                 // create/update a user entry for this comments.
                 $shub_user_id = 0;
                 $first_comment = current($comments);
                 if (!empty($first_comment['username'])) {
                     $comment_user = new SupportHubUser_Envato();
                     $res = $comment_user->load_by('envato_username', $first_comment['username']);
                     if (!$res) {
                         $res = $comment_user->load_by('user_username', $first_comment['username']);
                         if (!$res) {
                             $comment_user->create_new();
                         }
                     }
                     if (!$comment_user->get('user_username')) {
                         $comment_user->update('user_username', $first_comment['username']);
                     }
                     if (!$comment_user->get('envato_username')) {
                         $comment_user->update('envato_username', $first_comment['username']);
                     }
                     $comment_user->update_user_data(array('image' => $first_comment['profile_image_url'], 'envato' => $first_comment));
                     $shub_user_id = $comment_user->get('shub_user_id');
                 }
                 $this->update('shub_user_id', $shub_user_id);
                 return $existing;
             }
             break;
     }
 }