/**
 * Calls BackType API and parses response
 *
 * @uses	btc_db_comment_counts()
 * @uses	btc_db_dupe_comment()
 * @uses	btc_db_add_comment_type()
 * @uses	btc_db_add_own_blog_comment()
 * @uses	btc_db_add_retweet()
 * @uses	btc_db_set_comment_counts()
 * @uses	btc_db_update_post()
 * @uses	_btc_akismet_check_comment()
 * @uses	_btc_comment_desc()
 * @uses	_btc_filter_content()
 * @uses	_btc_get_filters()
 * @uses	_btc_url_open()
 * @uses	_btc_xml_unserialize()
 *
 * @param	object	$btc_post	Post to call API for
 * @return	array				Status
 */
function _btc_import(&$btc_post)
{
    $filters = _btc_get_filters();
    $page = 1;
    $processed = false;
    $error = 0;
    $url = get_permalink($btc_post->ID);
    $itemsperpage = '25';
    $params = array('identifier' => 'btc', 'url' => $url, 'key' => get_option(BTC_API_KEY_OPTION), 'page' => '1', 'sort' => '1', 'itemsperpage' => $itemsperpage);
    do {
        btc_log('Fetching: ' . BTC_API_CONNECT_URL . '?' . http_build_query($params, null, '&'), 'debug');
        if (!($contents = _btc_url_open(BTC_API_CONNECT_URL . '?' . http_build_query($params, null, '&')))) {
            btc_log('Failed opening url: ' . BTC_API_CONNECT_URL . '?' . http_build_query($params, null, '&'), 'error');
            $error = 1;
            break;
        }
        $xml = _btc_xml_unserialize($contents['body']);
        unset($contents);
        if (class_exists('SimpleXMLElement')) {
            if (!$xml || !empty($xml->errorCode) || empty($xml->comments)) {
                if (!empty($xml->errorCode) && $xml->errorCode == 'related-conversations-not-found' || (int) $xml->totalresults == 0) {
                    $btc_post->last_import_date_gmt = gmdate('Y-m-d H:i:s');
                    $btc_post->misses = (int) $btc_post->misses + 1;
                    btc_db_update_post($btc_post);
                    btc_log('No related conversations.', 'error');
                    $error = 2;
                } else {
                    if ($xml && empty($xml->comments->entry) && (int) $xml->startindex > (int) $xml->totalresults) {
                        btc_log('Paginated too far.', 'error');
                        //..
                    } else {
                        btc_log('Unknown XML error.', 'error');
                        $error = 3;
                    }
                }
                break;
            }
            if (empty($xml->comments->entry) || !count($xml->comments->entry)) {
                btc_log('No comments.', 'debug');
                break;
            }
            require_once BTC_DIR . '/db.php';
            $new = 0;
            btc_log('Comments received: ' . count($xml->comments->entry), 'debug');
            $comments = array();
            $ignore_own_blog = get_option(BTC_IGNORE_OWN_BLOG_OPTION);
            $ignore_retweets = get_option(BTC_IGNORE_RETWEETS_OPTION);
            $siteurl = get_option('siteurl');
            $site_pieces = parse_url($siteurl);
            $site_domain = isset($site_pieces['host']) ? trim($site_pieces['host'], '/') : '';
            $site_path = isset($site_pieces['path']) ? trim($site_pieces['path'], '/') : '';
            foreach ($xml->comments->entry as $entry) {
                if ($entry['type'] == 'comment') {
                    $entry_pieces = parse_url($entry->blog->url);
                    $entry_domain = isset($entry_pieces['host']) ? trim($entry_pieces['host'], '/') : '';
                    $entry_path = isset($entry_pieces['path']) ? trim($entry_pieces['path'], '/') : '';
                    $is_own_blog = $site_domain == $entry_domain && $site_path == $entry_path ? 1 : 0;
                    $is_retweet = 0;
                    $commentdata = array('comment_post_ID' => $btc_post->ID, 'comment_author' => $entry->author->name ? trim($entry->author->name) : 'Anonymous', 'comment_author_email' => '', 'comment_author_url' => trim($entry->author->url), 'comment_author_IP' => '', 'comment_date' => date('Y-m-d H:i:s', strtotime(trim($entry->comment->date)) + get_option('gmt_offset') * 3600), 'comment_date_gmt' => date('Y-m-d H:i:s', strtotime(trim($entry->comment->date))), 'comment_content' => _btc_filter_content($entry->comment->content), 'comment_approved' => $ignore_own_blog && $is_own_blog ? 'ignored' : (get_option(BTC_MODERATION_OPTION) ? '0' : '1'), 'comment_agent' => 'btc_' . $entry['src'], 'comment_type' => '', 'comment_parent' => '');
                    $desc = array('comment_src' => $entry['src'], 'site_url' => trim($entry->blog->url), 'site_title' => trim($entry->blog->title), 'post_url' => trim($entry->post->url), 'post_title' => $entry->post->title ? trim($entry->post->title) : trim($entry->blog->title), 'comment_url' => trim($entry->comment->url));
                } elseif ($entry['type'] == 'tweet') {
                    $is_own_blog = 0;
                    $is_retweet = substr(strtolower($entry->tweet_text), 0, 2) == 'rt' ? 1 : 0;
                    $commentdata = array('comment_post_ID' => $btc_post->ID, 'comment_author' => trim($entry->tweet_from_user), 'comment_author_email' => '', 'comment_author_url' => 'http://twitter.com/' . trim($entry->tweet_from_user), 'comment_author_IP' => '', 'comment_date' => date('Y-m-d H:i:s', strtotime(trim($entry->tweet_created_at)) + get_option('gmt_offset') * 3600), 'comment_date_gmt' => date('Y-m-d H:i:s', strtotime(trim($entry->tweet_created_at))), 'comment_content' => _btc_filter_content($entry->tweet_text), 'comment_approved' => $ignore_retweets && $is_retweet ? 'ignored' : (get_option(BTC_MODERATION_OPTION) ? '0' : '1'), 'comment_agent' => 'btc_twitter', 'comment_type' => '', 'comment_parent' => '');
                    $desc = array('comment_src' => 'twitter', 'site_url' => 'http://twitter.com/', 'site_title' => 'Twitter', 'post_url' => 'http://twitter.com/' . trim($entry->tweet_from_user) . '/statuses/' . $entry->tweet_id, 'post_title' => trim($entry->tweet_text), 'comment_url' => 'http://twitter.com/' . trim($entry->tweet_from_user) . '/statuses/' . $entry->tweet_id);
                }
                $commentdata['comment_content'] .= _btc_comment_desc($desc);
                if (!btc_db_dupe_comment($commentdata)) {
                    if (get_option(BTC_AKISMET_OPTION) && function_exists('akismet_auto_check_comment')) {
                        $commentdata = _btc_akismet_check_comment($commentdata);
                    }
                    if (in_array($desc['comment_src'], $filters['srcs'])) {
                        $commentdata['comment_approved'] = 'd_' . $commentdata['comment_approved'];
                    }
                    if ($comment_ID = wp_insert_comment($commentdata)) {
                        $dupes = btc_db_dupe_clean($comment_ID);
                        if (count($dupes) > 0) {
                            btc_db_delete_dupe_comment($comment_ID);
                            continue;
                        }
                        if ($is_own_blog) {
                            btc_db_add_own_blog_comment($btc_post->ID, $comment_ID);
                        } elseif ($is_retweet) {
                            btc_db_add_retweet($btc_post->ID, $comment_ID);
                        }
                        btc_db_add_comment_type($btc_post->ID, $commentdata['comment_agent'], $comment_ID);
                        $new++;
                    }
                }
            }
            btc_log('Inserted ' . $new . ' new comments.', 'debug');
            // paginate
            if ($new) {
                $btc_post->last_import_date_gmt = gmdate('Y-m-d H:i:s');
                $btc_post->hits = (int) $btc_post->hits + $new;
                btc_db_update_post($btc_post);
                if ($new == (int) $itemsperpage && isset($xml->next_page)) {
                    $params['page'] = (int) $xml->next_page;
                } else {
                    $btc_counts = btc_db_comment_counts($btc_post->ID);
                    btc_db_set_comment_counts($btc_post->ID, $btc_counts);
                    if (function_exists('wp_update_comment_count')) {
                        wp_update_comment_count($btc_post->ID);
                    }
                    $btc_summary = btc_db_comment_summary($btc_post->ID);
                    btc_db_set_comment_summary($btc_post->ID, $btc_summary);
                    $processed = true;
                }
            } else {
                $btc_post->last_import_date_gmt = gmdate('Y-m-d H:i:s');
                $btc_post->misses = (int) $btc_post->misses + 1;
                btc_db_update_post($btc_post);
                $processed = true;
            }
        } else {
            if (!$xml || !empty($xml['error']['errorCode']) || empty($xml['feed']['comments'])) {
                if (!empty($xml['error']['errorCode']) && $xml['error']['errorCode'] == 'related-conversations-not-found') {
                    $btc_post->last_import_date_gmt = gmdate('Y-m-d H:i:s');
                    $btc_post->misses = (int) $btc_post->misses + 1;
                    btc_db_update_post($btc_post);
                    btc_log('No related conversations.', 'error');
                    $error = 2;
                } else {
                    if ($xml && empty($xml['feed']['comments']['entry']) && (int) $xml['feed']['startindex'] > (int) $xml['feed']['totalresults']) {
                        btc_log('Paginated too far.', 'error');
                        //..
                    } else {
                        btc_log('Unknown XML error.', 'error');
                        $error = 3;
                    }
                }
                break;
            }
            if (empty($xml['feed']['comments']['entry']) || !count($xml['feed']['comments']['entry'])) {
                btc_log('No comments.', 'debug');
                break;
            }
            require_once BTC_DIR . '/db.php';
            $new = 0;
            btc_log('Comments received: ' . count($xml['feed']['comments']['entry']), 'debug');
            $comments = array();
            $ignore_own_blog = get_option(BTC_IGNORE_OWN_BLOG_OPTION);
            $ignore_retweets = get_option(BTC_IGNORE_RETWEETS_OPTION);
            $siteurl = get_option('siteurl');
            $site_pieces = parse_url($siteurl);
            $site_domain = isset($site_pieces['host']) ? trim($site_pieces['host'], '/') : '';
            $site_path = isset($site_pieces['path']) ? trim($site_pieces['path'], '/') : '';
            foreach ($xml['feed']['comments']['entry'] as $key => $value) {
                if (is_int($key)) {
                    $entry = $value;
                    $entry['type'] = $type;
                    $entry['src'] = $src;
                } else {
                    $type = $value['type'];
                    $src = isset($value['src']) ? $value['src'] : '';
                    continue;
                }
                if ($entry['type'] == 'comment') {
                    $entry_pieces = parse_url($entry['blog']['url']);
                    $entry_domain = isset($entry_pieces['host']) ? trim($entry_pieces['host'], '/') : '';
                    $entry_path = isset($entry_pieces['path']) ? trim($entry_pieces['path'], '/') : '';
                    $is_own_blog = $site_domain == $entry_domain && $site_path == $entry_path ? 1 : 0;
                    $is_retweet = 0;
                    $commentdata = array('comment_post_ID' => $btc_post->ID, 'comment_author' => $entry['author']['name'] ? trim($entry['author']['name']) : 'Anonymous', 'comment_author_email' => '', 'comment_author_url' => trim($entry['author']['url']), 'comment_author_IP' => '', 'comment_date' => date('Y-m-d H:i:s', strtotime(trim($entry['comment']['date'])) + get_option('gmt_offset') * 3600), 'comment_date_gmt' => date('Y-m-d H:i:s', strtotime(trim($entry['comment']['date']))), 'comment_content' => _btc_filter_content($entry['comment']['content']), 'comment_approved' => $ignore_own_blog && $is_own_blog ? 'ignored' : (get_option(BTC_MODERATION_OPTION) ? '0' : '1'), 'comment_agent' => 'btc_' . $entry['src'], 'comment_type' => '', 'comment_parent' => '');
                    $desc = array('comment_src' => $entry['src'], 'site_url' => trim($entry['blog']['url']), 'site_title' => trim($entry['blog']['title']), 'post_url' => trim($entry['post']['url']), 'post_title' => $entry['post']['title'] ? trim($entry['post']['title']) : trim($entry['blog']['title']), 'comment_url' => trim($entry['comment']['url']));
                } elseif ($entry['type'] == 'tweet') {
                    $is_own_blog = 0;
                    $is_retweet = substr(strtolower($entry['tweet_text']), 0, 2) == 'rt' ? 1 : 0;
                    $commentdata = array('comment_post_ID' => $btc_post->ID, 'comment_author' => trim($entry['tweet_from_user']), 'comment_author_email' => '', 'comment_author_url' => 'http://twitter.com/' . trim($entry['tweet_from_user']), 'comment_author_IP' => '', 'comment_date' => date('Y-m-d H:i:s', strtotime(trim($entry['tweet_created_at'])) + get_option('gmt_offset') * 3600), 'comment_date_gmt' => date('Y-m-d H:i:s', strtotime(trim($entry['tweet_created_at']))), 'comment_content' => _btc_filter_content($entry['tweet_text']), 'comment_approved' => $ignore_retweets && $is_retweet ? 'ignored' : (get_option(BTC_MODERATION_OPTION) ? '0' : '1'), 'comment_agent' => 'btc_twitter', 'comment_type' => '', 'comment_parent' => '');
                    $desc = array('comment_src' => 'twitter', 'site_url' => 'http://twitter.com/', 'site_title' => 'Twitter', 'post_url' => 'http://twitter.com/' . trim($entry['tweet_from_user']) . '/statuses/' . $entry['tweet_id'], 'post_title' => trim($entry['tweet_text']), 'comment_url' => 'http://twitter.com/' . trim($entry['tweet_from_user']) . '/statuses/' . $entry['tweet_id']);
                }
                $commentdata['comment_content'] .= _btc_comment_desc($desc);
                if (!btc_db_dupe_comment($commentdata)) {
                    if (get_option(BTC_AKISMET_OPTION) && function_exists('akismet_auto_check_comment')) {
                        $commentdata = _btc_akismet_check_comment($commentdata);
                    }
                    if (in_array($desc['comment_src'], $filters['srcs'])) {
                        $commentdata['comment_approved'] = 'd_' . $commentdata['comment_approved'];
                    }
                    if ($comment_ID = wp_insert_comment($commentdata)) {
                        $dupes = btc_db_dupe_comment($commentdata);
                        if (count($dupes) > 1 && $comment_ID > min($dupes)) {
                            btc_db_delete_dupe_comment($comment_ID);
                            continue;
                        }
                        if ($is_own_blog) {
                            btc_db_add_own_blog_comment($btc_post->ID, $comment_ID);
                        } elseif ($is_retweet) {
                            btc_db_add_retweet($btc_post->ID, $comment_ID);
                        }
                        btc_db_add_comment_type($btc_post->ID, $commentdata['comment_agent'], $comment_ID);
                        $new++;
                    }
                }
            }
            btc_log('Inserted ' . $new . ' new comments.', 'debug');
            // paginate
            if ($new) {
                $btc_post->last_import_date_gmt = gmdate('Y-m-d H:i:s');
                $btc_post->hits = (int) $btc_post->hits + $new;
                btc_db_update_post($btc_post);
                if ($new == (int) $itemsperpage && isset($xml['feed']['next_page'])) {
                    $params['page'] = (int) $xml['feed']['next_page'];
                } else {
                    $btc_counts = btc_db_comment_counts($btc_post->ID);
                    btc_db_set_comment_counts($btc_post->ID, $btc_counts);
                    if (function_exists('wp_update_comment_count')) {
                        wp_update_comment_count($btc_post->ID);
                    }
                    $btc_summary = btc_db_comment_summary($btc_post->ID);
                    btc_db_set_comment_summary($btc_post->ID, $btc_summary);
                    $processed = true;
                }
            } else {
                $btc_post->last_import_date_gmt = gmdate('Y-m-d H:i:s');
                $btc_post->misses = (int) $btc_post->misses + 1;
                btc_db_update_post($btc_post);
                $processed = true;
            }
        }
    } while (!$processed && !$error);
    if (!$error) {
        return array('success' => 1);
    } else {
        if ($error == 1) {
            if ($page == 1) {
                return array('success' => 0, 'message' => 'Could not open the URL.');
            } else {
                return array('success' => 0, 'message' => 'Could not open some of the URLs.');
            }
        } else {
            if ($error == 2) {
                return array('success' => 0, 'message' => 'No related conversations were found.');
            } else {
                return array('success' => 0, 'message' => 'An unknown error occurred.');
            }
        }
    }
}
<?php

global $post;
require_once BTC_DIR . '/db.php';
if (($btc_summary = btc_db_get_comment_summary($post->ID)) === false) {
    $btc_summary = btc_db_comment_summary($post->ID);
    btc_db_set_comment_summary($post->ID, $btc_summary);
}
if ($btc_summary) {
    $summary_html = '';
    if ($btc_summary[0]->comment_src == 'blog') {
        array_push($btc_summary, array_shift($btc_summary));
    }
    if ($src = array_shift($btc_summary)) {
        $plural = $src->cnt != 1 ? 's' : '';
        $summary_html .= ' <img src="' . WP_PLUGIN_URL . '/backtype-connect/images/' . $src->comment_src . '-16.gif" alt=""/> <a href="http://www.backtype.com/connect/' . _btc_url_encode(get_permalink($post->ID));
        $summary_html .= $src->comment_src == 'twitter' ? '/tweets" title="' . $src->cnt . ' tweet' . $plural . ' on ' . $src->comment_src . '">' . $src->cnt . ' Tweet' : '?src=' . $src->comment_src . '" title="' . $src->cnt . ' comment' . $plural . ' on ' . ($src->comment_src == 'blog' ? 'other sites' : $src->comment_src) . '">' . $src->cnt . ($src->comment_src == 'blog' ? ' Other' : '') . ' Comment';
        $summary_html .= $plural . '</a>';
    }
    foreach ($btc_summary as $src) {
        $plural = $src->cnt != 1 ? 's' : '';
        $summary_html .= ' <img src="' . WP_PLUGIN_URL . '/backtype-connect/images/' . $src->comment_src . '-16.gif" style="margin-left:1em" alt=""/> <a href="http://www.backtype.com/connect/' . _btc_url_encode(get_permalink($post->ID));
        $summary_html .= $src->comment_src == 'twitter' ? '/tweets" title="' . $src->cnt . ' tweet' . $plural . ' on ' . $src->comment_src . '">' . $src->cnt . ' Tweet' : '?src=' . $src->comment_src . '" title="' . $src->cnt . ' comment' . $plural . ' on ' . ($src->comment_src == 'blog' ? 'other sites' : $src->comment_src) . '">' . $src->cnt . ($src->comment_src == 'blog' ? ' Other' : '') . ' Comment';
        $summary_html .= $plural . '</a>';
    }
    echo '<p class="btc-summary">' . $summary_html . '</p>';
}
if (file_exists(STYLESHEETPATH . $file)) {
    require STYLESHEETPATH . $file;
} elseif (file_exists(TEMPLATEPATH . $file)) {
    require TEMPLATEPATH . '/comments.php';