Plugin Directory

Changeset 790774


Ignore:
Timestamp:
10/20/2013 06:50:57 AM (12 years ago)
Author:
mobius5150
Message:

Got twitter request signing working again.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • globalfeed/trunk/feeds/mb_twitter/mb_twitter.php

    r715356 r790774  
    4040     * @var str
    4141     */
    42     private $feed_name = 'Twitter Connect';
     42    protected $feed_name = 'Twitter Connect';
    4343   
    4444    /**
     
    4747     * @var str
    4848     */
    49     private $feed_slug = 'twitter_connect';
    50    
    51     private $feed_version = '0.1.3';
     49    protected $feed_slug = 'twitter_connect';
     50   
     51    protected $feed_version = '0.1.3';
    5252   
    5353    /**
     
    5656     * @var str
    5757     */
    58     private $feed_type = 'request';
     58    protected $feed_type = 'request';
    5959   
    6060    /**
     
    6262     * @var boolean
    6363     */
    64     private $auto_interupt_flow = true;
     64    protected $auto_interupt_flow = true;
    6565   
    6666    /**
     
    6969     * @var array
    7070     */
    71     private $pages_to_show = array(
     71    protected $pages_to_show = array(
    7272        'all' => 'all'
    7373    );
     
    7777     * @var array
    7878     */
    79     private $pages_not_to_show = array(
     79    protected $pages_not_to_show = array(
    8080       
    8181    );
     
    8585     * @var type
    8686     */
    87     private $globalfeed;
     87    protected $globalfeed;
    8888   
    8989    private $_apiurl = 'http://api.twitter.com/1/';
     
    9696       
    9797        // Content endpoints
    98         'get_status' => 'http://api.twitter.com/1/statuses/user_timeline.json',
    99         'get_retweet'=> 'http://api.twitter.com/1/statuses/retweeted_by_user.json',
     98        'get_status' => 'https://api.twitter.com/1.1/statuses/home_timeline.json',
     99        'get_retweet'=> 'https://api.twitter.com/1.1/statuses/retweets_of_me.json',
     100       
     101        // User endpoints
     102        'get_user' => 'https://api.twitter.com/1.1/users/show.json',
     103        'user_lookup' => 'https://api.twitter.com/1.1/users/lookup.json',
    100104    ); //['oauth_request_token']
    101105   
     
    156160     * @var array $feed_options
    157161     */
    158     private $feed_options = null;
     162    protected $feed_options = null;
    159163
    160164    /**
     
    266270            add_action( 'wp_ajax_mbgf_twitter_connect_reset_feed_defaults', array( &$this, 'reset_feed_defaults' ) );
    267271            add_action( 'wp_ajax_mbgf_twitter_connect_manual_feed_update', array( &$this, 'ajax_do_update' ) );
     272            add_action( 'wp_ajax_mbgf_twitter_connect_get_user', array( &$this, 'ajax_user_lookup' ) );
    268273           
    269274            // General Hooks
     
    272277            // Unregister feed hook
    273278            add_action( 'mbgf_unregister_feed-' . $this->get_slug(), array( &$this, 'unregister_feed') );
     279        }
     280    }
     281   
     282    function get_message($message_slug) {
     283        $text_domain = 'mb_globalfeed';
     284       
     285        switch ($message_slug) {
     286            case 'client_configuration_error':
     287                return __('GlobalFeed Twitter Connect cannot fetch updates due to a client side or network error.', $text_domain);
     288            case 'not_configured':
     289                return __('GlobalFeed Twitter Connect is not properly configured. Please redo the initial configuration.', $text_domain);
     290            case 'need_reauth':
     291                return __('GlobalFeed Twitter Connect needs you to reauthenticate the application with Twitter to continue receiving updates.', $text_domain);
     292            case 'rate_limiting':
     293                return __('GlobalFeed Twitter Connect is currently being rate limited. If you have issued a manual update please wait several minutes. Otherwise please reduce the update frequency.', $text_domain);
     294            default:
     295                return 'GlobalFeed Twitter error 404: Unknown message slug.';
    274296        }
    275297    }
     
    486508       
    487509        $this->globalfeed->print_debug_info("OAuth Key Generation");
    488         $this->get_oauth_key_request(); // will call register_feed
     510        if (!$this->get_oauth_key_request()) {
     511            die("{'error':'An error occured'}");
     512        }
    489513       
    490514        $this->register_feed(true);
     
    535559        die(json_encode(array('object' => $this->feed_options['object_to_subscribe'])));
    536560    }
     561   
     562    public function ajax_user_lookup() {
     563        check_admin_referer( 'twitter-connect-admin' );
     564        wp_verify_nonce( 'twitter-connect-admin' );
     565       
     566        $availparams = array( 'screen_name', 'user_id' );
     567        $params = array();
     568       
     569        foreach ($availparams as $param) {
     570            if ( isset($_GET[$param]) )
     571                $params[$param] = $_GET[$param];
     572        }
     573       
     574        $request = $this->do_twitter_remote_post($this->tw_endpoints['get_user'], $params, 'GET');
     575       
     576        // Check for a WP Error
     577        if ( is_wp_error($request) ) {
     578            http_response_code(500);
     579            die();
     580        }
     581       
     582        // Return the received data
     583        header( "HTTP/1.1 {$request['response']['code']} {$request['response']['message']}", true, $request['response']['code']);
     584        $this->globalfeed->print_debug_info($request);
     585        die($request['body']);
     586    }
    537587
    538588    /**
     
    592642            return new WP_Error ('not_setup', "You must set a Twitter consumer Key and Secret to get a request token");
    593643       
     644        $parameters = array(
     645            'oauth_callback' => get_bloginfo('wpurl').'/',
     646//            'x_auth_access_type' => 'read'
     647        );
     648       
    594649        // Do the request
    595         $request = $this->do_twitter_remote_post( $this->tw_endpoints['oauth_request_token'] );
     650        $request = $this->do_twitter_remote_post( $this->tw_endpoints['oauth_request_token'], array(), 'POST', $parameters );
    596651       
    597652        // Check if a request error occured
     
    685740     * @return array|WP_Error The result from executing wp_remote_post on the generated request
    686741     */
    687     private function do_twitter_remote_post( $endpoint, $parameters = array(), $method = 'POST' ) {
     742    private function do_twitter_remote_post( $endpoint, $parameters = array(), $method = 'POST', $auth_params = array() ) {
    688743        $default_parameters = array(
    689744            'oauth_consumer_key' => $this->feed_options['consumer_key'],
    690745            'oauth_nonce' => $_SESSION['state'],
     746//            'oauth_nonce' => "f9b649e39402a68e3ebbdbd2f8968fd3",
    691747            'oauth_signature_method' => 'HMAC-SHA1',
    692             'oauth_timestamp' => time(),
     748            'oauth_timestamp' => (string) time(),
     749//            'oauth_timestamp' => "1382247124",
     750//            'oauth_token' => $this->feed_options['oauth_access_token'],
    693751            'oauth_version' => '1.0',
    694             'oauth_callback' => get_bloginfo('wpurl').'/',
    695             'x_auth_access_type' => 'read'
     752//            'oauth_callback' => get_bloginfo('wpurl').'/',
     753//            'x_auth_access_type' => 'read'
    696754        );
    697755       
    698         if ( !empty($this->feed_options['oauth_access_token']) )
    699             $default_parameters['oauth_access_token'] = $this->feed_options['oauth_access_token'];
     756       
     757       
     758//        if ( !empty($this->feed_options['oauth_access_token']) )
     759//            $default_parameters['oauth_token'] = $this->feed_options['oauth_access_token'];
    700760       
    701761        // Parse the default parameters
    702         $parameters = wp_parse_args($parameters, $default_parameters);
     762//        $parameters = wp_parse_args($parameters, $default_parameters);
     763        $auth_params = wp_parse_args($auth_params, $default_parameters);
     764        $all_params = wp_parse_args($parameters, $auth_params);
     765       
     766        ksort($all_params);
    703767           
    704768        // Get the signature for the request
    705         $parameters['oauth_signature'] = $this->generate_twitter_request_signature($endpoint, $method, $parameters);
    706        
    707         // The below code is what is SUPPOSED to be done -- but it didn't want to work :(
    708 //        // Build the Authorization header string
    709 //        $header_str = 'OAuth ';
    710 //        foreach ( $parameters as $key => $value )
    711 //            $header_str .= rawurlencode($key) . '="' . rawurlencode($value) . '", ';
    712 //       
    713 //        // Remove trailing ", " from string
    714 //        $header_str = substr($header_str, 0, -2);
     769        $signature = $this->generate_twitter_request_signature($endpoint, $method, $all_params);
     770        $auth_params['oauth_signature'] = $signature;
     771       
     772        ksort($auth_params);
     773       
     774        $this->globalfeed->print_debug_info($auth_params);
     775       
     776        $this->globalfeed->print_debug_info($parameters);
    715777       
    716778        $endpoint .= '?';
     
    720782        $endpoint = substr($endpoint, 0, -1);
    721783       
     784        $this->globalfeed->print_debug_info($endpoint);
     785       
     786        $auth_header = "OAuth ";
     787        foreach ( $auth_params as $key => $value )
     788            $auth_header .= rawurlencode($key) . "=\"" . rawurlencode($value) . "\", ";
     789       
     790        $this->globalfeed->print_debug_info(substr($auth_header, 0, -2));
     791       
    722792        // Execute the request, and return whatever results
    723         return wp_remote_post($endpoint, array( 'method' => strtoupper($method), ) );
     793        return wp_remote_post($endpoint, array( 'method' => strtoupper($method), 'headers' => array( 'Authorization' => $auth_header ) ) );
    724794    }
    725795   
     
    733803     */
    734804    private function generate_twitter_request_signature( $endpoint, $method, $parameters ) {
     805        $this->globalfeed->print_debug_info("------------------------Beginning signature generation");
     806       
    735807        // Sort the parameters alphabetically
    736808        ksort($parameters);
     
    746818        // The base string is the parameter string appendd to the base string (as per oauth spec)
    747819        $base_str = strtoupper($method) . '&' . rawurlencode($endpoint) . '&' . rawurlencode($param_str);
     820        $this->globalfeed->print_debug_info('base string:');
     821        $this->globalfeed->print_debug_info($base_str);
    748822       
    749823        // Build the signing key
     
    752826        // If we have a user request token, that needs to be a part of the signing key
    753827        if ( !empty($this->feed_options['oauth_access_token_secret']) )
    754             $signing_key .= rawurlencode($this->feed_options['oauth_token_secret']);
     828            $signing_key .= rawurlencode($this->feed_options['oauth_access_token_secret']);
     829       
     830        $this->globalfeed->print_debug_info('signing key:');
     831        $this->globalfeed->print_debug_info($signing_key);
     832       
     833        $this->globalfeed->print_debug_info("------------------------Done signature generation");
    755834       
    756835        // Create and return the signature
    757836        return base64_encode(hash_hmac('sha1', $base_str, $signing_key, true));
    758     }
    759    
    760     /**
    761      * Adds a Twitter alert that should be displayed to the user
    762      *
    763      * If an alert with the same $alert_code already exists, it will be overwritten.
    764      *
    765      * @param str $alert_code A slug-style code for the alert
    766      * @param str $alert_text The alert text
    767      * @param bool $sitewide (optional, defaults to false) Whether the alert should be shown sitewide, or just within GlobalFeed.
    768      */
    769    
    770     /**
    771      * Adds a Twitter alert that should be displayed to the user
    772      *
    773      * If an alert with the same $alert_code already exists, it will be overwritten.
    774      *
    775      * @global type $current_user
    776      *
    777      * @param str $alert_code A slug-style code for the alert
    778      * @param str $alert_text The alert text
    779      * @param type $important Whether the alert should be shown as a notice or an error
    780      * @param bool $sitewide (optional, defaults to false) Whether the alert should be shown sitewide, or just within GlobalFeed.
    781      * @param type $require_priv What privilege the alert requires to be seen. '' if none.
    782      * @param type $dismissable Whether the alert should be dismissable by the user
    783      */
    784     function add_alert( $alert_code, $alert_text, $important = false, $sitewide = false, $require_priv = 'manage_options', $dismissable = true ) {
    785         global $current_user;
    786        
    787         $this->feed_options['alerts'][$alert_code] = array(
    788             'alert_code' => $alert_code,
    789             'alert_text' => $alert_text,
    790             'sitewide'   => $sitewide,
    791             'hidden'     => false,
    792             'remind'     => 0,
    793             'important'  => $important,
    794             'require_priv' => $require_priv,
    795             'never_show' => (isset($this->feed_options['alerts'][$alert_code]) ? $this->feed_options['alerts'][$alert_code]['never_show'] : false),
    796             'dismissable'=> $dismissable,
    797         );
    798        
    799         $this->globalfeed->print_debug_info("Feed options");
    800         $this->globalfeed->print_debug_info($this->feed_options['alerts']);
    801        
    802         $this->register_feed(true);
    803        
    804         delete_user_meta($current_user->ID, "mbgf_twitter_connect_hide_alert_" . $alert_code);
    805        
    806         $this->globalfeed->print_debug_info("Added alert: $alert_code");
    807     }
    808    
    809     /**
    810      * When an alert no longer applies, hide it from the user.
    811      *
    812      * @param type $alert_code
    813      */
    814     function hide_alert( $alert_code ) {
    815         if ( isset($this->feed_options['alerts'][$alert_code]) )
    816             $this->feed_options['alerts'][$alert_code]['hidden'] = true;
    817        
    818         $this->register_feed(true);
    819     }
    820    
    821     /**
    822      * Shows any queued alerts. Also detects if the user hides an alert
    823      *
    824      * Called by WordPress Action 'admin_notices'
    825      *
    826      */
    827     function show_alerts() {
    828         global $current_user;
    829        
    830         // Check if there are alerts
    831         if ( !count($this->feed_options['alerts']) )
    832             return;
    833        
    834         $hide_text = __('Hide', 'mb_twitter');
    835         $never_show_text = __('Never show again', 'mb_twitter');
    836        
    837         // Used for show/hide urls
    838         $server_args = array();
    839         parse_str($_SERVER['QUERY_STRING'], $server_args);
    840        
    841         // Loop through alerts
    842         foreach ($this->feed_options['alerts'] as $alert_code => $alert) {
    843             // Check if this alert should be hidden from the user
    844             $hide_alert = "mbgf_twitter_connect_hide_alert_" . $alert['alert_code'];
    845             $never_show_alert = "mbgf_twitter_connect_never_show_alert_" . $alert['alert_code'];
    846            
    847             // Check if alert is disabled -- but make sure we catch anything telling us to hide the alert (but make sure the user has permission)
    848             if ( !isset($_GET[$hide_alert]) && !isset($_GET[$never_show_alert]) && !( $alert['require_priv'] !== '' && current_user_can($require_priv) ) && (
    849                     // Is this alert disabled?
    850                     $alert['hidden'] || $alert['never_show']
    851                    
    852                     // Check if the alert should be shown accross WP-Admin
    853                     || ( $this->globalfeed->in_admin() === false && !$alert['sitewide'] )
    854                    
    855                     // Check if the user has previously hidden this alert
    856                     || get_user_meta($current_user->ID, $hide_alert, true) === true ) )
    857                 continue;
    858            
    859             // Check if alert show status changed
    860             if ( isset($_GET[$hide_alert]) ) {
    861                 add_user_meta($current_user->ID, $hide_alert, true);
    862                 continue;
    863             }
    864            
    865             if ( isset($_GET[$never_show_alert]) ) {
    866                 $this->feed_options['alerts'][$alert_code]['never_show'] = true;
    867                 $this->register_feed(true);
    868                 continue;
    869             }
    870            
    871             // This alert should be shown to the user
    872             echo "<div class='{$alert['alert_code']} " . ($alert['important'] ? 'error' : 'updated') . "'><p>{$alert['alert_text']}</p>";
    873            
    874             if ( $alert['dismissable'] ) {
    875                 $hide_addr = http_build_query(array_merge($server_args, array($hide_alert=>1)));
    876                 $never_addr=  http_build_query(array_merge($server_args, array($never_show_alert=>1)));
    877                 echo "<div class='align_right'><a href='?$hide_addr' title='$hide_text'>$hide_text</a> | <a href='?$never_addr' title='$never_show_text'>$never_show_text</a></div></div>";
    878             } else
    879                 echo '</div>';
    880         }
    881837    }
    882838
     
    891847     */
    892848    function update_feed() {
    893        
    894849        // Don't try and update if authorization is in progress
    895         if ( $this->feed_options['tw_auth_status'] !== 'authorized' && $this->feed_options['tw_auth_status'] !== 'not_initiated' )
     850        if ( $this->feed_options['tw_auth_status'] !== 'authorized' && $this->feed_options['tw_auth_status'] !== 'not_initiated' ) {
     851            $this->add_alert('not_configure', $this->get_message('not_configure'), true, false);
    896852            return;
     853        }
     854       
     855        $this->hide_alert('not_authenticated');
    897856       
    898857        $globalfeed = &$this->globalfeed;
     
    950909           
    951910            // Check for a WP Error
    952             if ( is_wp_error($request) )
    953                 return $request;
     911            if ( is_wp_error($request) ) {
     912                $this->add_alert('client_configuration_error', $this->get_message('client_configuration_error'), true, false);
     913                continue;
     914            }
    954915
    955916            // Hide any previous alerts
    956             $this->hide_alert('request_error');
    957             $this->hide_alert('rate_limiting');
     917            $this->hide_alerts(array('request_error', 'rate_limiting', 'client_configuration_error'));
    958918           
    959919            // Check the response code
     
    961921            if ( $request['response']['code'] !== 200 ) {
    962922                if ( $request['response']['code'] === 302 ) {
    963                     $this->globalfeed->print_debug_info('Rate limiting error', 'mb_twitter');
    964                    
    965923                    // We are being rate limited
    966924                    if ( !empty($this->feed_options['oauth_access_token'])) {
     
    974932                } else {
    975933                    $this->globalfeed->print_debug_info('Request error.', 'mb_twitter');
    976                     $this->add_alert('error_connecting', "Problems were experienced communicating with Twitter. Received response code {$request['response']['code']} on endpoint {$endpoint_id}");
    977                     return new WP_Error('request_error', "Twitter connect experienced a comms error fetching new content from Twitter.", $request['response']['code']);
     934                    $this->add_alert('error_connecting', "GlobalFeed Twitter Connect experienced problems communicating with Twitter. Received response code {$request['response']['code']} on endpoint {$endpoint_id}.");
     935                    return new WP_Error('request_error', "GlobalFeed Twitter Connect experienced a comms error fetching new content from Twitter.", $request['response']['code']);
    978936                }
    979937            }
     
    990948           
    991949            foreach ($updates as $update) {
    992                 if ( $update['user']['id'] != $feed_options['object_to_subscribe'] ) {
    993                     //$globalfeed->print_debug_info($update);
     950                if ( $update['user']['id'] != $feed_options['object_to_subscribe'] )
    994951                    continue;
    995                 }
    996952
    997953                $post_date = new DateTime((string) trim($update['created_at']), $gmt_timezone);
Note: See TracChangeset for help on using the changeset viewer.