Advertisement
Guest User

Untitled

a guest
Jan 13th, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.47 KB | None | 0 0
  1. <?php
  2. /*
  3.  * Requests Twitter Feed and Updates Transient
  4.  */
  5.  
  6. function kebo_twitter_get_tweets() {
  7.  
  8.     // If there is no social connection, we cannot get tweets, so return false
  9.     $twitter_data = get_option( 'kebo_twitter_connection' );
  10.     if ( empty ( $twitter_data ) ) {
  11.         return false;
  12.     }
  13.  
  14.     // Grab the Plugin Options.
  15.     $options = kebo_get_twitter_options();
  16.     /*
  17.      * Get transient and check if it has expired.
  18.      */
  19.     if (false === ( $tweets = get_transient( 'kebo_twitter_feed_' . get_current_blog_id() ) ) ) {
  20.  
  21.         // Make POST request to Kebo OAuth App.
  22.         $response = kebo_twitter_external_request();
  23.        
  24.         // If not WP Error response is in body
  25.         if ( ! is_wp_error( $response ) ) {
  26.            
  27.             // Response is in JSON format, so decode it.
  28.             $response = json_decode( $response['body'] );
  29.            
  30.         }
  31.        
  32.         // Check for Error or Success Response.
  33.         if ( isset( $response->errors ) ) {
  34.            
  35.             // If error, add to error log.
  36.             kebo_twitter_add_error( $response );
  37.            
  38.         } else {
  39.            
  40.             // We have Tweets, linkify the text
  41.             $tweets = kebo_twitter_linkify( $response );
  42.  
  43.             // Add custom expiry time
  44.             $tweets['expiry'] = time() + ( $options['kebo_twitter_cache_timer'] * MINUTE_IN_SECONDS );
  45.  
  46.             // JSON encode Tweet data
  47.             $tweets = json_encode( $tweets );
  48.                        
  49.             // No error, set transient with latest Tweets
  50.             set_transient( 'kebo_twitter_feed_' . get_current_blog_id(), base64_encode($tweets), 24 * HOUR_IN_SECONDS );
  51.            
  52.             // Decode for use
  53.             $tweets = json_decode( $tweets, false );
  54.         }
  55.     }
  56.    
  57.     /*
  58.      * If we have serialized data from the Transient we must decode it.
  59.      */
  60.     if ( is_string( $tweets ) && ( null != json_decode( base64_decode($tweets) ) ) ) {
  61.         $tweets = json_decode( base64_decode($tweets), false );
  62.     }
  63.  
  64.     /*
  65.      * Check if Tweets have soft expired (user setting), if so run refresh after page load.
  66.      */
  67.     if ( ! empty( $tweets->expiry ) && $tweets->expiry < time() ) {
  68.  
  69.         // Add 30 seconds to soft expire, to stop other threads trying to update it at the same time.
  70.         $tweets->expiry = ( time() + 30 );
  71.  
  72.         // JSON encode Tweet data
  73.         $tweets = json_encode( $tweets );
  74.        
  75.         // Update soft expire time.
  76.         set_transient( 'kebo_twitter_feed_' . get_current_blog_id(), base64_encode($tweets), 24 * HOUR_IN_SECONDS );
  77.        
  78.         // Decode for use
  79.         $tweets = json_decode( $tweets, false );
  80.  
  81.         // Set silent cache to refresh after page load.
  82.         add_action( 'shutdown', 'kebo_twitter_refresh_cache' );
  83.        
  84.     }
  85.    
  86.     return $tweets;
  87.    
  88. }
  89.  
  90. /*
  91.  * Alias function for 'kebo_twitter_get_tweets'.
  92.  */
  93. if ( ! function_exists( 'get_tweets' ) ) {
  94.  
  95.     function get_tweets() {
  96.  
  97.         $tweets = kebo_twitter_get_tweets();
  98.        
  99.         return $tweets;
  100.        
  101.     }
  102.  
  103. }
  104.  
  105. /*
  106.  * Hooks Output Function to 'wp_footer'.
  107.  */
  108.  
  109. function kebo_twitter_print_js() {
  110.  
  111.     // Add javascript output script to 'wp_footer' hook with low priority so that jQuery loads before.
  112.     add_action( 'wp_footer', 'kebo_twitter_slider_script', 99 );
  113.    
  114. }
  115.  
  116. /*
  117.  * Make external request to Kebo auth script
  118.  */
  119.  
  120. function kebo_twitter_external_request() {
  121.  
  122.     if ( false !== ( $twitter_data = get_option( 'kebo_twitter_connection' ) ) ) {
  123.  
  124.         // URL to Kebo OAuth Request App
  125.         $request_url = 'http://auth.kebopowered.com/request/index.php';
  126.  
  127.         // Setup arguments for OAuth request.
  128.         $data = array(
  129.             'service' => 'twitterfull',
  130.             'account' => $twitter_data['account'], // Screen Name
  131.             'token' => $twitter_data['token'], // OAuth Token
  132.             'secret' => $twitter_data['secret'], // OAuth Secret
  133.             'userid' => $twitter_data['userid'], // User ID
  134.         );
  135.  
  136.         // Setup arguments for POST request.
  137.         $args = array(
  138.             'method' => 'POST',
  139.             'timeout' => 10,
  140.             'redirection' => 5,
  141.             'httpversion' => '1.1',
  142.             'blocking' => true,
  143.             'headers' => array(),
  144.             'body' => array(
  145.                 'feed' => 'true',
  146.                 'data' => json_encode( $data ),
  147.             ),
  148.             'cookies' => array(),
  149.             'sslverify' => false,
  150.         );
  151.  
  152.         // Make POST request to Kebo OAuth App.
  153.         $request = wp_remote_post( $request_url, $args );
  154.  
  155.         return $request;
  156.        
  157.     }
  158.    
  159. }
  160.  
  161. /*
  162.  * Silently refreshes the cache (transient) after page has rendered.
  163.  */
  164. function kebo_twitter_refresh_cache() {
  165.  
  166.     /*
  167.      * If cache has already been updated, no need to refresh
  168.      */
  169.     if ( false !== ( $tweets = get_transient( 'kebo_twitter_feed_' . get_current_blog_id() ) ) ) {
  170.  
  171.         /*
  172.          * Check if we are already updating.
  173.          */
  174.         if ( get_transient( 'kebo_cron_is_running' ) ) {
  175.             die();
  176.         }
  177.  
  178.         /*
  179.          * Create hash of the current time (nothing else should occupy the same microtime).
  180.          */
  181.         $hash = hash( 'sha1', microtime() );
  182.  
  183.         /*
  184.          * Set transient to show we are updating and set the hash for this specific thread.
  185.          */
  186.         set_transient( 'kebo_cron_is_running', $hash, 5 );
  187.        
  188.         /*
  189.          * Sleep so that other threads at the same point can set the hash
  190.          */
  191.         usleep( 250000 ); // Sleep for 1/4th of a second
  192.        
  193.         /*
  194.          * Only one thread will have the same hash as is stored in the transient now, all others can die.
  195.          */
  196.         if ( get_transient( 'kebo_cron_is_running' ) && ( get_transient( 'kebo_cron_is_running' ) != $hash ) ) {
  197.             die();
  198.         }
  199.        
  200.         // Make POST request to Kebo OAuth App.
  201.         $response = kebo_twitter_external_request();
  202.        
  203.         // If not WP Error response is in body
  204.         if ( ! is_wp_error( $response ) ) {
  205.            
  206.             // Response is in JSON format, so decode it.
  207.             $response = json_decode( $response['body'] );
  208.            
  209.         }
  210.        
  211.         // Grab the Plugin Options.
  212.         $options = kebo_get_twitter_options();
  213.  
  214.         // Check for Error or Success Response.
  215.         if ( isset( $response->errors ) ) {
  216.            
  217.             // If error, add to error log.
  218.             kebo_twitter_add_error( $response );
  219.            
  220.         } else {
  221.            
  222.             // We have Tweets, linkify the text
  223.             $tweets = kebo_twitter_linkify( $response );
  224.  
  225.             // Add custom expiry time
  226.             $tweets['expiry'] = time() + ( $options['kebo_twitter_cache_timer'] * MINUTE_IN_SECONDS );
  227.            
  228.             // JSON encode Tweet data
  229.             $tweets = json_encode( $tweets );
  230.  
  231.             // No error, set transient with latest Tweets
  232.             set_transient( 'kebo_twitter_feed_' . get_current_blog_id(), base64_encode($tweets), 24 * HOUR_IN_SECONDS );
  233.            
  234.         }
  235.        
  236.         /*
  237.          * Remove transient once updating is done.
  238.          */
  239.         delete_transient( 'kebo_cron_is_running' );
  240.        
  241.     }
  242.    
  243. }
  244.  
  245. /*
  246.  * Converts Tweet text urls, account names and hashtags into HTML links.
  247.  */
  248. function kebo_twitter_linkify( $tweets ) {
  249.    
  250.     foreach ( $tweets as $tweet ) {
  251.  
  252.         // TEMPORARILY COMMENTED OUT AND REPLACED WITH REGEX
  253.        
  254.         /*
  255.         $hash_length = 45; // Length of HTML added to hashtags
  256.         $mention_length = 33; // Length of HTML added to mentions
  257.         $markers = array();
  258.          *
  259.          */
  260.        
  261.         /*
  262.          * Linkify Hashtags
  263.          */
  264.         /*
  265.         if ( ! empty( $tweet->entities->hashtags ) ) {
  266.            
  267.             // One Hashtag at a time
  268.             foreach ( $tweet->entities->hashtags as $hashtag ) {
  269.                
  270.                 // Start offset from 0
  271.                 $offset = 0;
  272.                 // Calculate length of hastag - end minus start
  273.                 $length = $hashtag->indices[1] - $hashtag->indices[0];
  274.                
  275.                 // If no markers, no need to offset
  276.                 if ( ! empty( $markers ) ) {
  277.                    
  278.                     foreach ( $markers as $mark ) {
  279.                        
  280.                         // If the start point is past a previous marker, we need to adjust for the characters added.
  281.                         if ( $hashtag->indices[0] > $mark['point'] ) {
  282.                            
  283.                             // Include previous offsets.
  284.                             $offset = ( $offset + ( $mark['length'] ) );
  285.                            
  286.                         }
  287.                        
  288.                     }
  289.                    
  290.                 }
  291.          *
  292.          */
  293.                
  294.                 /*
  295.                  * Replace hashtag text with an HTML link
  296.                  */
  297.         /*
  298.                 $tweet->text = substr_replace( $tweet->text, '<a href="http://twitter.com/search?q=%23' . $hashtag->text . '">#' . $hashtag->text . '</a>', $hashtag->indices[0] + $offset, $length );
  299.  
  300.                 // Set marker so we can take into account the characters we just added.
  301.                 $markers[] = array(
  302.                     'point' => $hashtag->indices[0],
  303.                     'length' => $hash_length + $length,
  304.                 );
  305.                
  306.                
  307.             }
  308.            
  309.         }
  310.          *
  311.          */
  312.        
  313.         /*
  314.          * Linkify Mentions
  315.          */
  316.         /*
  317.         if ( ! empty( $tweet->entities->user_mentions ) ) {
  318.            
  319.             // One Mention at a time
  320.             foreach ( $tweet->entities->user_mentions as $mention ) {
  321.                
  322.                 $offset = 0;
  323.                 $length = $mention->indices[1] - $mention->indices[0];
  324.                
  325.                 if ( ! empty($markers) ) {
  326.                    
  327.                     foreach ( $markers as $mark ) {
  328.                        
  329.                         if ( $mention->indices[0] > $mark['point'] ) {
  330.                            
  331.                             $offset = ( $offset + ( $mark['length'] ) );
  332.                            
  333.                         }
  334.                        
  335.                     }
  336.                    
  337.                 }
  338.          *
  339.          */
  340.                
  341.                 /*
  342.                  * Replace mention text with an HTML link
  343.                  */
  344.         /*
  345.                 $tweet->text = substr_replace( $tweet->text, '<a href="http://twitter.com/' . $mention->screen_name . '">@' . $mention->screen_name . '</a>', $mention->indices[0] + $offset, $length );
  346.  
  347.                 // Set marker so we can take into account the characters we just added.
  348.                 $markers[] = array(
  349.                     'point' => $mention->indices[0],
  350.                     'length' => $mention_length + $length,
  351.                 );
  352.                
  353.                
  354.             }
  355.            
  356.         }
  357.          *
  358.          */
  359.        
  360.         /*
  361.          * Check if it is the Tweet text or Re-Tweet text which we need to pre-process.
  362.          */
  363.         if ( ! empty( $tweet->retweeted_status ) ) {
  364.            
  365.            /*
  366.             * Decode HTML Chars like &#039; to '
  367.             */
  368.            $tweet->retweeted_status->text = htmlspecialchars_decode( $tweet->retweeted_status->text, ENT_QUOTES );
  369.  
  370.            /*
  371.             * Turn Hasntags into HTML Links
  372.             */
  373.            $tweet->retweeted_status->text = preg_replace( '/#([A-Za-z0-9\/\.]*)/', '<a href="http://twitter.com/search?q=$1">#$1</a>', $tweet->retweeted_status->text );
  374.  
  375.            /*
  376.             * Turn Mentions into HTML Links
  377.             */
  378.            $tweet->retweeted_status->text = preg_replace( '/@([A-Za-z0-9_\/\.]*)/', '<a href="http://www.twitter.com/$1">@$1</a>', $tweet->retweeted_status->text );
  379.  
  380.            /*
  381.             * Linkify text URLs
  382.             */
  383.            $tweet->retweeted_status->text = make_clickable( $tweet->retweeted_status->text );
  384.  
  385.            /*
  386.             * Add target="_blank" to all links
  387.             */
  388.            $tweet->retweeted_status->text = links_add_target( $tweet->retweeted_status->text, '_blank', array( 'a' ) );
  389.            
  390.         } else {
  391.            
  392.            /*
  393.             * Decode HTML Chars like &#039; to '
  394.             */
  395.            $tweet->text = htmlspecialchars_decode( $tweet->text, ENT_QUOTES );
  396.  
  397.            /*
  398.             * Turn Hasntags into HTML Links
  399.             */
  400.            $tweet->text = preg_replace( '/#([A-Za-z0-9\/\.]*)/', '<a href="http://twitter.com/search?q=$1">#$1</a>', $tweet->text );
  401.  
  402.            /*
  403.             * Turn Mentions into HTML Links
  404.             */
  405.            $tweet->text = preg_replace( '/@([A-Za-z0-9_\/\.]*)/', '<a href="http://www.twitter.com/$1">@$1</a>', $tweet->text );
  406.  
  407.            /*
  408.             * Linkify text URLs
  409.             */
  410.            $tweet->text = make_clickable( $tweet->text );
  411.  
  412.            /*
  413.             * Add target="_blank" to all links
  414.             */
  415.            $tweet->text = links_add_target( $tweet->text, '_blank', array( 'a' ) );
  416.            
  417.         }
  418.        
  419.     }
  420.    
  421.     return $tweets;
  422.    
  423. }
  424.  
  425. /*
  426.  * Adds an error from the Twitter API to the error log.
  427.  */
  428. function kebo_twitter_add_error( $response ) {
  429.    
  430.     if ( is_wp_error( $response ) ) {
  431.        
  432.         // Add details of current WP error
  433.         $error[] = array(
  434.             'date' => time(),
  435.             'code' => 1,
  436.             'message' => $response->errors['http_request_failed'][0],
  437.         );
  438.        
  439.     } else {
  440.        
  441.         // Add details of current error
  442.         $error[] = array(
  443.             'date' => time(),
  444.             'code' => $response->errors[0]->code,
  445.             'message' => $response->errors[0]->message,
  446.         );
  447.        
  448.     }
  449.    
  450.     // Get currently stored errors
  451.     $log = get_option( 'kebo_twitter_errors' );
  452.    
  453.     if ( $log[0] ) {
  454.        
  455.         // Add new error to start of array
  456.         $errors = array_merge( $error, $log );
  457.        
  458.     } else {
  459.        
  460.         $errors = $error;
  461.        
  462.     }
  463.    
  464.     // Limit array to the latest 10 errors
  465.     $errors = array_slice( $errors, 0, 10, false );
  466.        
  467.     update_option( 'kebo_twitter_errors', $errors );
  468.        
  469. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement