コード例 #1
0
function ozh_ta_do_page_manual()
{
    ?>
	<fieldset class="ozh_ta_fs">
	<h3>Manual archiving</h3>
	<?php 
    if (!ozh_ta_is_manually_archiving()) {
        ?>
		<p>Manually archive your tweets as posts into WordPress. Once this is done, the import will be set to <strong>automatic</strong>, as per the refresh interval defined.</p>
		<p>If this is the first time you do it and you have lots of tweets to import, this will be longish. Don't close this page till it says "all done"! If the script timeouts or goes moo in the middle of an import, just refresh the page</p>
		<?php 
        $url = wp_nonce_url(admin_url('options-general.php?page=ozh_ta&action=import_all&time=' . time()), 'ozh_ta-import_all');
        ?>
		<p><a href="<?php 
        echo $url;
        ?>
" class="button">Manually archive now</a></p>

	<?php 
    } else {
        check_admin_referer('ozh_ta-import_all');
        // Import the goodness
        ozh_ta_require('import.php');
        ozh_ta_schedule_next(0);
        // clear any scheduling : it'll be rescheduled after all tweets have been imported
        ozh_ta_get_tweets(true);
    }
    echo '</fieldset>';
}
コード例 #2
0
/**
 * Poll Twitter API and get tweets
 *
 * @param  bool $echo  True to output results and redirect page (ie called from option page)
 * @return bool        false if error while polling Twitter, true otherwise
 */
function ozh_ta_get_tweets($echo = false)
{
    global $ozh_ta;
    if (!ozh_ta_is_configured()) {
        ozh_ta_debug('Config incomplete, cannot import tweets');
        return false;
    }
    $api = add_query_arg(array('count' => OZH_TA_BATCH, 'page' => $ozh_ta['api_page'], 'screen_name' => urlencode($ozh_ta['screen_name']), 'since_id' => $ozh_ta['last_tweet_id_inserted']), OZH_TA_API);
    ozh_ta_debug("Polling {$api}");
    $headers = array('Authorization' => 'Bearer ' . $ozh_ta['access_token']);
    ozh_ta_debug("Headers: " . json_encode($headers));
    $response = wp_remote_get($api, array('headers' => $headers, 'timeout' => 10));
    $tweets = wp_remote_retrieve_body($response);
    $ratelimit = wp_remote_retrieve_header($response, 'x-rate-limit-limit');
    $ratelimit_r = wp_remote_retrieve_header($response, 'x-rate-limit-remaining');
    $status = wp_remote_retrieve_response_code($response);
    ozh_ta_debug("API status: {$status}");
    ozh_ta_debug("API rate: {$ratelimit_r}/{$ratelimit}");
    /**
     * Something to check when Twitter update their API :
     *
     * Currently, when you try to retrieve more tweets than available (either you already have fetched 3200, or you
     * have fetched them all), the API returns no particular error: status 200, just an empty body.
     * In the future, check if they change this and return a particular message or status code
     */
    // Fail Whale or other error
    if (!$tweets or $status != 200) {
        // 401 : Unauthorized
        if ($status == 401) {
            ozh_ta_debug('Could not fetch tweets: unauthorized access.');
            if ($echo) {
                wp_die('<p>Twitter returned an "Unauthorized" error. Check your consumer key and secret!</p>');
            } else {
                // TODO: what to do in such a case? Better not to silently die and do nothing.
                // Email blog admin ?
                return false;
            }
        }
        // 419 : Rate limit exceeded
        // 5xx : Fail whale
        ozh_ta_debug('Twitter fail, retry in ' . OZH_TA_NEXT_FAIL);
        // Context: from option page
        if ($echo) {
            $url = wp_nonce_url(admin_url('options-general.php?page=ozh_ta&action=import_all&time=' . time()), 'ozh_ta-import_all');
            ozh_ta_reload($url, OZH_TA_NEXT_FAIL);
            wp_die('<p>Twitter is over capacity. This page will refresh in ' . OZH_TA_NEXT_FAIL . ' seconds. Please wait this delay to avoid a ban.</p>');
            // Context: from cron
        } else {
            // schedule same operation later
            ozh_ta_schedule_next(OZH_TA_NEXT_FAIL);
            return false;
        }
    }
    // No Fail Whale, let's import
    // Legacy note:
    // We used to have to fix integers in the JSON response to have them handled as strings and not integers,
    // to avoid having tweet ID 438400650846928897 interpreted as 4.34343e15
    // $tweets = preg_replace( '/"\s*:\s*([\d]+)\s*([,}{])/', '": "$1"$2', $tweets );
    // This isn't needed anymore since, smartly, Twitter's API returns both an id and an id_str. Nice, Twitter :)
    $tweets = array_reverse((array) json_decode($tweets));
    // Tweets found, let's archive
    if ($tweets) {
        if (ozh_ta_is_debug()) {
            $overall = new ozh_ta_query_count();
        }
        $results = ozh_ta_insert_tweets($tweets, true);
        // array( inserted, skipped, tagged, num_tags, (array)$user );
        // Increment api_page and update user info
        $ozh_ta['twitter_stats'] = array_merge($ozh_ta['twitter_stats'], $results['user']);
        $ozh_ta['api_page']++;
        update_option('ozh_ta', $ozh_ta);
        ozh_ta_debug("Twitter OK, imported {$results['inserted']}, skipped {$results['skipped']}, tagged {$results['tagged']} with {$results['num_tags']} tags, next in " . OZH_TA_NEXT_SUCCESS);
        if (ozh_ta_is_debug()) {
            ozh_ta_debug('Total queries: ' . $overall->stop());
        }
        // Context: option page
        if ($echo) {
            echo "<p>Tweets inserted: <strong>{$results['inserted']}</strong></p>";
            $url = wp_nonce_url(admin_url('options-general.php?page=ozh_ta&action=import_all&time=' . time()), 'ozh_ta-import_all');
            ozh_ta_reload($url, OZH_TA_NEXT_SUCCESS);
            // Context: from cron
        } else {
            // schedule next operation soon
            ozh_ta_schedule_next(OZH_TA_NEXT_SUCCESS);
        }
        // No tweets found
    } else {
        global $wpdb;
        // Schedule next operation
        ozh_ta_schedule_next($ozh_ta['refresh_interval']);
        ozh_ta_debug("Twitter finished, next in {$ozh_ta['refresh_interval']}");
        // Update last_tweet_id_inserted, stats, & reset API paging
        $ozh_ta['api_page'] = 1;
        $ozh_ta['last_tweet_id_inserted'] = $wpdb->get_var("SELECT `meta_value` FROM `{$wpdb->postmeta}` WHERE `meta_key` = 'ozh_ta_id' ORDER BY ABS(`meta_value`) DESC LIMIT 1");
        // order by ABS() because they are strings in the DB
        $ozh_ta['twitter_stats']['link_count'] = $wpdb->get_var("SELECT COUNT(ID) FROM `{$wpdb->posts}` WHERE `post_type` = 'post' AND `post_status` = 'publish' AND `post_content` LIKE '%class=\"link%'");
        $ozh_ta['twitter_stats']['replies'] = $wpdb->get_row("SELECT COUNT( DISTINCT `meta_value`) as unique_names, COUNT( `meta_value`) as total FROM `{$wpdb->postmeta}` WHERE `meta_key` = 'ozh_ta_reply_to_name'", ARRAY_A);
        $ozh_ta['twitter_stats']['total_archived'] = $wpdb->get_var("SELECT COUNT(`meta_key`) FROM `{$wpdb->postmeta}` WHERE `meta_key` = 'ozh_ta_id'");
        update_option('ozh_ta', $ozh_ta);
        // Context: option page
        if ($echo) {
            echo '<p>Finished importing tweets! Automatic archiving now scheduled.</p>';
            echo '<p><a href="' . menu_page_url('ozh_ta', false) . '" class="button">Return to plugin config</a></p>';
        }
    }
    return true;
}
コード例 #3
0
ファイル: settings.php プロジェクト: kw217/ozh-tweet-archiver
function ozh_ta_validate_options($input)
{
    global $ozh_ta;
    // Screw validation. Just don't be an idiot.
    // Reset if applicable
    if (isset($_POST['delete_btn'])) {
        $input = array();
        ozh_ta_schedule_next(0);
    } else {
        // don't lose stuff that are not "settings" submitted in the plugin page
        $input = array_merge($ozh_ta, $input);
        // Consumer key & secret defined? Get an OAuth token
        if (isset($input['cons_key']) && isset($input['cons_secret']) && !ozh_ta_is_manually_archiving()) {
            $input['access_token'] = ozh_ta_get_token($input['cons_key'], $input['cons_secret']);
        }
    }
    return $input;
}