Advertisement
Guest User

Facebook Album 4 pages

a guest
Dec 16th, 2014
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 20.43 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Facebook Albums
  4. Plugin URI: http://glamanate.com/wordpress/facebook-album/?utm_source=fbalbum_pluginspage&utm_medium=website&utm_campaign=fbalbum
  5. Description: Facebook Albums allows you to display Facebook Albums on your WordPress site. Brought to you by <a href="http://dooleyandassociates.com/?utm_source=fbalbum&utm_medium=referral&utm_campaign=Facebook%2BAlbum">Dooley & Associates</a>
  6. Version: 2.0.5.3a
  7. Author: Matt Glaman
  8. Author URI: http://glamanate.com
  9.  
  10.  
  11. Copyright 2012  Matt Glaman  (email : nmd.matt@gmail.com)
  12.  
  13. This program is free software; you can redistribute it and/or modify
  14. it under the terms of the GNU General Public License as published by
  15. the Free Software Foundation; either version 2 of the License, or
  16. (at your option) any later version.
  17.  
  18. This program is distributed in the hope that it will be useful,
  19. but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21. GNU General Public License for more details.
  22.  
  23. You should have received a copy of the GNU General Public License
  24. along with this program; if not, write to the Free Software
  25. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  26.  
  27. */
  28. if (!defined('DB_NAME')) {
  29.   header('HTTP/1.0 403 Forbidden');
  30.   die;
  31. }
  32.  
  33. add_action( 'plugins_loaded', 'myplugin_load_textdomain' );
  34. /**
  35.  * Load plugin textdomain.
  36.  *
  37.  * @since 2.0.5.3a
  38.  */
  39. function myplugin_load_textdomain() {
  40.   load_plugin_textdomain( 'facebook-albums', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
  41. }
  42.  
  43. if (!class_exists('Facebook'))
  44.   include dirname( __FILE__ ).'/inc/facebook-sdk/facebook.php';
  45.  
  46. include dirname( __FILE__ ).'/inc/widget.php';
  47.  
  48.  
  49. //Registers actions
  50. register_activation_hook(__FILE__, array('FB_Album', 'activate'));
  51. add_action('init', array('FB_Album', 'set_facebook_sdk'), 0);
  52. add_action( 'save_post', array('FB_Album', 'save_post') );
  53. class FB_Album {
  54.  
  55.   protected static $album_url;  //Stores the album URL in the class
  56.   protected static $album_id;   //Stores the album ID in the class
  57.   protected static $album_limit;  //Stores max number of photos, defaults to 1000.
  58.  
  59.   //The graph API URl the plugin will access. Script replaces {ALBUM_ID} with self::$album_id
  60.   protected static $graph_url = 'https://graph.facebook.com/{ALBUM_ID}/photos?fields=source,link,name,images,album&limit={LIMIT}';
  61.   //Stores plugin options, leave public for widget
  62.   public static $options;
  63.   //Stores SDK class..sloppily for now.
  64.   public static $facebook_sdk;
  65.  
  66.  
  67.   //Activated, let us save options
  68.   public static function activate() {
  69.     update_option('facebookalbum', FB_Album::default_options());
  70.   }
  71.   /**
  72.     * Default options to install, provides a fall back just in case.
  73.     * Decap from move to 2.0
  74.     */
  75.   public static function default_options() {
  76.     $default_options = array(
  77.       'order'   => get_option('fbalbum_order'),
  78.       'title'   => '',
  79.       'size'    => get_option('fbalbum_size', '5'), //New save structure, copy in previous value, if set, else set default
  80.       'photo_title' => 'false',
  81.       'colorbox'  => array(
  82.         'enabled'       => get_option('fbalbum_lightbox', 'true'), //New save structure, copy in previous value, if set, else set default
  83.         'width'       => "false",
  84.         'height'    => 'false',
  85.         'transition'    => 'elastic',
  86.         'speed'       => '350',
  87.         'opacity'     => '0.85',
  88.         'slideshow'     => 'false',
  89.         'slideshow-speed' => '2300',
  90.         'slideshow-auto'  => 'true'
  91.       ),
  92.       'pages' => get_option('fbalbum_pages', array()), //New save structure, copy in previous value, if set, else set default
  93.       'app_id' => '',
  94.       'app_secret' => '',
  95.       'access_token' => ''
  96.     );
  97.     return $default_options;
  98.   }
  99.  
  100.   /**
  101.     * Loads our options, defaults to base options if not set.
  102.     */
  103.   public static function load_options() {
  104.     self::$options = wp_parse_args( get_option('facebookalbum', self::default_options()), array(
  105.       'order'     => '',
  106.       'title'   => '',
  107.       'size'    => '5',
  108.       'photo_title'   => '',
  109.       'colorbox'  => array(
  110.           'enabled'     => 'true',
  111.           'width'       => 'false',
  112.           'height'    => 'false',
  113.           'transition'    => 'elastic',
  114.           'speed'     => '350',
  115.           'opacity'   => '0.85',
  116.           'slideshow'   => 'false',
  117.           'slideshow-speed' => '2300',
  118.           'slideshow-auto'  => 'true'
  119.         ),
  120.       'pages'   => array(),
  121.       'app_id'  => '',
  122.       'app_secret'  => '',
  123.       'access_token'  => ''
  124.       ) );
  125.   }
  126.  
  127.   /**
  128.     * Function to verify if we have the Facebook application ID and Secret loaded.
  129.     */
  130.   public static function verify_app_information() {
  131.     //This is might get called after reset, so refresh plugin options
  132.     self::load_options();
  133.     if(isset(self::$options['app_id']) && !empty(self::$options['app_id']) && isset(self::$options['app_secret']) && !empty(self::$options['app_secret']))
  134.       return true;
  135.     return false;
  136.   }
  137.  
  138.   //Shortcode callback
  139.   public static function shortcode_callback( $atts ) {
  140.  
  141.     //Defaults to null URL. If no limit set, default to 1000 (max album size, besides Timeline)
  142.     extract( shortcode_atts( array(
  143.       'url' => '', 'limit' => '1000'
  144.     ), $atts ) );
  145.     self::_set_album_url( $url );
  146.     self::$album_limit = $limit;
  147.     //Sets up album HTML. Gathers data from class variables.
  148.     return self::print_album();
  149.   }
  150.  
  151.   public static function save_post($post_id) {
  152.     if ( wp_is_post_revision( $post_id ) )
  153.       return;
  154.  
  155.     $post = get_post($post_id);
  156.     if(strpos($post->post_content, '[fbalbum ') !== FALSE) {
  157.       preg_match("/[fbalbum [^>]*url=(.+) /", $post->post_content, $output);
  158.       $facebook_album_url = str_replace('"', '', $output[1]);
  159.       FB_Album::_set_album_url($facebook_album_url);
  160.       $album_id = FB_Album::_get_album_id();
  161.       FB_Album::clear_cache($album_id);
  162.     }
  163.   }
  164.  
  165.   /**
  166.     * Builds HTML string to output album photos
  167.     */
  168.   public static function print_album() {
  169.       if(!self::_get_album_id() )
  170.         return 'Album ID was empty';
  171.      
  172.       if(!($fb = self::_get_graph_results(self::$album_limit, '')))
  173.         return;
  174.  
  175.       if(isset($fb['paging']['next']))
  176.         $paging_result = (self::_get_graph_results('', $fb['paging']['next']));
  177.  
  178.       if(isset($paging_result['paging']['next']))
  179.         $paging_result2 = (self::_get_graph_results('', $paging_result['paging']['next']));
  180.  
  181.       if(isset($paging_result2['paging']['next']))
  182.         $paging_result3 = (self::_get_graph_results('', $paging_result2['paging']['next']));
  183.        
  184.  
  185.       if(!isset($fb['data']) || !$fb['data']) {
  186.         return 'Facebook API came back with a faulty result. You may be accessing an album you do not have permissions to access.';
  187.       }
  188.       self::_enqueue_resources();
  189.  
  190.       $html = '<div class="facebook-album-container">';
  191.       if(self::$options['title']) $html .= '<h2><a href="' . self::_clean_url(self::_get_album_url()) . '" target="_blank"">' . $fb['data'][0]['album']['name'] . '</a></h2>';
  192.  
  193.       //Reverse array to show oldest to newest
  194.       if( isset(self::$options['order']) && !empty(self::$options['order']))
  195.         $fb['data'] = array_reverse($fb['data']);
  196.  
  197.       foreach ($fb['data'] as $img) {
  198.         $photo_title = (isset(self::$options['photo_title']) && isset($img['name'])) ? $img['name'] : '';
  199.         //Quick workaround to fix thumbnail resolution without causing issues on current saved data.
  200.         $thumb_size = self::$options['size'] - 1;
  201.         $thumbnail_src_url = self::check_thumbnail_src_size_url($img, $thumb_size);
  202.  
  203.         $html .= '<div class="facebook-album-wrapper" style="float: left;margin: 2px;">';
  204.         $html   .= '<a href="'. self::_clean_url($img['images'][1]['source']) . '" title="'. esc_attr($photo_title) .'" rel="lightbox" class="fbalbum cboxElement">';
  205.         $html   .= '<div class="image size-'. self::$options['size'] .'" style="background-image: url(' . self::_clean_url($thumbnail_src_url) . ')">&nbsp;</div>';
  206.         $html .= '</a>';
  207.         $html .= '</div>';
  208.       }
  209.      
  210.       if(isset($paging_result['data'])){
  211.  
  212.         foreach ($paging_result['data'] as $img) {
  213.  
  214.           $photo_title = (isset(self::$options['photo_title']) && isset($img['name'])) ? $img['name'] : '';
  215.           //Quick workaround to fix thumbnail resolution without causing issues on current saved data.
  216.           $thumb_size = self::$options['size'] - 1;
  217.           $thumbnail_src_url = self::check_thumbnail_src_size_url($img, $thumb_size);
  218.  
  219.           $html .= '<div class="facebook-album-wrapper" style="float: left;margin: 2px;">';
  220.           $html   .= '<a href="'. self::_clean_url($img['images'][1]['source']) . '" title="'. esc_attr($photo_title) .'" rel="lightbox" class="fbalbum cboxElement">';
  221.           $html   .= '<div class="image size-'. self::$options['size'] .'" style="background-image: url(' . self::_clean_url($thumbnail_src_url) . ')">&nbsp;</div>';
  222.           $html .= '</a>';
  223.           $html .= '</div>';
  224.         }
  225.       }
  226.  
  227.       if(isset($paging_result2['data'])){
  228.  
  229.         foreach ($paging_result2['data'] as $img) {
  230.  
  231.           $photo_title = (isset(self::$options['photo_title']) && isset($img['name'])) ? $img['name'] : '';
  232.           //Quick workaround to fix thumbnail resolution without causing issues on current saved data.
  233.           $thumb_size = self::$options['size'] - 1;
  234.           $thumbnail_src_url = self::check_thumbnail_src_size_url($img, $thumb_size);
  235.  
  236.           $html .= '<div class="facebook-album-wrapper" style="float: left;margin: 2px;">';
  237.           $html   .= '<a href="'. self::_clean_url($img['images'][1]['source']) . '" title="'. esc_attr($photo_title) .'" rel="lightbox" class="fbalbum cboxElement">';
  238.           $html   .= '<div class="image size-'. self::$options['size'] .'" style="background-image: url(' . self::_clean_url($thumbnail_src_url) . ')">&nbsp;</div>';
  239.           $html .= '</a>';
  240.           $html .= '</div>';
  241.         }
  242.       }
  243.  
  244.       if(isset($paging_result3['data'])){
  245.  
  246.         foreach ($paging_result3['data'] as $img) {
  247.  
  248.           $photo_title = (isset(self::$options['photo_title']) && isset($img['name'])) ? $img['name'] : '';
  249.           //Quick workaround to fix thumbnail resolution without causing issues on current saved data.
  250.           $thumb_size = self::$options['size'] - 1;
  251.           $thumbnail_src_url = self::check_thumbnail_src_size_url($img, $thumb_size);
  252.  
  253.           $html .= '<div class="facebook-album-wrapper" style="float: left;margin: 2px;">';
  254.           $html   .= '<a href="'. self::_clean_url($img['images'][1]['source']) . '" title="'. esc_attr($photo_title) .'" rel="lightbox" class="fbalbum cboxElement">';
  255.           $html   .= '<div class="image size-'. self::$options['size'] .'" style="background-image: url(' . self::_clean_url($thumbnail_src_url) . ')">&nbsp;</div>';
  256.           $html .= '</a>';
  257.           $html .= '</div>';
  258.         }
  259.       }
  260.  
  261.       $html .= '<div style="clear:both">&nbsp;</div>';
  262.       if(isset(self::$options['colorbox']['enabled']) && self::$options['colorbox']['enabled']) $html .= self::build_colorbox();
  263.       $html .="</div>";
  264.       return $html;
  265.   }
  266.  
  267.   /** Builds the Colorbox script initializer based off of options set
  268.     */
  269.   public static function build_colorbox() {
  270.     $colorbox = self::$options['colorbox'];
  271.     $colorbox = wp_parse_args( $colorbox, array( 'width' => '', 'height' => '', 'speed' => '', 'slideshow' => 'false') );
  272.     $width        = $colorbox['width'];
  273.     $height       = $colorbox['height'];
  274.     $transition       = $colorbox['transition'];
  275.     $speed      = $colorbox['speed'];
  276.     $opacity      = $colorbox['opacity'];
  277.     //$slideshow      = $colorbox['slideshow'];
  278.     //$slideshow_speed    = $colorbox['slideshow-speed'];
  279.     //$slideshow_auto     = $colorbox['slideshow-auto'];
  280.  
  281.     //TODO: Slideshow settings
  282.     $colorbox_slideshow  = get_option('fbalbum_colorbox_slideshow', 'false');
  283.     $colorbox_slideshow_speed = get_option('fbalum_colorbox_slidespeed', 2300);
  284.     $colorbox_slideshow_auto  = get_option('fbalbum_colorbox_slideauto', 'true');
  285.  
  286.     $script = '<script>';
  287.     $script .= ' jQuery(document).ready(function($) {';
  288.     $script .= "  $('.cboxElement').colorbox({";
  289.     $script .= "    rel: 'fbalbum', ";
  290.     $script .= "    width:  '{$width}',";
  291.     $script .= "    height: '{$height}', ";
  292.     $script .= "    maxHeight: '90%', ";
  293.     $script .= "    maxWidth: '90%', ";
  294.     $script .= "    transition: '{$transition}', ";
  295.     $script .= "    speed: '{$speed}', ";
  296.     $script .= "    opacity: '{$opacity}', ";
  297.     $script .= "    slideshow: {$colorbox_slideshow}, ";
  298.     $script .= "    slideshowSpeed: '{$colorbox_slideshow_speed}',";
  299.     $script .= "    slideshowAuto: {$colorbox_slideshow_auto},";
  300.     $script .= '  });';
  301.     $script .= ' });';
  302.     $script .= '</script>';
  303.     return $script;
  304.   }
  305.  
  306.   public static function set_facebook_sdk() {
  307.  
  308.     self::load_options();
  309.     if(!empty(self::$options['app_id']) && !empty(self::$options['app_secret'])) {
  310.       self::$facebook_sdk = new Facebook(array(
  311.             'appId'  => self::$options['app_id'],
  312.             'secret' => self::$options['app_secret'],
  313.       ));
  314.       if(self::$facebook_sdk->getUser()) {
  315.         try{
  316.  
  317.         }
  318.         catch (FacebookApiException $e) {
  319.           echo "<!--DEBUG: ".$e." :END-->";
  320.           error_log($e);
  321.         }
  322.       }
  323.  
  324.       if(!empty(self::$options['access_token'])) {
  325.         self::$facebook_sdk->setAccessToken(self::$options['access_token']);
  326.         self::$facebook_sdk->setExtendedAccessToken();
  327.         self::$options['access_token'] = FB_Album::$facebook_sdk->getAccessToken();
  328.         update_option('facebookalbum', self::$options);
  329.       }
  330.     }
  331.  
  332.     //Registers the short code to be placed within posts or pages.
  333.     add_shortcode( 'fbalbum', array('FB_Album', 'shortcode_callback') );
  334.     //Registers options page
  335.     add_action('admin_menu', array('FB_Album', '_setup_opt_menu'));
  336.   }
  337.  
  338.   /**
  339.     * Builds Facebook API string and returns JSON output
  340.     */
  341.   public static function _get_graph_results($limit, $newurl) {
  342.  
  343.     //if(self::get_api_cache())
  344.       //return self::get_api_cache();
  345.     if(!empty(self::$facebook_sdk)) {
  346.       try {
  347.         $api_call = '/'.self::_get_album_id().'/photos?fields=source,link,name,images,album&limit=' . $limit;
  348.         $album = self::$facebook_sdk->api($api_call);
  349.         if($album['data']) {
  350.           //We're good to go, let's cache the JSON
  351.           self::set_api_cache($album);
  352.         } else {
  353.           printf('<p>Please try entering <strong>%s</strong> into your URL bar and seeing if the page loads.', 'https://graph.facebook.com' . $api_call);
  354.         }
  355.       } catch (FacebookApiException $e) {
  356.         error_log($e);
  357.         print $e;
  358.  
  359.           $album = null;
  360.       }
  361.       return $album;
  362.     } else {
  363.       //Just in case the user did not set API access through a Facebook application      
  364.       if(isset($newurl) && $newurl != ''){
  365.         $facebook_graph_url = $newurl;
  366.       } else {
  367.         $facebook_graph_url = str_replace(array('{ALBUM_ID}', '{LIMIT}'), array(self::_get_album_id(), $limit), self::$graph_url);
  368.       }
  369.  
  370.       $album = self::decap_do_curl($facebook_graph_url);
  371.  
  372.       if(isset($album['data']) && !empty($album['data'])) {
  373.         //We're good to go, let's cache the JSON
  374.         self::set_api_cache($album);
  375.       } else {
  376.         printf('<p>Please try entering <strong>%s</strong> into your URL bar and seeing if the page loads.', $facebook_graph_url);
  377.       }
  378.  
  379.       return $album;
  380.     }
  381.   }
  382.  
  383.   public static function decap_do_curl($uri) {
  384.     $facebook_graph_results = null;
  385.     $facebook_graph_url = $uri; //TODO: Add URL checking here, else error out
  386.       //Attempt CURL
  387.       if (extension_loaded('curl')){
  388.         $ch = curl_init();
  389.         curl_setopt($ch,CURLOPT_URL, $facebook_graph_url);
  390.         curl_setopt($ch, CURLOPT_HEADER, 0);
  391.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  392.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  393.         if(!$facebook_graph_results = curl_exec($ch)) {
  394.           printf('<p>cURL Error: %1$s %2$s</p>', curl_errno($ch), curl_error($ch));
  395.           printf('<p>Please try entering <strong>%s</strong> into your URL bar and seeing if the page loads.', $facebook_graph_url);
  396.         }
  397.         if(curl_errno($ch) == 7) {
  398.           print '<p><strong>Your server cannot communicate with Facebook\'s servers. This means your server does not support IPv6 or is having issues resolving facebook.com. Please contact your hosting provider.';
  399.         }
  400.         curl_close($ch);
  401.       } else {
  402.         print ('Sorry, your server does not allow remote fopen or have CURL');
  403.       }
  404.     $facebook_graph_results = json_decode($facebook_graph_results, true);
  405.     return $facebook_graph_results;
  406.   }
  407.  
  408.   public static function _enqueue_resources() {
  409.     if(isset(self::$options['colorbox']['enabled']) && self::$options['colorbox']['enabled']) {
  410.       wp_enqueue_script('lightbox-js', plugins_url( '/js/colorbox/jquery.colorbox-min.js', __FILE__ ), array('jquery'));
  411.       wp_enqueue_style('lightbox-style', plugins_url( '/css/colorbox.css', __FILE__ ));
  412.     }
  413.       wp_enqueue_style('fbalbum-style', plugins_url( '/css/fbalbum.css', __FILE__ ));
  414.   }
  415.  
  416.   public static function _setup_opt_menu() {
  417.     add_options_page('Facebook Album', 'Facebook Album', 'publish_pages', 'facebook-album', array('FB_Album', '_options_page'), '', 25);
  418.     add_action('admin_enqueue_scripts', array('FB_Album', '_options_page_resources'));
  419.   }
  420.   public static function _options_page() {
  421.     include dirname( __FILE__ ).'/inc/options-facebookalbum.php';
  422.   }
  423.   public static function _options_page_resources($hook) {
  424.     if( 'settings_page_facebook-album' != $hook ) return;
  425.       wp_enqueue_style( 'facebookalbum.css', plugins_url('/css/admin-facebookalbum.css', __FILE__) );
  426.   }
  427.   /**
  428.     * Some pictures are too small and don't have everythumnail. This cycles to find the lowest one, exits out if thumb hits 0, just in case
  429.     */
  430.   public static function check_thumbnail_src_size_url( $img_array, $thumb_size ) {
  431.     while( !isset($img_array['images'][$thumb_size]['source']) || $thumb_size == 0 ) {
  432.       $thumb_size--;
  433.     }
  434.     return $img_array['images'][$thumb_size]['source'];
  435.  
  436.   }
  437.  
  438.   /**
  439.     * Finds and saves album ID by breaking apart the Facebook URL
  440.     * @return void
  441.     */
  442.   protected static function _find_album_id() {
  443.     if(!self::_get_album_url())
  444.         return;
  445.  
  446.     //Explodes URL based on slashes, we need the end of the URL
  447.     $facebook_album_id = explode('?set=', self::_get_album_url());
  448.     $facebook_album_id = $facebook_album_id['1'];
  449.     //Explodes section by periods, Album ID is first of the 3 sets of numbers
  450.     $facebook_album_id = explode('.', $facebook_album_id);
  451.     $facebook_album_id = $facebook_album_id['1'];
  452.  
  453.     self::_set_album_id( $facebook_album_id );
  454.   }
  455.  
  456.   /**
  457.     * Sets WordPress transient to cache API response
  458.     */
  459.   protected static function set_api_cache($json) {
  460.     //Just in case
  461.     if(!self::$album_id)
  462.       return;
  463.     $cache_lifetime = (isset(self::$options['cache'])) ? self::$options['cache'] * HOUR_IN_SECONDS : HOUR_IN_SECONDS;
  464.  
  465.     set_transient("fbalbum_".self::$album_id, $json, $cache_lifetime); //caching for 12 hours
  466.   }
  467.  
  468.   /**
  469.    * Clears the plugins cache
  470.    */
  471.   public static function clear_cache($album_id) {
  472.     delete_transient('fbalbum_' . $album_id);
  473.   }
  474.  
  475.   /**
  476.     * Gets WordPress transient of cached JSON response
  477.     **/
  478.   protected static function get_api_cache() {
  479.     return get_transient("fbalbum_".self::$album_id);
  480.   }
  481.  
  482.   /**
  483.     * Sets $album_url within class.
  484.     * @param url
  485.     * @return void
  486.     */
  487.   public static function _set_album_url( $url ) {
  488.       self::$album_url = $url;
  489.       self::_find_album_id();
  490.   }
  491.   /**
  492.     * Gets $album_url from within class
  493.     * @return url
  494.     */ public static function _get_album_url() { return self::$album_url; }
  495.   /**
  496.   * Sets $album_id within class
  497.   * @param id
  498.   * @return void
  499.   */
  500.   public static function _set_album_id( $id ) { self::$album_id = $id; }
  501.   /**
  502.   * Gets $album_url from within class
  503.   */
  504.   public static function _get_album_id() { return self::$album_id; }
  505.   /**
  506.   * Makes URLs validator friendly by replacing & to &amp;
  507.   * @param url
  508.   * @return string
  509.   */
  510.   public static function _clean_url( $url ) {
  511.   return str_replace('&', '&amp;', $url);
  512.   }
  513. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement