Advertisement
bradvin

simple-social-buttons.php

Feb 28th, 2012
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 17.48 KB | None | 0 0
  1. <?php
  2.  /*
  3.     Plugin Name: Simple Social Buttons
  4.     Plugin URI: http://blog.rabinek.pl/simple-social-buttons-wordpress/
  5.     Description: Insert social buttons into posts and archives: Facebook "Like it", Google Plus One "+1" and Twitter share.
  6.     Author: Paweł Rabinek
  7.     Version: 999
  8.     Author URI: http://blog.rabinek.pl/
  9. */
  10.  
  11. /*  Copyright 2011, Paweł Rabinek (xradar)  (email : pawel@rabinek.pl)
  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, version 2, as
  15.     published by the Free Software Foundation.
  16.  
  17.     This program is distributed in the hope that it will be useful,
  18.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  19.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  20.     GNU General Public License for more details.
  21.  
  22.     You should have received a copy of the GNU General Public License
  23.     along with this program; if not, write to the Free Software
  24.     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  25. */
  26.  
  27. /**
  28.  * HACK: Converted to class, added buttons ordering, improve saving settings
  29.  * @author Fabian Wolf
  30.  * @link http://usability-idealist.de/
  31.  * @since 1.3
  32.  * @requires PHP 5
  33.  */
  34.  
  35.  
  36. class SimpleSocialButtonsPR {
  37.     var $pluginName = 'Simple Social Buttons';
  38.     var $pluginVersion = '1.5';
  39.     var $pluginPrefix = 'ssb_pr_';
  40.     var $hideCustomMetaKey = '_ssb_hide';
  41.   var $showCustomMetaKey = '_ssb_show';
  42.    
  43.     // plugin default settings
  44.     var $pluginDefaultSettings = array(
  45.         'googleplus' => '1',
  46.         'fblike' => '2',
  47.         'twitter' => '3',
  48.         'beforepost' => '1',
  49.         'afterpost' => '0',
  50.         'beforepage' => '1',
  51.         'afterpage' => '0',
  52.         'beforearchive' => '0',
  53.         'afterarchive' => '0'
  54.     );
  55.  
  56.     // defined buttons
  57.     var $arrKnownButtons = array('fblike', 'googleplus', 'twitter');
  58.  
  59.  
  60.     /**
  61.      * Constructor
  62.      */
  63.     function __construct() {
  64.         register_activation_hook( __FILE__, array(&$this, 'plugin_install') );
  65.         register_deactivation_hook( __FILE__, array(&$this, 'plugin_uninstall') );
  66.  
  67.         /**
  68.          * Action hooks
  69.          */
  70.         add_action( 'create_ssb', array(&$this, 'direct_display'), 10 , 1);
  71.        
  72.         /**
  73.          * basic init
  74.          */
  75.         add_action( 'init', array(&$this, 'plugin_init') );
  76.  
  77.         // get settings
  78.         $currentSettings = $this->get_settings();
  79.  
  80.         // social JS + CSS data
  81.         add_action( 'wp_footer', array(&$this, 'include_social_js') );
  82.         if(!isset($currentSettings['override_css'])) {
  83.             add_action( 'wp_head', array(&$this, 'include_css') );
  84.         }
  85.        
  86.         /**
  87.          * Filter hooks
  88.          */
  89.         add_filter( 'the_content', array(&$this, 'insert_buttons') );
  90.         add_filter( 'the_excerpt', array(&$this, 'insert_buttons') );
  91.     }
  92.  
  93.     function plugin_init() {
  94.         load_plugin_textdomain( 'simplesocialbuttons', '', dirname( plugin_basename( __FILE__ ) ).'/lang' );
  95.     }
  96.  
  97.     /**
  98.      * Both avoids time-wasting https calls AND provides better SSL-protection if the current server is accessed using HTTPS
  99.      */
  100.     public function get_current_http( $echo = true ) {
  101.         $return = 'http' . (strtolower(@$_SERVER['HTTPS']) == 'on' ? 's' : '') . '://';
  102.  
  103.         if($echo != false) {
  104.             echo $return;
  105.             return;
  106.         }
  107.  
  108.         return $return;
  109.     }
  110.  
  111.     function include_social_js($force_include = false) {
  112.         $lang = get_bloginfo('language');
  113.         $lang_g = strtolower(substr($lang, 0, 2));
  114.         $lang_fb = str_replace('-', '_', $lang);
  115.  
  116.         /**
  117.          * Disable loading of social network JS if disabled for specific post type
  118.          *
  119.          * NOTE: Conditional tags seem to work only AFTER the page has loaded, thus the code has been added here instead of at the plugin init
  120.          * @author Fabian Wolf
  121.          * @link http://usability-idealist.de/
  122.          * @date Di 20. Dez 17:50:01 CET 2011
  123.          */
  124.         if($this->where_to_insert() != false || $force_include == true) {
  125. ?>
  126.  
  127. <!-- Simple Social Buttons plugin -->
  128. <script type="text/javascript">
  129. //<![CDATA[
  130. // google plus
  131. window.___gcfg = {lang: '<?php echo $lang_g; ?>'};
  132. (function() {
  133.    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
  134.    po.src = 'https://apis.google.com/js/plusone.js';
  135.    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  136. })();
  137. // facebook
  138. (function(d, s, id) {
  139.   var js, fjs = d.getElementsByTagName(s)[0];
  140.   if (d.getElementById(id)) return;
  141.   js = d.createElement(s); js.id = id;
  142.   js.src = "//connect.facebook.net/<?php echo $lang_fb; ?>/all.js#xfbml=1";
  143.   fjs.parentNode.insertBefore(js, fjs);
  144. }(document, 'script', 'facebook-jssdk'));
  145. // twitter
  146. !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
  147. // ]]>
  148. </script>
  149. <!-- /End of Simple Social Buttons -->
  150.  
  151. <?php
  152.         }
  153.     }
  154.  
  155.  
  156.     function include_css() {
  157. ?>
  158.  
  159. <!-- Simple Social Buttons style sheet -->
  160. <style type="text/css">
  161.    div.simplesocialbuttons { height: 20px; margin: 10px auto 10px 0; text-align: center; clear: left; }
  162.    div.simplesocialbutton { float: left; text-align: center;}
  163. </style>
  164. <!-- End of Simple Social Buttons -->
  165.  
  166. <?php
  167.     }
  168.  
  169.     /**
  170.      * Called when installing = activating the plugin
  171.      */
  172.     function plugin_install() {
  173.         $defaultSettings = $this->check_old_settings();
  174.  
  175.         /**
  176.          * @see http://codex.wordpress.org/Function_Reference/add_option
  177.          * @param string $name          Name of the option to be added. Use underscores to separate words, and do not use uppercase - this is going to be placed into the database.
  178.          * @param mixed $value          Value for this option name. Limited to 2^32 bytes of data.
  179.          * @param string $deprecated    Deprecated in WordPress Version 2.3.
  180.          * @param string $autoload      Should this option be automatically loaded by the function wp_load_alloptions() (puts options into object cache on each page load)? Valid values: yes or no. Default: yes
  181.          */
  182.         add_option( $this->pluginPrefix . 'settings', $defaultSettings, '', 'yes' );
  183.         add_option( $this->pluginPrefix . 'version', $this->pluginVersion, '', 'yes' ); // for backward-compatiblity checks
  184.  
  185.     }
  186.  
  187.     /**
  188.      * Backward compatiblity for newer versions
  189.      */
  190.     function check_old_settings() {
  191.         $return = $this->pluginDefaultSettings;
  192.  
  193.         $oldSettings = get_option( $this->pluginPrefix . 'settings', array() );
  194.  
  195.         if( !empty($oldSettings) && is_array($oldSettings) != false) {
  196.             $return = wp_parse_args( $oldSettings, $this->pluginDefaultSettings );
  197.         }
  198.  
  199.         return $return;
  200.     }
  201.  
  202.    /**
  203.     * Plugin unistall and database clean up
  204.     */
  205.     function plugin_uninstall() {
  206.         if( !defined( 'ABSPATH') && !defined('WP_UNINSTALL_PLUGIN') ) {
  207.             exit();
  208.         }
  209.  
  210.         delete_option( $this->pluginPrefix . 'settings' );
  211.         delete_option( $this->pluginPrefix . 'version' );
  212.  
  213.     }
  214.  
  215.  
  216.     /**
  217.      * Get settings from database
  218.      */
  219.     public function get_settings() {
  220.         $return = get_option($this->pluginPrefix . 'settings' );
  221.         if(empty($return) != false) {
  222.             $return = $this->pluginDefaultSettings;
  223.         }
  224.  
  225.         return $return;
  226.     }
  227.  
  228.     /**
  229.      * Update settings
  230.      */
  231.     function update_settings( $newSettings = array() ) {
  232.         $return = false;
  233.  
  234.         // compile settings
  235.         $currentSettings = $this->get_settings();
  236.  
  237.         /**
  238.          * Compile settings array
  239.          * @see http://codex.wordpress.org/Function_Reference/wp_parse_args
  240.          * @param mixed $args
  241.          * @param mixed $defaults
  242.          */
  243.         $updatedSettings = wp_parse_args( $newSettings, $currentSettings );
  244.  
  245.         if($currentSettings != $updatedSettings ) {
  246.             $return = update_option( $this->pluginPrefix . 'settings', $newSettings );
  247.         }
  248.  
  249.         return $return;
  250.     }
  251.  
  252.    /**
  253.     * Returns true on pages where buttons should be shown
  254.     */
  255.     function where_to_insert() {
  256.         $return = false;
  257.        
  258.         // get settings from database
  259.         $settings = $this->get_settings();
  260.  
  261.         extract( $settings, EXTR_PREFIX_ALL, 'ssb' );
  262.  
  263.         // display on single post?
  264.         if (is_single()) {
  265.       if (array_shift(get_post_meta(get_the_ID(), $this->showCustomMetaKey)) == 'true' ||
  266.           (($ssb_beforepost || $ssb_afterpost) && array_shift(get_post_meta(get_the_ID(), $this->hideCustomMetaKey)) != 'true')) {
  267.         $return = true;
  268.       }
  269.         }
  270.  
  271.         // display on single page?
  272.         if (is_page()) {
  273.       if (array_shift(get_post_meta(get_the_ID(), $this->showCustomMetaKey)) == 'true' ||
  274.           (($ssb_beforepage || $ssb_afterpage) && array_shift(get_post_meta(get_the_ID(), $this->hideCustomMetaKey)) != 'true')) {
  275.         $return = true;
  276.       }
  277.         }
  278.  
  279.         // display on frontpage?
  280.         if((is_front_page() || is_home()) && $ssb_showfront) {
  281.             $return = true;
  282.         }
  283.  
  284.         // display on category archive?
  285.         if(is_category() && $ssb_showcategory) {
  286.             $return = true;
  287.         }
  288.  
  289.         // display on date archive?
  290.         if(is_date() && $ssb_showarchive)
  291.         {
  292.             $return = true;
  293.         }
  294.  
  295.         // display on tag archive?
  296.         if(is_tag() && $ssb_showtag) {
  297.             $return = true;
  298.         }
  299.         return $return;
  300.     }
  301.  
  302.     /**
  303.      * Insert the buttons to the content
  304.      */
  305.     function insert_buttons($content) {    
  306.         // Insert or  not?
  307.         if(!$this->where_to_insert() ) {
  308.             return $content;
  309.         }
  310.        
  311.         // get settings from database
  312.         $settings = $this->get_settings();
  313.        
  314.         extract( $settings, EXTR_PREFIX_ALL, 'ssb' );
  315.    
  316.     $via = $settings['twitter_username'];
  317.  
  318.         // creating order
  319.         $order = array();
  320.         foreach ($this->arrKnownButtons as $button_name) {
  321.             $order[$button_name] = $settings[$button_name];
  322.         }
  323.         $ssb_buttonscode = $this->generate_buttons_code($order, $via);
  324.  
  325.         if(is_single()) {
  326.             if($ssb_beforepost) {
  327.                 $content = $ssb_buttonscode.$content;
  328.             }
  329.             if($ssb_afterpost) {
  330.                 $content = $content.$ssb_buttonscode;
  331.             }
  332.         } else if(is_page()) {
  333.             if($ssb_beforepage || array_shift(get_post_meta(get_the_ID(), $this->showCustomMetaKey)) == 'true') {
  334.                 $content = $ssb_buttonscode.$content;
  335.             }
  336.             if($ssb_afterpage) {
  337.                 $content = $content.$ssb_buttonscode;
  338.             }
  339.         } else {
  340.             if($ssb_beforearchive) {
  341.                 $content = $ssb_buttonscode.$content;
  342.             }
  343.             if($ssb_afterarchive) {
  344.                 $content = $content.$ssb_buttonscode;
  345.             }
  346.         }
  347.  
  348.         return $content;
  349.  
  350.     }
  351.    
  352.     function direct_display($order = null, $via = null)
  353.     {
  354.         // Return false if hide SSB for this page/post is disabled
  355.         if (is_single() && array_shift(get_post_meta(get_the_ID(), $this->hideCustomMetaKey)) == 'true') return false;
  356.        
  357.         // Display buttons and scripts
  358.         $buttons_code = $this->generate_buttons_code($order, $via);
  359.         echo $buttons_code;
  360.         $this->include_social_js(true);
  361.     }
  362.    
  363.     /**
  364.      * Generate buttons html code with specified order
  365.      *
  366.      * @param mixed $order - order of social buttons
  367.      */
  368.     function generate_buttons_code($order = null, $via = null)
  369.     {  
  370.         foreach ($this->arrKnownButtons as $button_name) {
  371.             $defaultOrder[$button_name] = $this->pluginDefaultSettings[$button_name];
  372.         }
  373.        
  374.         $order = wp_parse_args($order, $defaultOrder);
  375.  
  376.         // define empty buttons code to use
  377.         $ssb_buttonscode = '';
  378.  
  379.         // get post permalink and title
  380.         $permalink = get_permalink();
  381.         $title = get_the_title();
  382.    
  383.     if (!empty($via)) {
  384.       $via = ' data-via="'.$via.'" ';
  385.     }
  386.    
  387.     $hashtags = get_post_meta(get_the_ID(), 'hashtags', true);
  388.     if (!empty($hashtags)) {
  389.       $hashtags = ' data-hashtags="'.$hashtags.'" ';
  390.     }
  391.  
  392.         //Sorting the buttons
  393.         foreach($this->arrKnownButtons as $button_name) {
  394.             if(!empty($order[$button_name]) && (int)$order[$button_name] != 0) {
  395.                 $arrButtons[$button_name] = $order[$button_name];
  396.             }
  397.         }
  398.         @asort($arrButtons);
  399.  
  400.         $arrButtonsCode = array();
  401.         foreach($arrButtons as $button_name => $button_sort) {
  402.             switch($button_name) {
  403.                 case 'googleplus':
  404.                     $arrButtonsCode[] = '<div class="simplesocialbutton ssb-button-googleplus"><!-- Google Plus One--><div class="g-plusone" data-size="medium" data-href="'.$permalink.'"></div></div>';
  405.                     break;
  406.                 case 'fblike':
  407.                     $arrButtonsCode[] = '<div class="simplesocialbutton ssb-button-fblike"><!-- Facebook like--><div class="fb-like" data-href="'.$permalink.'" data-send="false" data-layout="button_count" data-width="100" data-show-faces="false"></div></div>';
  408.                     break;
  409.                 case 'twitter':
  410.                     $arrButtonsCode[] = '<div class="simplesocialbutton ssb-buttom-twitter"><!-- Twitter--><a href="https://twitter.com/share" class="twitter-share-button" data-text="'.$title.'" data-url="'.$permalink.'" '.$via.$hashtags.'rel="nofollow"></a></div>';
  411.                     break;
  412.             }
  413.         }
  414.  
  415.    
  416.         if(count($arrButtonsCode) > 0) {
  417.             $ssb_buttonscode = '<div class=simplesocialbuttons>';
  418.             $ssb_buttonscode .= implode("\n", $arrButtonsCode);
  419.             $ssb_buttonscode .= '</div><div style=clear:both></div>';
  420.         }
  421.        
  422.         return $ssb_buttonscode;
  423.     }
  424. } // end class
  425.  
  426.  
  427. /**
  428.  * Admin class
  429.  *
  430.  * Gets only initiated if this plugin is called inside the admin section ;)
  431.  */
  432. class SimpleSocialButtonsPR_Admin extends SimpleSocialButtonsPR {
  433.  
  434.     function __construct() {
  435.         parent::__construct();
  436.  
  437.         add_action('admin_menu', array(&$this, 'admin_actions') );
  438.         add_action('add_meta_boxes', array(&$this, 'ssb_meta_box'));
  439.         add_action('save_post', array(&$this, 'ssb_save_meta'), 10, 2);
  440.        
  441.         add_filter('plugin_action_links', array(&$this, 'plugin_action_links'), 10, 2 );
  442.     }
  443.  
  444.     public function admin_actions() {
  445.         if (current_user_can('administrator'))
  446.             add_options_page('Simple Social Buttons ', 'Simple Social Buttons ', 1, 'simple-social-buttons', array(&$this, 'admin_page') );
  447.     }
  448.  
  449.     public function admin_page() {
  450.         global $wpdb;
  451.  
  452.         include dirname( __FILE__  ).'/ssb-admin.php';
  453.     }
  454.  
  455.  
  456.  
  457.     public function plugin_action_links($links, $file) {
  458.         static $this_plugin;
  459.  
  460.         if (!$this_plugin) {
  461.             $this_plugin = plugin_basename(__FILE__);
  462.         }
  463.  
  464.         if ($file == $this_plugin) {
  465.             $settings_link = '<a href="' . get_bloginfo('wpurl') . '/wp-admin/options-general.php?page=simple-social-buttons">'.__('Settings', 'simplesocialbuttons').'</a>';
  466.             array_unshift($links, $settings_link);
  467.         }
  468.  
  469.         return $links;
  470.     }
  471.    
  472.     /**
  473.      * Register meta box to hide/show SSB plugin on single post or page
  474.      */
  475.     public function ssb_meta_box()
  476.     {      
  477.         $postId = $_GET['post'];
  478.         $postType = get_post_type($postId);
  479.        
  480.         if ($postType != 'page' && $postType != 'post') return false;
  481.        
  482.         $currentSsbHide = get_post_custom_values($this->hideCustomMetaKey, $postId);
  483.     $currentSsbShow = get_post_custom_values($this->showCustomMetaKey, $postId);
  484.         $currentSettings = $this->get_settings();
  485.        
  486.         if ($currentSsbHide[0] == 'true') {
  487.             $hideChecked = true;
  488.         } else {
  489.             $hideChecked = false;          
  490.         }
  491.    
  492.         if ($currentSsbShow[0] == 'true') {
  493.             $showChecked = true;
  494.         } else {
  495.             $showChecked = false;          
  496.         }    
  497.        
  498.         // Rendering meta box
  499.         if (!function_exists('add_meta_box')) include('includes/template.php');
  500.         add_meta_box('ssb_meta_box', __('SSB Settings', 'simplesocialbuttons'), array(&$this, 'render_ssb_meta_box'), $postType, 'side', 'default', array('type' => $postType, 'hidechecked' => $hideChecked, 'showchecked' => $showChecked));
  501.     }
  502.    
  503.     /**
  504.      * Showing custom meta field
  505.      */
  506.     public function render_ssb_meta_box($post, $metabox)
  507.     {
  508.         wp_nonce_field( plugin_basename( __FILE__ ), 'ssb_noncename' );
  509. ?>
  510.  
  511. <label for="<?php echo $this->hideCustomMetaKey;?>"><input type="checkbox" id="<?php echo $this->hideCustomMetaKey;?>" name="<?php echo $this->hideCustomMetaKey;?>" value="true" <?php if ($metabox['args']['hidechecked']):?>checked="checked"<?php endif;?>/>&nbsp;<?php echo __('Hide Simple Social Buttons', 'simplesocialbuttons');?></label>
  512. <br />
  513. <label for="<?php echo $this->showCustomMetaKey;?>"><input type="checkbox" id="<?php echo $this->showCustomMetaKey;?>" name="<?php echo $this->showCustomMetaKey;?>" value="true" <?php if ($metabox['args']['showchecked']):?>checked="checked"<?php endif;?>/>&nbsp;<?php echo __('Force Show Before Content', 'simplesocialbuttons');?></label>
  514.  
  515. <?php
  516.     }
  517.    
  518.        
  519.     /**
  520.      * Saving custom meta value
  521.      */
  522.     public function ssb_save_meta($post_id, $post)
  523.     {      
  524.         $postId = (int)$post_id;
  525.        
  526.         // Verify if this is an auto save routine.
  527.         if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
  528.             return;
  529.    
  530.         // Verify this came from the our screen and with proper authorization
  531.         if ( !wp_verify_nonce( $_POST['ssb_noncename'], plugin_basename( __FILE__ ) ) )
  532.             return;
  533.    
  534.         // Check permissions
  535.         if ( 'page' == $_POST['post_type'] ) {
  536.             if ( !current_user_can( 'edit_page', $post_id ) )
  537.                 return;
  538.         } else {
  539.             if ( !current_user_can( 'edit_post', $post_id ) )
  540.             return;
  541.         }
  542.        
  543.         // Saving data
  544.         $hideNewValue = (isset($_POST[$this->hideCustomMetaKey])) ? $_POST[$this->hideCustomMetaKey] : 'false';
  545.         update_post_meta($postId, $this->hideCustomMetaKey, $hideNewValue);
  546.    
  547.         $showNewValue = (isset($_POST[$this->showCustomMetaKey])) ? $_POST[$this->showCustomMetaKey] : 'false';
  548.     update_post_meta($postId, $this->showCustomMetaKey, $showNewValue);    
  549.    
  550.     }
  551.  
  552.  
  553. } // end SimpleSocialButtonsPR_Admin
  554.  
  555. if(is_admin() ) {
  556.     $_ssb_pr = new SimpleSocialButtonsPR_Admin();
  557. } else {
  558.     $_ssb_pr = new SimpleSocialButtonsPR();
  559. }
  560.  
  561. /**
  562.  * Function to insert Simple Social Buttons directly in template.
  563.  *
  564.  * @param mixed $order - order of the buttons in array or string (parsed by wp_parse_args())
  565.  *
  566.  * @example 1 - use in template with default order
  567.  * get_ssb();
  568.  *
  569.  * @example 2 - use in template with specified order
  570.  * get_ssb('googleplus=3&fblike=2&twitter=1');
  571.  *
  572.  * @example 3 - hiding button by setting order to 0. By using code below googleplus button won't be displayed
  573.  * get_ssb('googleplus=0&fblike=1&twitter=2');
  574.  *
  575.  *
  576.  */
  577. function get_ssb($order = null)
  578. {
  579.     do_action('create_ssb', $order);
  580. }
  581.  
  582. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement