Advertisement
adsleeblythe

Easy Instagram index.php

Nov 1st, 2012
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 31.52 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Easy Instagram
  4. Plugin URI:
  5. Description: Display one or more Instagram images by user id or tag
  6. Version: 1.2.1
  7. Author: VeloMedia
  8. Author URI: http://www.velomedia.com
  9. Licence:
  10. */
  11. require_once 'include/Instagram-PHP-API/Instagram.php';
  12. add_action( 'admin_menu', array( 'Easy_Instagram', 'admin_menu' ) );
  13. add_action( 'wp_enqueue_scripts', array( 'Easy_Instagram', 'init_scripts_and_styles' ) );
  14. add_action( 'admin_init', array( 'Easy_Instagram', 'admin_init' ) );
  15. register_activation_hook( __FILE__, array( 'Easy_Instagram', 'plugin_activation' ) );
  16. register_deactivation_hook( __FILE__, array( 'Easy_Instagram', 'plugin_deactivation' ) );
  17. add_action( 'easy_instagram_clear_cache_event', array( 'Easy_Instagram', 'clear_expired_cache_action' ) );
  18. add_shortcode( 'easy-instagram', array( 'Easy_Instagram', 'shortcode' ) );
  19. //=============================================================================
  20. define( 'EASY_INSTAGRAM_PLUGIN_PATH', dirname( __FILE__ ) );
  21. class Easy_Instagram {
  22.     static $cache_dir = 'cache/';
  23.     static $minimum_cache_expire_minutes = 10;
  24.     static $default_cache_expire_minutes = 30;
  25.     static $max_images = 10;
  26.     static function admin_menu() {
  27.         add_submenu_page(
  28.             'options-general.php',
  29.             __( 'Easy Instagram', 'Easy_Instagram' ),
  30.             __( 'Easy Instagram', 'Easy_Instagram' ),
  31.             'manage_options',
  32.             'easy-instagram',
  33.             array( 'Easy_Instagram', 'admin_page' )
  34.         );
  35.     }
  36.     //=========================================================================
  37.     static function init_scripts_and_styles() {
  38.         if ( ! is_admin() ) {
  39.             wp_register_style( 'Easy_Instagram', plugins_url( 'css/style.css', __FILE__ ) );
  40.             wp_enqueue_style( 'Easy_Instagram' );
  41.         }
  42.     }
  43.     //=========================================================================
  44.     static function admin_init() {
  45.         wp_register_style( 'Easy_Instagram_Admin', plugins_url( 'css/admin.css', __FILE__ ) );
  46.         wp_enqueue_style( 'Easy_Instagram_Admin' );
  47.     }
  48.     //=========================================================================
  49.     static function set_instagram_settings( $client_id, $client_secret, $redirect_uri ) {
  50.         update_option( 'easy_instagram_client_id', $client_id );
  51.         update_option( 'easy_instagram_client_secret', $client_secret );
  52.         update_option( 'easy_instagram_redirect_uri', $redirect_uri );
  53.     }
  54.     //=========================================================================
  55.     static function get_instagram_settings() {
  56.         $client_id = get_option( 'easy_instagram_client_id' );
  57.         $client_secret = get_option( 'easy_instagram_client_secret' );
  58.         $redirect_uri = get_option( 'easy_instagram_redirect_uri' );
  59.         return array( $client_id, $client_secret, $redirect_uri );
  60.     }
  61.     //=========================================================================
  62.     static function get_instagram_config() {
  63.         list( $client_id, $client_secret, $redirect_uri ) = self::get_instagram_settings();
  64.         return array(
  65.             'client_id'     => $client_id,
  66.             'client_secret' => $client_secret,
  67.             'grant_type'    => 'authorization_code',
  68.             'redirect_uri'  => $redirect_uri
  69.         );
  70.     }  
  71.     //=========================================================================
  72.     static function admin_page() {
  73.         if ( isset( $_POST['ei_general_settings'] ) &&
  74.                 check_admin_referer( 'ei_general_settings_nonce', 'ei_general_settings_nonce' ) ) {
  75.             $errors = array();
  76.             $instagram_client_id = isset( $_POST['ei_client_id'] )
  77.                 ? trim( $_POST['ei_client_id'] )
  78.                 : '';
  79.             $instagram_client_secret = isset( $_POST['ei_client_secret'] )
  80.                 ? trim( $_POST['ei_client_secret'] )
  81.                 : '';
  82.             $instagram_redirect_uri = isset( $_POST['ei_redirect_uri'] )
  83.                 ? trim( $_POST['ei_redirect_uri'] )
  84.                 : '';
  85.             if ( empty( $instagram_client_id ) ) {
  86.                 $errors['client_id'] = __( 'Please enter your Instagram client id', 'Easy_Instagram' );
  87.             }
  88.            
  89.             if ( empty( $instagram_client_secret ) ) {
  90.                 $errors['client_secret'] = __( 'Please enter your Instagram client secret', 'Easy_Instagram' );
  91.             }
  92.             if ( empty( $instagram_redirect_uri ) ) {
  93.                 $errors['redirect_uri'] = __( 'Please enter your Instagram redirect URI', 'Easy_Instagram' );
  94.             }
  95.             if ( empty( $errors ) ) {
  96.                 self::set_instagram_settings( $instagram_client_id, $instagram_client_secret, $instagram_redirect_uri );
  97.             }
  98.             $cache_expire_time = isset( $_POST['ei_cache_expire_time'] )
  99.                 ? (int) $_POST['ei_cache_expire_time']
  100.                 : 0;
  101.             if ( $cache_expire_time < self::$minimum_cache_expire_minutes ) {
  102.                 $cache_expire_time = self::$minimum_cache_expire_minutes;
  103.             }
  104.             self::set_cache_refresh_minutes( $cache_expire_time );     
  105.         }
  106.         else {
  107.             list( $instagram_client_id, $instagram_client_secret, $instagram_redirect_uri )
  108.                 = self::get_instagram_settings();
  109.         }
  110.         if ( isset( $_POST['instagram-logout'] )
  111.                 && check_admin_referer( 'ei_user_logout_nonce', 'ei_user_logout_nonce' ) ) {
  112.             self::set_access_token( '' );
  113.             update_option( 'ei_access_token', '' );
  114.         }
  115.         $config = self::get_instagram_config();
  116.         $instagram = new MC_Instagram_Connector( $config );
  117.         $access_token = self::get_access_token();
  118.         $cache_dir = self::get_cache_dir();
  119.         $cache_expire_time = self::get_cache_refresh_minutes();
  120.         if ( empty ( $access_token ) ) {
  121.             if ( isset( $_GET['code'] ) ) {
  122.                 $access_token = $instagram->getAccessToken();
  123.                 if ( !empty( $access_token ) ) {
  124.                     self::set_access_token( $access_token );
  125.                 }
  126.                 $instagram_user = $instagram->getCurrentUser();
  127.                 if ( !empty( $instagram_user ) ) {
  128.                     self::set_instagram_user_data( $instagram_user->username, $instagram_user->id );
  129.                 }
  130.             }
  131.         }
  132. ?>
  133.     <div id="icon-options-general" class="icon32"></div>
  134.     <h2><?php _e( 'Easy Instagram', 'Easy_Instagram' ) ?></h2>
  135.     <form method='POST' action='' class='easy-instagram-settings-form'>
  136.         <table class='easy-instagram-settings'>
  137.             <?php if ( !is_writable( $cache_dir ) ): ?>
  138.                 <tr class='warning'>
  139.                     <td colspan='2'>
  140.                         <?php printf( __( 'The directory %s is not writable !', 'Easy_Instagram' ), $cache_dir ); ?>
  141.                     </td>
  142.                 </tr>
  143.             <?php endif; ?>
  144.             <tr>
  145.                 <td colspan='2'><h3><?php _e( 'General Settings', 'Easy_Instagram' ); ?></h3></td>
  146.             </tr>
  147.             <tr>
  148.                 <td class='labels'>
  149.                     <label for='ei-client-id'><?php _e( 'Application Client ID', 'Easy_Instagram' ); ?></label>
  150.                 </td>
  151.                 <td>
  152.                     <input type='text' name='ei_client_id' id='ei-client-id' value='<?php echo esc_html( $instagram_client_id ); ?>' />
  153.                     <br />
  154.                     <?php if ( isset( $errors['client_id'] ) ): ?>
  155.                         <div class='form-error'><?php echo $errors['client_id']; ?></div>
  156.                     <?php endif; ?>
  157.                     <span class='info'><?php _e( 'This is the ID of your Instagram application', 'Easy_Instagram' ); ?></span>
  158.                 </td>
  159.             </tr>
  160.             <tr>
  161.                 <td class='labels'>
  162.                     <label for='ei-client-secret'><?php _e( 'Application Client Secret', 'Easy_Instagram' ); ?></label>
  163.                 </td>
  164.                 <td>
  165.                     <input type='text' name='ei_client_secret' id='ei-client-secret' value='<?php echo esc_html( $instagram_client_secret ); ?>' />
  166.                     <br />
  167.                     <?php if ( isset( $errors['client_secret'] ) ): ?>
  168.                         <div class='form-error'><?php echo $errors['client_secret']; ?></div>
  169.                     <?php endif; ?>
  170.                     <span class='info'><?php _e( 'This is your Instagram application secret', 'Easy_Instagram' ); ?></span>
  171.                 </td>
  172.             </tr>
  173.             <tr>
  174.                 <td class='labels'>
  175.                     <label for='ei-redirect-uri'><?php _e( 'Application Redirect URI', 'Easy_Instagram' ); ?></label>
  176.                 </td>
  177.                 <td>
  178.                     <input type='text' name='ei_redirect_uri' id='ei-redirect-uri' value='<?php echo esc_html( $instagram_redirect_uri ); ?>' />
  179.                     <br />
  180.                     <?php if ( isset( $errors['redirect_uri'] ) ): ?>
  181.                         <div class='form-error'><?php echo $errors['redirect_uri']; ?></div>
  182.                     <?php endif; ?>
  183.                     <span class='info'><?php _e( 'This is your Instagram application redirect URI', 'Easy_Instagram' ); ?></span>
  184.                 </td>
  185.             </tr>
  186.             <tr>
  187.                 <td class='labels'>
  188.                     <label for='ei-cache-expire-time'><?php _e( 'Cache Expire Time (minutes)', 'Easy_Instagram' ); ?></label>
  189.                 </td>  
  190.                 <td>
  191.                     <input type='text' name='ei_cache_expire_time' id='ei-cache-expire-time' value='<?php echo esc_html( $cache_expire_time ); ?>' />
  192.                     <br />
  193.                     <span class='info'>
  194.                         <?php printf( __( 'Minimum expire time: %d minute.',
  195.                                             'Easy_Instagram' ),
  196.                                         self::$minimum_cache_expire_minutes ); ?>
  197.                     </span>
  198.                 </td>
  199.             </tr>
  200.             <tr>
  201.                 <td>
  202.                     <input type='hidden' name='ei_general_settings' value='1' />
  203.                     <?php wp_nonce_field( 'ei_general_settings_nonce', 'ei_general_settings_nonce' ); ?>
  204.                 </td>
  205.                 <td>
  206.                     <input type='submit' value='<?php _e( "Save Settings" , "Easy_Instagram" ) ?>' name='submit' />
  207.                 </td>
  208.             </tr>
  209.         </table>
  210.     </form>
  211.     <form method='POST' action='' class='easy-instagram-settings-form'>
  212.         <table class='easy-instagram-settings'>
  213.         <?php if ( empty( $access_token ) ) : ?>
  214.             <tr>
  215.                 <td colspan='2'><h3><?php _e( 'Instagram Account', 'Easy_Instagram' ); ?></h3></td>
  216.             </tr>
  217.             <tr>
  218.                 <td>
  219.                     <?php if ( !empty( $instagram_client_id )
  220.                         && !empty( $instagram_client_secret )
  221.                         && ! empty( $instagram_redirect_uri ) ): ?>
  222.                         <?php $authorization_url = $instagram->getAuthorizationUrl(); ?>
  223.                         <a href="<?php echo $authorization_url;?>"><?php _e( 'Instagram Login' );?></a>
  224.                     <?php else: ?>
  225.                         <?php _e( 'Please configure the General Settings first', 'Easy_Instagram' ); ?>
  226.                     <?php endif; ?>
  227.                 </td>  
  228.                 <td>
  229.                 </td>          
  230.             </tr>
  231.         <?php else: ?>
  232.             <?php list( $username, $user_id ) = self::get_instagram_user_data(); ?>
  233.                 <tr>
  234.                     <td colspan='2'><h3><?php _e( 'Instagram Account', 'Easy_Instagram' ); ?></h3></td>
  235.                 </tr>
  236.                 <tr>
  237.                     <td class='labels'>
  238.                         <label><?php _e( 'Instagram Username', 'Easy_Instagram' ); ?></label>
  239.                     </td>
  240.                     <td>
  241.                         <?php echo $username; ?>   
  242.                     </td>
  243.                 </tr>
  244.                 <tr>
  245.                     <td class='labels'>
  246.                         <label><?php _e( 'Instagram User ID', 'Easy_Instagram' ); ?></label>
  247.                     </td>
  248.                     <td>
  249.                         <?php echo $user_id; ?>
  250.                     </td>
  251.                 </tr>
  252.                 <tr>
  253.                     <td>
  254.                         <?php wp_nonce_field( 'ei_user_logout_nonce', 'ei_user_logout_nonce' ); ?>
  255.                     </td>
  256.                     <td>
  257.                         <input type='submit' name='instagram-logout' value="<?php _e( 'Instagram Logout' );?>" />
  258.                     </td>
  259.                 </tr>              
  260.         <?php endif; ?>
  261.         </table>
  262.     </form>    
  263. <?php      
  264.     }
  265.     //=========================================================================
  266.     static function set_instagram_user_data( $username, $id ) {
  267.         update_option( 'easy_instagram_username', $username );
  268.         update_option( 'easy_instagram_user_id', $id );
  269.     }
  270.     //=========================================================================
  271.     static function get_instagram_user_data() {
  272.         $username = get_option( 'easy_instagram_username' );
  273.         $user_id = get_option( 'easy_instagram_user_id' );
  274.         return array( $username, $user_id );
  275.     }
  276.     //=========================================================================
  277.     static function set_access_token( $access_token ) {
  278.         update_option( 'easy_instagram_access_token', $access_token );
  279.     }
  280.     //=========================================================================
  281.     static function get_access_token() {
  282.         return get_option( 'easy_instagram_access_token' );
  283.     }
  284.     //=========================================================================
  285.     static function get_live_user_data( $instagram, $user_id, $limit = 1 ) {
  286.         if ( $limit > self::$max_images ) {
  287.             $limit = self::$max_images;
  288.         }
  289.         $live_data = $instagram->getUserRecent( $user_id );
  290.         $recent = json_decode( $live_data );
  291.         if ( empty( $recent ) ) {
  292.             $live_data = NULL;
  293.         }              
  294.         else {
  295.             $live_data = array_slice( $recent->data, 0, $limit );
  296.         }
  297.         return $live_data;
  298.     }
  299.     //=========================================================================
  300.     static function get_live_tag_data( $instagram, $tag, $limit = 1 ) {
  301.         if ( $limit > self::$max_images ) {
  302.             $limit = self::$max_images;
  303.         }
  304.         $live_data = $instagram->getRecentTags( $tag );
  305.         $recent = json_decode( $live_data );
  306.         if ( empty( $recent ) || !isset( $recent->data ) ) {
  307.             $live_data = NULL;
  308.         }              
  309.         else {
  310.             $live_data = array_slice( $recent->data, 0, $limit );
  311.         }
  312.         return $live_data;
  313.     }
  314.     //=========================================================================
  315.    
  316.     static function shortcode( $attributes ) {
  317.         extract(
  318.             shortcode_atts(
  319.                 array(
  320.                     'tag'               => '',
  321.                     'user_id'           => '',
  322.                     'limit'             => 1,
  323.                     'caption_hashtags'  => 'true'
  324.                 ),
  325.                 $attributes
  326.             )
  327.         );
  328.        
  329.         $caption_hashtags = strtolower( $caption_hashtags );
  330.         return self::generate_content( $tag, $user_id, $limit, $caption_hashtags );
  331.     }
  332.     //=========================================================================
  333.    
  334.     static function generate_content( $tag, $user_id, $limit, $caption_hashtags ) {
  335.         if ( empty( $tag ) && empty( $user_id ) ) {
  336.             return '';
  337.         }
  338.         $access_token = self::get_access_token();
  339.         if ( empty( $access_token ) ) {
  340.             return '';
  341.         }
  342.         $out = '';
  343.         $config = self::get_instagram_config();
  344.         $instagram = new MC_Instagram_Connector( $config );
  345.         $instagram->setAccessToken( $access_token );
  346.         if ( ! empty( $user_id ) ) {
  347.             list( $data, $expired ) = self::get_cached_data_for_id_or_tag( $user_id, $limit, 'id' );
  348.            
  349.             if ( $expired ) {
  350.                 $live_data = self::get_live_user_data( $instagram, $user_id, $limit );
  351.                 if ( ! empty( $live_data ) ) {
  352.                     self::clear_cache( $user_id, 'id' );
  353.                 }
  354.                 else {
  355.                     $live_data = NULL;
  356.                 }
  357.             }
  358.             elseif ( NULL == $data ) {
  359.                 $live_data = self::get_live_user_data( $instagram, $user_id, $limit );
  360.             }
  361.            
  362.             $cache_index = 'id' . $user_id;        
  363.         }
  364.         else {
  365.             if ( ! empty( $tag ) ) {
  366.                 list( $data, $expired ) = self::get_cached_data_for_id_or_tag( $tag, $limit, 'tag' );
  367.                 if ( $expired ) {
  368.                     $live_data = self::get_live_tag_data( $instagram, $tag, $limit );
  369.                     if ( ! empty( $live_data ) ) {
  370.                         self::clear_cache( $tag, 'tag' );
  371.                     }
  372.                     else {
  373.                         $live_data = NULL;
  374.                     }
  375.                 }
  376.                 elseif ( NULL == $data ) {
  377.                     $live_data = self::get_live_tag_data( $instagram, $tag, $limit );
  378.                 }
  379.                 $cache_index = 'tag' . $tag;
  380.             }
  381.         }
  382.         if ( isset( $live_data ) && !empty( $live_data ) ) {
  383.             $hash = md5( $cache_index );
  384.             $timestamp = time();
  385.             $cache_data = array( 'cache_timestamp' => $timestamp );
  386.             $cache_data['data'] = array();
  387.             foreach ( $live_data as $elem ) {
  388.                 if ( isset( $elem->caption ) ) {
  389.                     $caption_text = isset( $elem->caption->text ) ? trim( $elem->caption->text ) : '';
  390.                     $caption_from = '';
  391.                    
  392.                     if ( isset( $elem->caption->from ) ) {
  393.                         if ( isset( $elem->caption->from->full_name ) ) {
  394.                             $caption_from = $elem->caption->from->full_name;
  395.                         }
  396.                         if ( empty( $caption_from ) && isset( $elem->caption->from->username ) ) {
  397.                             $caption_from = $elem->caption->from->username;
  398.                         }
  399.                     }
  400.                     if ( empty( $caption_from ) ) {
  401.                         if ( isset( $elem->user ) ) {
  402.                             if ( isset( $elem->user->full_name ) ) {
  403.                                 $caption_from = $elem->user->full_name;
  404.                             }
  405.                             if ( empty( $caption_from ) && isset( $elem->user->username ) ) {
  406.                                 $caption_from = $elem->user->username;
  407.                             }
  408.                         }
  409.                     }
  410.                     $caption_created_time = isset( $elem->caption->created_time ) ? $elem->caption->created_time : time();
  411.                 }
  412.                 else {
  413.                     $caption_text = '';
  414.                     $caption_from = '';
  415.                     $caption_created_time = time();
  416.                 }
  417.                
  418.                 $cached_elem = array(
  419.                     'link'                  => isset( $elem->link ) ? $elem->link : '#',
  420.                     'caption_text'          => $caption_text,
  421.                     'caption_from'          => $caption_from,
  422.                     'created_time'          => $elem->created_time,
  423.                     'caption_created_time'  => $caption_created_time
  424.                 );
  425.                 $images = $elem->images;
  426.                 if ( isset( $images->low_resolution ) ) {
  427.                     $cached_elem['low_resolution'] = array(
  428.                         'width'     => $images->low_resolution->width,
  429.                         'height'    => $images->low_resolution->height
  430.                     );
  431.                     $local_url = self::save_remote_image(
  432.                         $images->low_resolution->url,
  433.                         'low_resolution'
  434.                     );
  435.                     if ( NULL == $local_url ) {
  436.                         $cached_elem['low_resolution']['url'] = $images->low_resolution->url;
  437.                     }
  438.                     else {
  439.                         $cached_elem['low_resolution']['url'] = $local_url;
  440.                     }
  441.                 }
  442.                 if ( isset( $images->thumbnail ) ) {
  443.                     $cached_elem['thumbnail'] = array(
  444.                         'width'     => $images->thumbnail->width,
  445.                         'height'    => $images->thumbnail->height
  446.                     );
  447.                        
  448.                     $local_url = self::save_remote_image(
  449.                         $images->thumbnail->url,
  450.                         'thumbnail'
  451.                     );
  452.                     if ( NULL == $local_url ) {
  453.                         $cached_elem['thumbnail']['url'] = $images->thumbnail->url;
  454.                     }
  455.                     else {
  456.                         $cached_elem['thumbnail']['url'] = $local_url;
  457.                     }
  458.                 }
  459.                 if ( isset( $images->standard_resolution ) ) {
  460.                     $cached_elem['standard_resolution'] = array(
  461.                         'width'     => $images->standard_resolution->width,
  462.                         'height'    => $images->standard_resolution->height
  463.                     );
  464.                        
  465.                     $local_url = self::save_remote_image(
  466.                         $images->standard_resolution->url,
  467.                         'standard_resolution'
  468.                     );
  469.                     if ( NULL == $local_url ) {
  470.                         $cached_elem['standard_resolution']['url'] = $images->standard_resolution->url;
  471.                     }
  472.                     else {
  473.                         $cached_elem['standard_resolution']['url'] = $local_url;
  474.                     }
  475.                 }
  476.                 $cache_data['data'][] = $cached_elem;
  477.             }
  478.             self::cache_data( $cache_index, $cache_data );
  479.             $instagram_elements = $cache_data['data'];
  480.         }
  481.         else {
  482.             if ( ! empty( $data ) ) {
  483.                 $instagram_elements = $data['data'];
  484.             }
  485.         }
  486.         if ( isset( $instagram_elements ) ) {
  487.             $crt = 0;
  488.             foreach ( $instagram_elements as $elem ) {
  489.                 $image_url = $elem['thumbnail']['url'];
  490.                 $width = $elem['thumbnail']['width'];
  491.                 $height = $elem['thumbnail']['height'];
  492.                 $out .= '<div class="easy-instagram-thumbnail-wrapper">';
  493.                 $out .= '<img src="' . $image_url . '" alt="" style="width:'
  494.                     . $width. 'px; height: ' . $height . 'px;" class="easy-instagram-thumbnail" />';
  495.                 $out .= '<div class="easy-instagram-thumbnail-author">by ' . $elem['caption_from'] . '</div>';
  496.                 $caption_text = $elem['caption_text'] ;
  497.                 if ( 'false' == $caption_hashtags ) {
  498.                     $caption_text = preg_replace( '/#[^\\s]+/', '', $caption_text );
  499.                     $caption_text = trim( $caption_text );
  500.                 }              
  501.                 $out .= '<div class="easy-instagram-thumbnail-caption">' . $caption_text . '</div>';
  502.                 $elem_time = ( $elem['caption_created_time'] > $elem['created_time'] )
  503.                             ? $elem['caption_created_time'] : $elem['created_time'];
  504.                 $out .= '<div class="easy-instagram-thumbnail-time">'
  505.                     . self::relative_time( $elem_time )
  506.                     . __( ' using Instagram', 'Easy_Instagram' )
  507.                     . '</div>';
  508.                 $out .= '</div>';
  509.                 $crt++;
  510.                 if ( $crt >= $limit ) {
  511.                     break;
  512.                 }
  513.             }      
  514.         }
  515.         return $out;   
  516.     }
  517.     //=========================================================================
  518.     static public function get_cache_dir() {
  519.         return EASY_INSTAGRAM_PLUGIN_PATH . '/' . self::$cache_dir;
  520.     }
  521.     //=========================================================================
  522.     static function cache_data( $id_or_tag, $data ) {
  523.         $timestamp = time();
  524.         $hash = md5( $id_or_tag );
  525.         $path = self::get_cache_dir() . $hash . '.cache';
  526.         $handle = fopen( $path, 'w' );
  527.         if ( FALSE === $handle ) {
  528.             return FALSE;
  529.         }
  530.         $serialized = serialize( $data );
  531.         $would_block = TRUE;
  532.         if ( flock( $handle, LOCK_EX, $would_block ) ) {
  533.             fwrite( $handle, $serialized );
  534.             fflush( $handle );
  535.             flock( $handle, LOCK_UN ); // release the lock
  536.         }
  537.         else {
  538.             error_log( 'Couldn\'t get the lock in cache_data.' );
  539.         }
  540.         fclose( $handle );
  541.         return TRUE;   
  542.     }
  543.     //=========================================================================
  544.     // Returns the cached data and a flag telling if the data expired
  545.     static function get_cached_data_for_id_or_tag( $id_or_tag, $limit, $type = 'id' ) {
  546.         $now = time();
  547.         $hash = md5( $type . $id_or_tag );
  548.         $path = self::get_cache_dir() . $hash . '.cache';
  549.         if ( !file_exists( $path ) ) {
  550.             return array( NULL, FALSE );
  551.         }
  552.         $handle = fopen( $path, 'r' );
  553.         if ( flock( $handle, LOCK_SH ) ) { 
  554.             $data = fgets( $handle );
  555.             flock( $handle, LOCK_UN ); // release the lock
  556.         }
  557.         else {
  558.             error_log( 'Couldn\'t get the lock in get_cached_data_for_id_or_tag.' );
  559.         }
  560.         if ( !empty( $data ) ) {
  561.             $cached_data = unserialize( $data );
  562.         }
  563.         fclose( $handle );
  564.         if ( !isset( $cached_data ) || !isset( $cached_data['data'] ) || !isset( $cached_data['cache_timestamp'] ) ) {
  565.             return array( NULL, FALSE ); //No cached data found
  566.         }
  567.         // If limit is greater than the cached data size, force clear cache
  568.         if ( $limit > count( $cached_data['data'] ) ) {
  569.             return array( $cached_data, TRUE );
  570.         }
  571.         $cache_minutes = self::get_cache_refresh_minutes();
  572.         $delta = ( $now - $cached_data['cache_timestamp'] ) / 60;
  573.         if ( $delta > $cache_minutes ) {
  574.             return array( $cached_data, TRUE );
  575.         }
  576.         else {
  577.             return array( $cached_data, FALSE );
  578.         }
  579.     }
  580.     //=========================================================================
  581.     static function clear_cache( $id_or_tag, $type ) {
  582.         $hash = md5( $type . $id_or_tag );
  583.         $cache_dir = self::get_cache_dir();
  584.         $path = $cache_dir . $hash . '.cache';
  585.         if ( file_exists( $path ) ) {
  586.             $handle = fopen( $path, 'r' );
  587.             if ( flock( $handle, LOCK_EX ) ) {
  588.                 $data = fread( $handle, filesize( $path ) );
  589.             }
  590.             if ( !empty( $data ) ) {
  591.                 $cached_data = unserialize( $data );
  592.             }
  593.             fclose( $handle );
  594.             unlink( $path );   
  595.    
  596.             $file_types = array( 'thumbnail', 'low_resolution', 'standard_resolution' );
  597.             if ( isset( $cached_data ) && isset( $cached_data['data'] ) ) {
  598.                 foreach ( $cached_data['data'] as $elem ) {
  599.                     //Delete images
  600.                     foreach ( $file_types as $file_type ) {
  601.                         if ( isset( $elem[$file_type] ) && isset( $elem[$file_type]['url'] ) ) {
  602.                             // Extract the file name from the file URL and look for the file in the cache directory
  603.                             $file_path = $cache_dir . basename( $elem[$file_type]['url'] );
  604.                             if ( file_exists( $file_path ) ) {
  605.                                 unlink( $file_path );
  606.                             }
  607.                         }
  608.                     }
  609.                 }
  610.             }
  611.         }
  612.     }
  613.     //=========================================================================
  614.     static function save_remote_image( $remote_image_url, $id ) {
  615.         $filename = '';
  616.         if ( preg_match( '/([^\/\.\?\&]+)\.([^\.\?\/]+)(\?[^\.\/]*)?$/', $remote_image_url, $matches ) ) {
  617.             $filename .= $matches[1] . '_' . $id . '.' . $matches[2];
  618.         }
  619.         else {
  620.             return NULL;
  621.         }
  622.         $path = self::get_cache_dir() . $filename;
  623.         $content = file_get_contents( $remote_image_url );
  624.         if ( FALSE == $content ) {
  625.             return NULL;
  626.         }
  627.        
  628.         if ( FALSE == file_put_contents( $path, $content ) ) {
  629.             return NULL;
  630.         }
  631.         return plugins_url( self::$cache_dir . $filename, __FILE__ );
  632.     }
  633.     //=========================================================================
  634.     static function get_cache_refresh_minutes() {
  635.         return get_option( 'easy_instagram_cache_expire_time', self::$default_cache_expire_minutes );
  636.     }
  637.     //=========================================================================    
  638.     static function set_cache_refresh_minutes( $minutes = 0 ) {
  639.         if ( 0 == $minutes ) {
  640.             $minutes = self::$default_cache_expire_minutes;
  641.         }
  642.         update_option( 'easy_instagram_cache_expire_time', (int) $minutes );
  643.     }
  644.     //=========================================================================
  645.     static function relative_time( $timestamp ) {
  646.         $difference = time() - $timestamp;
  647.         $periods = array( "sec", "min", "hour", "day", "week", "month", "years", "decade" );
  648.         $lengths = array( "60", "60", "24", "7", "4.35", "12", "10" );
  649.         if ($difference > 0) { // this was in the past
  650.             $ending = "ago";
  651.         } else { // this was in the future
  652.             $difference = -$difference;
  653.             $ending = "to go";
  654.         }
  655.         for( $j = 0; $difference >= $lengths[$j]; $j++ ) {
  656.             $difference /= $lengths[$j];
  657.         }
  658.         $difference = round( $difference );
  659.         if($difference != 1) {
  660.             $periods[$j] .= "s";
  661.         }
  662.        
  663.         $text = "$difference $periods[$j] $ending";
  664.         return $text;
  665.     }      
  666.     //=====================================================================
  667.     static function plugin_activation() {
  668.         wp_schedule_event(
  669.             current_time( 'timestamp' ),
  670.             'daily',
  671.             'easy_instagram_clear_cache_event'
  672.         ); 
  673.     }
  674.    
  675.     //=====================================================================
  676.    
  677.     static function clear_expired_cache_action() {
  678.         $valid_files = array();
  679.         $cache_dir = self::get_cache_dir();
  680.         $files = scandir( $cache_dir );
  681.         if ( ! empty( $files ) ) {
  682.             foreach ( $files as $file ) {
  683.                 if ( preg_match( '/\.cache$/', $file ) ) {
  684.                     $ret = self::remove_cache_file( $file );
  685.                     if ( ! empty( $ret ) ) {
  686.                         $valid_files = array_merge( $valid_files, $ret );
  687.                     }
  688.                 }
  689.             }
  690.             // Remove all the files from the cache folder not in the valid files array (or valid files is empty)
  691.             foreach ( $files as $file ) {
  692.                 if ( ( '.' != $file ) && ( '..' != $file ) ) {
  693.                     if ( ! in_array( $file, $valid_files ) ) {
  694.                         $file_path = $cache_dir . '/' . $file;
  695.                         if ( file_exists( $file_path ) ) {
  696.                             unlink( $file_path );
  697.                         }
  698.                     }
  699.                 }
  700.             }
  701.         }
  702.     }
  703.     //=====================================================================
  704.     static function remove_cache_file( $filename ) {
  705.         $cache_dir = self::get_cache_dir() ;
  706.         $path = $cache_dir . $filename;
  707.        
  708.         $handle = fopen( $path, 'r' );
  709.         if ( flock( $handle, LOCK_EX ) ) {
  710.             $data = fread( $handle, filesize( $path ) );
  711.         }
  712.         if ( !empty( $data ) ) {
  713.             $cached_data = unserialize( $data );
  714.         }
  715.         fclose( $handle );
  716.         $now = time();
  717.         $delta = ( $now - $cached_data['cache_timestamp'] ) / 60;
  718.         $file_types = array( 'thumbnail', 'low_resolution', 'standard_resolution' );
  719.         $valid_files = array();
  720.         if ( ! isset( $cached_data ) ) {
  721.             return $valid_files;
  722.         }
  723.         if ( $delta > 24 * 60 ) {
  724.             if ( !empty( $cached_data['data'] ) ) {
  725.                 foreach ( $cached_data['data'] as $elem ) {
  726.                     //Delete images                
  727.                     foreach ( $file_types as $file_type ) {
  728.                         if ( isset( $elem[$file_type] ) && isset( $elem[$file_type]['url'] ) ) {
  729.                             // Extract the file name from the file URL and look for the file in the cache directory
  730.                             $file_path = $cache_dir . basename( $elem[$file_type]['url'] );
  731.                             if ( file_exists( $file_path ) ) {
  732.                                 unlink( $file_path );
  733.                             }
  734.                         }
  735.                     }
  736.                 }
  737.             }
  738.            
  739.             unlink( $path );
  740.         }
  741.         else {
  742.             if ( ! empty( $cached_data['data'] ) ) {
  743.                 foreach ( $cached_data['data'] as $elem ) {
  744.                     foreach ( $file_types as $file_type ) {
  745.                         if ( isset( $elem[$file_type]['url'] ) ) {
  746.                             $filename = basename( $elem[$file_type]['url'] );
  747.                             $file_path = $cache_dir . $filename;
  748.                             if ( file_exists( $file_path ) ) {
  749.                                 $valid_files[] = $filename;
  750.                             }
  751.                         }
  752.                     }
  753.                 }
  754.                 $valid_files[] = $path;
  755.             }
  756.             $valid_files[] = $filename; //Keep the cache file as valid
  757.         }
  758.        
  759.         return $valid_files;
  760.     }
  761.     //=====================================================================
  762.    
  763.     static function plugin_deactivation() {
  764.         wp_clear_scheduled_hook( 'easy_instagram_clear_cache_event' );
  765.     }
  766. }
  767. /*
  768.  * Easy Instagram Widget
  769.  */
  770. class Easy_Instagram_Widget extends WP_Widget {
  771.     public function __construct() {
  772.         parent::__construct(
  773.             'easy_instagram_widget_base',
  774.             'Easy Instagram',
  775.             array(
  776.                 'description' => 'Display one or more images from Instagram based on a tag or Instagram user id',
  777.                 'class' => 'easy-instagram-widget'
  778.             )
  779.         );
  780.     }
  781.     //==========================================================================
  782.     public function form( $instance ) {
  783.         if ( isset( $instance['type'] ) ) {
  784.             $type = $instance['type'];
  785.         }
  786.         else {
  787.             $type = 'tag';
  788.         }
  789.        
  790.         if ( isset( $instance['value'] ) ) {
  791.             $value = $instance['value'];
  792.         }
  793.         else {
  794.             $value = '';
  795.         }
  796.         if ( isset( $instance['limit'] ) ) {
  797.             $limit = $instance['limit'];
  798.         }
  799.         else {
  800.             $limit = 1;
  801.         }
  802.         if ( $limit > Easy_Instagram::$max_images ) {
  803.             $limit = Easy_Instagram::$max_images;
  804.         }
  805.         if ( isset( $instance['caption_hashtags'] ) ) {
  806.             $caption_hashtags = $instance['caption_hashtags'];
  807.         }
  808.         else {
  809.             $caption_hashtags = 'true';
  810.         }      
  811. ?>
  812.         <p>
  813.         <label for="<?php echo $this->get_field_id( 'type' ); ?>"><?php _e( 'Type:' ); ?></label>
  814.         <select class="widefat" id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>">
  815.             <?php $selected = ( 'tag' == $type ) ? 'selected="selected"' : ''; ?>
  816.             <option value="tag" <?php echo $selected;?>><?php _e( 'Tag' ); ?></option>
  817.            
  818.             <?php $selected = ( 'user_id' == $type ) ? 'selected="selected"' : ''; ?>
  819.             <option value="user_id" <?php echo $selected;?>><?php _e( 'User ID' ); ?></option>
  820.         </select>
  821.         </p>
  822.        
  823.         <p>
  824.         <label for="<?php echo $this->get_field_id( 'value' ); ?>"><?php _e( 'Value:' ); ?></label>
  825.         <input type='text' class="widefat" id="<?php echo $this->get_field_id( 'value' ); ?>" name="<?php echo $this->get_field_name( 'value' ); ?>" value="<?php _e( $value ); ?> " />
  826.         </p>
  827.        
  828.         <p>
  829.         <label for="<?php echo $this->get_field_id( 'limit' ); ?>"><?php _e( 'Images:' ); ?></label>
  830.         <select class="widefat" id="<?php echo $this->get_field_id( 'limit' ); ?>" name="<?php echo $this->get_field_name( 'limit' ); ?>">
  831.         <?php for ( $i=1; $i<= Easy_instagram::$max_images; $i++ ): ?>
  832.        
  833.         <?php printf(
  834.             '<option value="%s"%s>%s</option>',
  835.                 $i,
  836.                 selected( $limit, $i, false ),
  837.                 $i );
  838.         ?>
  839.        
  840.         <?php endfor; ?>
  841.         </select>
  842.         </p>
  843.         <p>
  844.         <label for="<?php echo $this->get_field_id( 'caption_hashtags' ); ?>"><?php _e( 'Show Caption Hashtags:' ); ?></label>
  845.         <select class="widefat" id="<?php echo $this->get_field_id( 'caption_hashtags' ); ?>" name="<?php echo $this->get_field_name( 'caption_hashtags' ); ?>">
  846.             <?php $selected = ( 'true' == $caption_hashtags ) ? 'selected="selected"' : ''; ?>
  847.             <option value="true" <?php echo $selected;?>><?php _e( 'Yes' ); ?></option>
  848.            
  849.             <?php $selected = ( 'false' == $caption_hashtags ) ? 'selected="selected"' : ''; ?>
  850.             <option value="false" <?php echo $selected;?>><?php _e( 'No' ); ?></option>
  851.         </select>
  852.         </p>
  853. <?php
  854.        
  855.     }
  856.     //==========================================================================
  857.     public function update( $new_instance, $old_instance ) {
  858.         $instance = array();
  859.         $instance['type']               = strip_tags( $new_instance['type'] );
  860.         $instance['value']              = trim( strip_tags( $new_instance['value'] ) );
  861.         $instance['limit']              = strip_tags( $new_instance['limit'] );    
  862.         $instance['caption_hashtags']   = $new_instance['caption_hashtags'];
  863.         return $instance;
  864.     }
  865.     //==========================================================================
  866.    
  867.     public function widget( $args, $instance ) {
  868.         extract( $args );
  869.         echo $before_widget;
  870.        
  871.         $tag = '';
  872.         $user_id = '';
  873.         $limit = 1;
  874.         $caption_hashtags = 'true';
  875.        
  876.         if ( 'tag' == $instance['type'] ) {
  877.             $tag = trim( $instance['value'] );
  878.             $user_id = '';
  879.         }
  880.         else {
  881.             $tag = '';
  882.             $user_id = $instance['value'];
  883.         }
  884.        
  885.         if ( isset( $instance['limit'] ) ) {
  886.             $limit = (int) $instance['limit'];
  887.             if ( $limit > Easy_Instagram::$max_images ) {
  888.                 $limit = Easy_Instagram::$max_images;
  889.             }
  890.         }
  891.        
  892.         if ( isset( $instance['caption_hashtags'] ) ) {
  893.             $caption_hashtags = $instance['caption_hashtags'];
  894.         }
  895.         $content = Easy_Instagram::generate_content( $tag, $user_id, $limit, $caption_hashtags );
  896.        
  897.         echo $content;
  898.        
  899.         echo $after_widget;
  900.     }
  901.     //==========================================================================
  902. }
  903. add_action( 'widgets_init', create_function( '', 'register_widget( "Easy_Instagram_Widget" );' ) );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement