Advertisement
almergabor

Wordpress popular posts

Nov 24th, 2011
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 64.14 KB | None | 0 0
  1. <?php
  2. //I marked the new code begining with //Include categories feature
  3. //And ended it with the same. For easy handling I used it inside the html code also, despite it is not correct
  4. /*
  5. Plugin Name: Wordpress Popular Posts
  6. Plugin URI: http://wordpress.org/extend/plugins/wordpress-popular-posts
  7. Description: Showcases your most popular posts to your visitors on your blog's sidebar. Use Wordpress Popular Posts as a widget or place it anywhere on your theme using  <strong>&lt;?php wpp_get_mostpopular(); ?&gt;</strong>
  8. Version: 2.1.6
  9. Author: H&eacute;ctor Cabrera
  10. Author URI: http://wordpress.org/extend/plugins/wordpress-popular-posts
  11. License: GPL2
  12. */
  13.  
  14. if (basename($_SERVER['SCRIPT_NAME']) == basename(__FILE__)) exit('Please do not load this page directly');
  15.  
  16. /**
  17.  * Load Wordpress Popular Posts to widgets_init.
  18.  * @since 2.0
  19.  */
  20. add_action('widgets_init', 'load_wpp');
  21.  
  22. function load_wpp() {
  23.     register_widget('WordpressPopularPosts');
  24. }
  25.  
  26. /**
  27.  * Wordpress Popular Posts class.
  28.  */
  29.  
  30. if ( !class_exists('WordpressPopularPosts') ) {
  31.     class WordpressPopularPosts extends WP_Widget {
  32.         // plugin global variables
  33.         var $version = "2.1.6";
  34.         var $qTrans = false;
  35.         var $postRating = false;
  36.         var $thumb = false;    
  37.         var $pluginDir = "";
  38.         var $charset = "UTF-8";
  39.         var $magicquotes = false;
  40.        
  41.         // constructor
  42.         function WordpressPopularPosts() {
  43.             global $wp_version;
  44.                
  45.             // widget settings
  46.             $widget_ops = array( 'classname' => 'popular-posts', 'description' => 'The most Popular Posts on your blog.' );
  47.    
  48.             // widget control settings
  49.             $control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'wpp' );
  50.    
  51.             // create the widget
  52.             $this->WP_Widget( 'wpp', 'Wordpress Popular Posts', $widget_ops, $control_ops );
  53.            
  54.             // set plugin path
  55.             if (empty($this->pluginDir)) $this->pluginDir = WP_PLUGIN_URL . '/wordpress-popular-posts';
  56.            
  57.             // set charset
  58.             $this->charset = get_bloginfo('charset');
  59.            
  60.             // detect PHP magic quotes
  61.             $this->magicquotes = get_magic_quotes_gpc();
  62.            
  63.             // print stylesheet
  64.             add_action('wp_head', array(&$this, 'wpp_print_stylesheet'));
  65.            
  66.             // add ajax update to wp_ajax_ hook
  67.             add_action('wp_ajax_nopriv_wpp_update', array(&$this, 'wpp_ajax_update'));
  68.             add_action('wp_head', array(&$this, 'wpp_print_ajax'));
  69.            
  70.             // add ajax table truncation to wp_ajax_ hook
  71.             add_action('wp_ajax_wpp_clear_cache', array(&$this, 'wpp_clear_data'));
  72.             add_action('wp_ajax_wpp_clear_all', array(&$this, 'wpp_clear_data'));
  73.            
  74.             // activate textdomain for translations
  75.             add_action('init', array(&$this, 'wpp_textdomain'));
  76.            
  77.             // activate maintenance page
  78.             add_action('admin_menu', array(&$this, 'add_wpp_maintenance_page'));
  79.            
  80.             // cache maintenance schedule
  81.             register_deactivation_hook(__FILE__, array(&$this, 'wpp_deactivation'));           
  82.             add_action('wpp_cache_event', array(&$this, 'wpp_cache_maintenance'));
  83.             if (!wp_next_scheduled('wpp_cache_event')) {
  84.                 $tomorrow = time() + 86400;
  85.                 $midnight  = mktime(0, 0, 0,
  86.                     date("m", $tomorrow),
  87.                     date("d", $tomorrow),
  88.                     date("Y", $tomorrow));
  89.                 wp_schedule_event( $midnight, 'daily', 'wpp_cache_event' );
  90.             }
  91.            
  92.             // Wordpress version check
  93.             if (version_compare($wp_version, '2.8.0', '<')) add_action('admin_notices', array(&$this, 'wpp_update_warning'));
  94.            
  95.             // qTrans plugin support
  96.             if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) $this->qTrans = true;
  97.            
  98.             // WP-Post Ratings plugin support
  99.             if (function_exists('the_ratings_results')) $this->postRating = true;
  100.            
  101.             // Can we create thumbnails?
  102.             if (extension_loaded('gd') && function_exists('gd_info') && version_compare(phpversion(), '4.3.0', '>=') && function_exists('add_theme_support')) $this->thumb = true;
  103.            
  104.             // shortcode
  105.             if( function_exists('add_shortcode') ){
  106.                 add_shortcode('wpp', array(&$this, 'wpp_shortcode'));
  107.                 add_shortcode('WPP', array(&$this, 'wpp_shortcode'));
  108.             }
  109.            
  110.             // set version
  111.             $wpp_ver = get_option('wpp_ver');
  112.             if (!$wpp_ver) {
  113.                 add_option('wpp_ver', $this->version);
  114.             } else if (version_compare($wpp_ver, $this->version, '<')) {
  115.                 update_option('wpp_ver', $this->version);
  116.             }
  117.            
  118.             // add stats page
  119.             add_action('admin_menu', array(&$this, 'wpp_stats'));
  120.         }
  121.  
  122.         // builds Wordpress Popular Posts' widgets
  123.         function widget($args, $instance) {
  124.             extract($args);
  125.             echo "<!-- Wordpress Popular Posts Plugin v". $this->version ." [W] [".$instance['range']."]". (($instance['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
  126.             echo $before_widget . "\n";
  127.            
  128.             // has user set a title?
  129.             if ($instance['title'] != '') {
  130.                 if ($instance['markup']['custom_html'] && $instance['markup']['title-start'] != "" && $instance['markup']['title-end'] != "" ) {
  131.                     echo htmlspecialchars_decode($instance['markup']['title-start'], ENT_QUOTES) . htmlspecialchars_decode($instance['title'], ENT_QUOTES) . htmlspecialchars_decode($instance['markup']['title-end'], ENT_QUOTES);
  132.                 } else {
  133.                     echo $before_title . htmlspecialchars_decode($instance['title'], ENT_QUOTES) . $after_title;
  134.                 }
  135.             }
  136.            
  137.             echo $this->get_popular_posts($instance, false);           
  138.             echo $after_widget . "\n";
  139.             echo "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
  140.         }
  141.  
  142.         // updates each widget instance when user clicks the "save" button
  143.         function update($new_instance, $old_instance) {
  144.            
  145.             $instance = $old_instance;
  146.            
  147.             //$instance['title'] = htmlspecialchars( stripslashes(strip_tags( $new_instance['title'] )), ENT_QUOTES, 'UTF-8', FALSE );
  148.             $instance['title'] = ($this->magicquotes) ? htmlspecialchars( stripslashes(strip_tags( $new_instance['title'] )), ENT_QUOTES ) : htmlspecialchars( strip_tags( $new_instance['title'] ), ENT_QUOTES );
  149.             $instance['limit'] = is_numeric($new_instance['limit']) ? $new_instance['limit'] : 10;
  150.             $instance['range'] = $new_instance['range'];
  151.             $instance['order_by'] = $new_instance['order_by'];
  152.             $instance['pages'] = $new_instance['pages'];
  153.             $instance['shorten_title']['active'] = $new_instance['shorten_title-active'];
  154.             $instance['shorten_title']['length'] = is_numeric($new_instance['shorten_title-length']) ? $new_instance['shorten_title-length'] : 25;
  155.             $instance['post-excerpt']['active'] = $new_instance['post-excerpt-active'];
  156.             $instance['post-excerpt']['length'] = is_numeric($new_instance['post-excerpt-length']) ? $new_instance['post-excerpt-length'] : 55;
  157.             $instance['post-excerpt']['keep_format'] = $new_instance['post-excerpt-format'];
  158.             $instance['exclude-cats']['active'] = $new_instance['exclude-cats'];
  159.             $instance['exclude-cats']['cats'] = empty($new_instance['excluded']) ? '' : (ctype_digit(str_replace(",", "", $new_instance['excluded']))) ? $new_instance['excluded'] : '';
  160.             //Include categories feature
  161.             $instance['include-cats']['active'] = $new_instance['include-cats'];
  162.             $instance['include-cats']['cats'] = empty($new_instance['included']) ? '' : (ctype_digit(str_replace(",", "", $new_instance['included']))) ? $new_instance['included'] : '';
  163.             //Include categories feature
  164.             $instance['thumbnail']['thumb_selection'] = "usergenerated";
  165.            
  166.             if ($this->thumb) { // can create thumbnails
  167.                 $instance['thumbnail']['active'] = $new_instance['thumbnail-active'];              
  168.                 $instance['thumbnail']['width'] = is_numeric($new_instance['thumbnail-width']) ? $new_instance['thumbnail-width'] : 15;
  169.                 $instance['thumbnail']['height'] = is_numeric($new_instance['thumbnail-height']) ? $new_instance['thumbnail-height'] : 15;
  170.             } else { // cannot create thumbnails
  171.                 $instance['thumbnail']['active'] = false;
  172.                 $instance['thumbnail']['width'] = 15;
  173.                 $instance['thumbnail']['height'] = 15;
  174.             }
  175.            
  176.             $instance['rating'] = $new_instance['rating'];
  177.             $instance['stats_tag']['comment_count'] = $new_instance['comment_count'];
  178.             $instance['stats_tag']['views'] = $new_instance['views'];
  179.             $instance['stats_tag']['author'] = $new_instance['author'];
  180.             $instance['stats_tag']['date']['active'] = $new_instance['date'];
  181.             $instance['stats_tag']['date']['format'] = empty($new_instance['date_format']) ? 'F j, Y' : $new_instance['date_format'];
  182.             $instance['markup']['custom_html'] = $new_instance['custom_html'];
  183.             $instance['markup']['wpp-start'] = empty($new_instance['wpp-start']) ? '&lt;ul&gt;' : htmlspecialchars( $new_instance['wpp-start'], ENT_QUOTES );
  184.             $instance['markup']['wpp-end'] = empty($new_instance['wpp-end']) ? '&lt;/ul&gt;' : htmlspecialchars( $new_instance['wpp-end'], ENT_QUOTES );
  185.             $instance['markup']['post-start'] = empty ($new_instance['post-start']) ? '&lt;li&gt;' : htmlspecialchars( $new_instance['post-start'], ENT_QUOTES );
  186.             $instance['markup']['post-end'] = empty ($new_instance['post-end']) ? '&lt;/li&gt;' : htmlspecialchars( $new_instance['post-end'], ENT_QUOTES );
  187.             $instance['markup']['title-start'] = empty($new_instance['title-start']) ? '' : htmlspecialchars( $new_instance['title-start'], ENT_QUOTES );
  188.             $instance['markup']['title-end'] = empty($new_instance['title-end']) ? '' : htmlspecialchars( $new_instance['title-end'], ENT_QUOTES );
  189.             $instance['markup']['pattern']['active'] = $new_instance['pattern_active'];
  190.             $instance['markup']['pattern']['form'] = empty($new_instance['pattern_form']) ? '{image} {title}: {summary} {stats}' : strip_tags( $new_instance['pattern_form'] );
  191.    
  192.             return $instance;
  193.         }
  194.  
  195.         // widget's form
  196.         function form($instance) {
  197.             // set default values          
  198.             $defaults = array(
  199.                 'title' => __('Popular Posts', 'wordpress-popular-posts'),
  200.                 'limit' => 10,
  201.                 'range' => 'daily',
  202.                 'order_by' => 'comments',
  203.                 'pages' => true,
  204.                 'shorten_title' => array(
  205.                     'active' => false,
  206.                     'length' => 25,
  207.                     'keep_format' => false
  208.                 ),
  209.                 'post-excerpt' => array(
  210.                     'active' => false,
  211.                     'length' => 55
  212.                 ),
  213.                 'exclude-cats' => array(
  214.                     'active' => false,
  215.                     'cats' => ''
  216.                 ),
  217. //Include categories feature
  218.                 'include-cats' => array(
  219.                     'active' => false,
  220.                     'cats' => ''
  221.                 ),
  222. //Include categories feature
  223.                 'thumbnail' => array(
  224.                     'active' => false,
  225.                     'width' => 15,
  226.                     'height' => 15
  227.                 ),
  228.                 'rating' => false,
  229.                 'stats_tag' => array(
  230.                     'comment_count' => true,
  231.                     'views' => false,
  232.                     'author' => false,
  233.                     'date' => array(
  234.                         'active' => false,
  235.                         'format' => 'F j, Y'
  236.                     )
  237.                 ),
  238.                 'markup' => array(
  239.                     'custom_html' => false,
  240.                     'wpp-start' => '&lt;ul&gt;',
  241.                     'wpp-end' => '&lt;/ul&gt;',
  242.                     'post-start' => '&lt;li&gt;',
  243.                     'post-end' => '&lt;/li&gt;',
  244.                     'title-start' => '&lt;h2&gt;',
  245.                     'title-end' => '&lt;/h2&gt;',
  246.                     'pattern' => array(
  247.                         'active' => false,
  248.                         'form' => '{image} {title}: {summary} {stats}'
  249.                     )
  250.                 )
  251.             );
  252.            
  253.             // update instance's default options
  254.             $instance = wp_parse_args( (array) $instance, $defaults );
  255.            
  256.             // form
  257.             ?>
  258.                         <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'wordpress-popular-posts'); ?></label>
  259.             <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" class="widefat" /></p>
  260.             <p><label for="<?php echo $this->get_field_id( 'limit' ); ?>"><?php _e('Show up to:', 'wordpress-popular-posts'); ?></label><br />
  261.             <input id="<?php echo $this->get_field_id( 'limit' ); ?>" name="<?php echo $this->get_field_name( 'limit' ); ?>" value="<?php echo $instance['limit']; ?>"  class="widefat" style="width:50px!important" /> <?php _e('posts', 'wordpress-popular-posts'); ?></p>
  262.             <p><label for="<?php echo $this->get_field_id( 'range' ); ?>"><?php _e('Time Range:', 'wordpress-popular-posts'); ?></label>
  263.             <select id="<?php echo $this->get_field_id( 'range' ); ?>" name="<?php echo $this->get_field_name( 'range' ); ?>" class="widefat">
  264.                 <option value="daily" <?php if ( 'daily' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Today', 'wordpress-popular-posts'); ?></option>
  265.                 <option value="weekly" <?php if ( 'weekly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 7 days', 'wordpress-popular-posts'); ?></option>
  266.                 <option value="monthly" <?php if ( 'monthly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 30 days', 'wordpress-popular-posts'); ?></option>
  267.                 <option value="all" <?php if ( 'all' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('All-time', 'wordpress-popular-posts'); ?></option>
  268.             </select>
  269.             </p>
  270.             <p><label for="<?php echo $this->get_field_id( 'order_by' ); ?>"><?php _e('Sort posts by:', 'wordpress-popular-posts'); ?></label>
  271.             <select id="<?php echo $this->get_field_id( 'order_by' ); ?>" name="<?php echo $this->get_field_name( 'order_by' ); ?>" class="widefat">
  272.                 <option value="comments" <?php if ( 'comments' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Comments', 'wordpress-popular-posts'); ?></option>
  273.                 <option value="views" <?php if ( 'views' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Total views', 'wordpress-popular-posts'); ?></option>
  274.                 <option value="avg" <?php if ( 'avg' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Avg. daily views', 'wordpress-popular-posts'); ?></option>
  275.             </select>
  276.             </p>
  277.             <input type="checkbox" class="checkbox" <?php echo ($instance['pages']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'pages' ); ?>" name="<?php echo $this->get_field_name( 'pages' ); ?>" /> <label for="<?php echo $this->get_field_id( 'pages' ); ?>"><?php _e('Include pages', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  278.             <?php if ($this->postRating) : ?>
  279.             <input type="checkbox" class="checkbox" <?php echo ($instance['rating']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'rating' ); ?>" name="<?php echo $this->get_field_name( 'rating' ); ?>" /> <label for="<?php echo $this->get_field_id( 'rating' ); ?>"><?php _e('Display post rating', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  280.             <?php endif; ?>
  281.             <input type="checkbox" class="checkbox" <?php echo ($instance['shorten_title']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'shorten_title-active' ); ?>" name="<?php echo $this->get_field_name( 'shorten_title-active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'shorten_title-active' ); ?>"><?php _e('Shorten title output', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  282.             <?php if ($instance['shorten_title']['active']) : ?>
  283.             <label for="<?php echo $this->get_field_id( 'shorten_title-length' ); ?>"><?php _e('Shorten title to', 'wordpress-popular-posts'); ?> <input id="<?php echo $this->get_field_id( 'shorten_title-length' ); ?>" name="<?php echo $this->get_field_name( 'shorten_title-length' ); ?>" value="<?php echo $instance['shorten_title']['length']; ?>" class="widefat" style="width:50px!important" /> <?php _e('characters', 'wordpress-popular-posts'); ?></label><br /><br />
  284.             <?php endif; ?>
  285.             <input type="checkbox" class="checkbox" <?php echo ($instance['post-excerpt']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'post-excerpt-active' ); ?>" name="<?php echo $this->get_field_name( 'post-excerpt-active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'post-excerpt-active' ); ?>"><?php _e('Display post excerpt', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  286.             <?php if ($instance['post-excerpt']['active']) : ?>
  287.             <fieldset class="widefat">
  288.                 <legend><?php _e('Excerpt Properties', 'wordpress-popular-posts'); ?></legend>
  289.                 &nbsp;&nbsp;<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'post-excerpt-format' ); ?>" name="<?php echo $this->get_field_name( 'post-excerpt-format' ); ?>" <?php echo ($instance['post-excerpt']['keep_format']) ? 'checked="checked"' : ''; ?> /> <label for="<?php echo $this->get_field_id( 'post-excerpt-format' ); ?>"><?php _e('Keep text format and links', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  290.                 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'post-excerpt-length' ); ?>"><?php _e('Excerpt length:', 'wordpress-popular-posts'); ?> <input id="<?php echo $this->get_field_id( 'post-excerpt-length' ); ?>" name="<?php echo $this->get_field_name( 'post-excerpt-length' ); ?>" value="<?php echo $instance['post-excerpt']['length']; ?>" class="widefat" style="width:30px!important" /> <?php _e('characters', 'wordpress-popular-posts'); ?></label>
  291.             </fieldset>
  292.             <br />
  293.             <?php endif; ?>
  294.             <input type="checkbox" class="checkbox" <?php echo ($instance['exclude-cats']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'exclude-cats' ); ?>" name="<?php echo $this->get_field_name( 'exclude-cats' ); ?>" /> <label for="<?php echo $this->get_field_id( 'exclude-cats' ); ?>"><?php _e('Exclude categories', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  295.             <?php if ($instance['exclude-cats']['active']) : ?>
  296.             <fieldset class="widefat">
  297.                 <legend><?php _e('Categories to exclude', 'wordpress-popular-posts'); ?></legend>
  298.                 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'excluded' ); ?>"><?php _e('ID(s) (comma separated, no spaces):', 'wordpress-popular-posts'); ?></label><br />&nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'excluded' ); ?>" name="<?php echo $this->get_field_name( 'excluded' ); ?>" value="<?php echo $instance['exclude-cats']['cats']; ?>" class="widefat" style="width:150px" /><br /><br />
  299.             </fieldset>            
  300.             <?php endif; ?>
  301. //Include categories feature
  302.             <input type="checkbox" class="checkbox" <?php echo ($instance['include-cats']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'include-cats' ); ?>" name="<?php echo $this->get_field_name( 'include-cats' ); ?>" /> <label for="<?php echo $this->get_field_id( 'include-cats' ); ?>"><?php _e('Include categories', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  303.             <?php if ($instance['include-cats']['active']) : ?>
  304.             <fieldset class="widefat">
  305.                 <legend><?php _e('Categories to include', 'wordpress-popular-posts'); ?></legend>
  306.                 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'included' ); ?>"><?php _e('ID(s) (comma separated, no spaces):', 'wordpress-popular-posts'); ?></label><br />&nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'included' ); ?>" name="<?php echo $this->get_field_name( 'included' ); ?>" value="<?php echo $instance['include-cats']['cats']; ?>" class="widefat" style="width:150px" /><br /><br />
  307.             </fieldset>            
  308.             <?php endif; ?>
  309. //Include categories feature
  310.             <br />
  311.            
  312.             <fieldset style="width:214px; padding:5px;"  class="widefat">
  313.                 <legend><?php _e('Thumbnail settings', 'wordpress-popular-posts'); ?></legend>
  314.                 <input type="checkbox" class="checkbox" <?php echo ($instance['thumbnail']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'thumbnail-active' ); ?>" name="<?php echo $this->get_field_name( 'thumbnail-active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'thumbnail-active' ); ?>"><?php _e('Display post thumbnail', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  315.                 <?php if($instance['thumbnail']['active']) : ?>
  316.                 <label for="<?php echo $this->get_field_id( 'thumbnail-width' ); ?>"><?php _e('Width:', 'wordpress-popular-posts'); ?></label>
  317.                 <input id="<?php echo $this->get_field_id( 'thumbnail-width' ); ?>" name="<?php echo $this->get_field_name( 'thumbnail-width' ); ?>" value="<?php echo $instance['thumbnail']['width']; ?>"  class="widefat" style="width:30px!important" <?php echo ($this->thumb) ? '' : 'disabled="disabled"' ?> /> <?php _e('px', 'wordpress-popular-posts'); ?> <br />
  318.                 <label for="<?php echo $this->get_field_id( 'thumbnail-height' ); ?>"><?php _e('Height:', 'wordpress-popular-posts'); ?></label>
  319.                 <input id="<?php echo $this->get_field_id( 'thumbnail-height' ); ?>" name="<?php echo $this->get_field_name( 'thumbnail-height' ); ?>" value="<?php echo $instance['thumbnail']['height']; ?>"  class="widefat" style="width:30px!important" <?php echo ($this->thumb) ? '' : 'disabled="disabled"' ?> /> <?php _e('px', 'wordpress-popular-posts'); ?><br />              
  320.                 <?php endif; ?>
  321.             </fieldset>
  322.            
  323.             <br />
  324.             <fieldset style="width:214px; padding:5px;"  class="widefat">
  325.                 <legend><?php _e('Stats Tag settings', 'wordpress-popular-posts'); ?></legend>
  326.                 <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['comment_count']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'comment_count' ); ?>" name="<?php echo $this->get_field_name( 'comment_count' ); ?>" /> <label for="<?php echo $this->get_field_id( 'comment_count' ); ?>"><?php _e('Display comment count', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />                
  327.                 <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['views']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'views' ); ?>" name="<?php echo $this->get_field_name( 'views' ); ?>" /> <label for="<?php echo $this->get_field_id( 'views' ); ?>"><?php _e('Display views', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />            
  328.                 <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['author']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'author' ); ?>" name="<?php echo $this->get_field_name( 'author' ); ?>" /> <label for="<?php echo $this->get_field_id( 'author' ); ?>"><?php _e('Display author', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />            
  329.                 <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['date']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'date' ); ?>" name="<?php echo $this->get_field_name( 'date' ); ?>" /> <label for="<?php echo $this->get_field_id( 'date' ); ?>"><?php _e('Display date', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small>
  330.                 <?php if ($instance['stats_tag']['date']['active']) : ?>                   
  331.                     <fieldset class="widefat">
  332.                         <legend><?php _e('Date Format', 'wordpress-popular-posts'); ?></legend>
  333.                         <label title='F j, Y'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='F j, Y' <?php echo ($instance['stats_tag']['date']['format'] == 'F j, Y') ? 'checked="checked"' : ''; ?> /><?php echo date_i18n('F j, Y', time()); ?></label><br />
  334.                         <label title='Y/m/d'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='Y/m/d' <?php echo ($instance['stats_tag']['date']['format'] == 'Y/m/d') ? 'checked="checked"' : ''; ?> /><?php echo date_i18n('Y/m/d', time()); ?></label><br />
  335.                         <label title='m/d/Y'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='m/d/Y' <?php echo ($instance['stats_tag']['date']['format'] == 'm/d/Y') ? 'checked="checked"' : ''; ?> /><?php echo date_i18n('m/d/Y', time()); ?></label><br />
  336.                         <label title='d/m/Y'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='d/m/Y' <?php echo ($instance['stats_tag']['date']['format'] == 'd/m/Y') ? 'checked="checked"' : ''; ?> /><?php echo date_i18n('d/m/Y', time()); ?></label><br />
  337.                     </fieldset>
  338.                 <?php endif; ?>
  339.             </fieldset>
  340.             <br />
  341.            
  342.             <fieldset style="width:214px; padding:5px;"  class="widefat">
  343.                 <legend><?php _e('HTML Markup settings', 'wordpress-popular-posts'); ?></legend>
  344.                 <input type="checkbox" class="checkbox" <?php echo ($instance['markup']['custom_html']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'custom_html' ); ?>" name="<?php echo $this->get_field_name( 'custom_html' ); ?>" /> <label for="<?php echo $this->get_field_id( 'custom_html' ); ?>"><?php _e('Use custom HTML Markup', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  345.                 <?php if ($instance['markup']['custom_html']) : ?>
  346.                 <br />
  347.                 <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'title-start' ); ?>"><?php _e('Before / after title:', 'wordpress-popular-posts'); ?></label> <br />
  348.                 <input type="text" id="<?php echo $this->get_field_id( 'title-start' ); ?>" name="<?php echo $this->get_field_name( 'title-start' ); ?>" value="<?php echo $instance['markup']['title-start']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /> <input type="text" id="<?php echo $this->get_field_id( 'title-end' ); ?>" name="<?php echo $this->get_field_name( 'title-end' ); ?>" value="<?php echo $instance['markup']['title-end']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /></p>
  349.                 <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'wpp_start' ); ?>"><?php _e('Before / after Popular Posts:', 'wordpress-popular-posts'); ?></label> <br />
  350.                 <input type="text" id="<?php echo $this->get_field_id( 'wpp-start' ); ?>" name="<?php echo $this->get_field_name( 'wpp-start' ); ?>" value="<?php echo $instance['markup']['wpp-start']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /> <input type="text" id="<?php echo $this->get_field_id( 'wpp-end' ); ?>" name="<?php echo $this->get_field_name( 'wpp-end' ); ?>" value="<?php echo $instance['markup']['wpp-end']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /></p>
  351.                 <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'post-start' ); ?>"><?php _e('Before / after each post:', 'wordpress-popular-posts'); ?></label> <br />
  352.                 <input type="text" id="<?php echo $this->get_field_id( 'post-start' ); ?>" name="<?php echo $this->get_field_name( 'post-start' ); ?>" value="<?php echo $instance['markup']['post-start']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /> <input type="text" id="<?php echo $this->get_field_id( 'post-end' ); ?>" name="<?php echo $this->get_field_name( 'post-end' ); ?>" value="<?php echo $instance['markup']['post-end']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /></p>
  353.                 <hr />
  354.                 <?php endif; ?>
  355.                 <input type="checkbox" class="checkbox" <?php echo ($instance['markup']['pattern']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'pattern_active' ); ?>" name="<?php echo $this->get_field_name( 'pattern_active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'pattern_active' ); ?>"><?php _e('Use content formatting tags', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
  356.                 <?php if ($instance['markup']['pattern']['active']) : ?>
  357.                 <br />
  358.                 <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'pattern_form' ); ?>"><?php _e('Content format:', 'wordpress-popular-posts'); ?></label>
  359.                 <input type="text" id="<?php echo $this->get_field_id( 'pattern_form' ); ?>" name="<?php echo $this->get_field_name( 'pattern_form' ); ?>" value="<?php echo $instance['markup']['pattern']['form']; ?>" style="width:204px" <?php echo ($instance['markup']['pattern']['active']) ? '' : 'disabled="disabled"' ?> /></p>
  360.                 <?php endif; ?>
  361.             </fieldset>
  362.             <?php
  363.         }
  364.        
  365.         // RRR Added to get local time as per WP settings      
  366.         function curdate() {
  367.             return "'".gmdate( 'Y-m-d', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ))."'";
  368.         }
  369.        
  370.         function now() {       
  371.             return "'".current_time('mysql')."'";
  372.         }
  373.        
  374.         // updates popular posts data table
  375.         function wpp_ajax_update() {       
  376.             $nonce = $_POST['token'];
  377.            
  378.             // is this a valid request?
  379.             if (! wp_verify_nonce($nonce, 'wpp-token') ) die("Oops!");
  380.            
  381.             if (is_numeric($_POST['id']) && (intval($_POST['id']) == floatval($_POST['id'])) && ($_POST['id'] != '')) {
  382.                 $id = $_POST['id'];
  383.             } else {
  384.                 die("Invalid ID");
  385.             }
  386.            
  387.             // if we got an ID, let's update the data table
  388.                        
  389.             global $wpdb;
  390.            
  391.             $wpdb->show_errors();
  392.            
  393.             $table = $wpdb->prefix . 'popularpostsdata';
  394.            
  395.             // update popularpostsdata table
  396.             $exists = $wpdb->get_results("SELECT postid FROM $table WHERE postid = '$id'");                        
  397.             if ($exists) {
  398.                 // RRR modified to use curdate & now functions above
  399.                 //$result = $wpdb->query("UPDATE $table SET last_viewed = NOW(), pageviews = pageviews + 1 WHERE postid = '$id'");
  400.                 $result = $wpdb->query("UPDATE $table SET last_viewed = ".$this->now().", pageviews = pageviews + 1 WHERE postid = '$id'");
  401.             } else {               
  402.                 // RRR modified to use curdate & now functions above
  403.                 //$result = $wpdb->query("INSERT INTO $table (postid, day, last_viewed) VALUES ('".$id."', NOW(), NOW())");
  404.                 $result = $wpdb->query("INSERT INTO $table (postid, day, last_viewed) VALUES ('".$id."', ".$this->now().", ".$this->now().")" );
  405.             }
  406.            
  407.             // update popularpostsdatacache table
  408.             // RRR modified to use curdate & now functions above
  409.             //$isincache = $wpdb->get_results("SELECT id FROM ".$table."cache WHERE id = '".$id."' AND day = CURDATE()");          
  410.             $isincache = $wpdb->get_results("SELECT id FROM ".$table."cache WHERE id = '".$id."' AND day = ".$this->curdate() );           
  411.             if ($isincache) {
  412.                 // RRR modified to use curdate & now functions above
  413.                 //$result2 = $wpdb->query("UPDATE ".$table."cache SET pageviews = pageviews + 1 WHERE id = '".$id."' AND day = CURDATE()");
  414.                 $result2 = $wpdb->query("UPDATE ".$table."cache SET pageviews = pageviews + 1 WHERE id = '".$id."' AND day = ".$this->curdate() );
  415.             } else {       
  416.                 // RRR modified to use curdate & now functions above
  417.                 //$result2 = $wpdb->query("INSERT INTO ".$table."cache (id, day) VALUES ('".$id."', CURDATE())");
  418.                 $result2 = $wpdb->query("INSERT INTO ".$table."cache (id, day) VALUES ('".$id."', ".$this->curdate().")");
  419.             }
  420.            
  421.             if (($result == 1) && ($result2 == 1)) {
  422.                 die("OK");
  423.             } else {
  424.                 die($wpdb->print_error);
  425.             }      
  426.            
  427.         }
  428.        
  429.         // clears Wordpress Popular Posts' data
  430.         function wpp_clear_data() {
  431.             $token = $_POST['token'];
  432.             $clear = isset($_POST['clear']) ? $_POST['clear'] : '';
  433.             $key = get_option("wpp_rand");
  434.            
  435.             if (current_user_can('manage_options') && ($token === $key) && !empty($clear)) {
  436.                 global $wpdb;
  437.                 // set table name
  438.                 $table = $wpdb->prefix . "popularpostsdata";
  439.                 $cache = $wpdb->prefix . "popularpostsdatacache";
  440.                
  441.                 if ($clear == 'cache') {
  442.                     if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
  443.                         $wpdb->query("TRUNCATE TABLE $cache;");
  444.                         _e('Success! The cache table has been cleared!', 'wordpress-popular-posts');
  445.                     } else {
  446.                         _e('Error: cache table does not exist.', 'wordpress-popular-posts');
  447.                     }
  448.                 } else if ($clear == 'all') {
  449.                     if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") == $table && $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
  450.                         $wpdb->query("TRUNCATE TABLE $table;");
  451.                         $wpdb->query("TRUNCATE TABLE $cache;");
  452.                         _e('Success! All data have been cleared!', 'wordpress-popular-posts');
  453.                     } else {
  454.                         _e('Error: one or both data tables are missing.', 'wordpress-popular-posts');
  455.                     }
  456.                 } else {
  457.                     _e('Invalid action.', 'wordpress-popular-posts');
  458.                 }
  459.             } else {
  460.                 _e('Sorry, you do not have enough permissions to do this. Please contact the site administrator for support.', 'wordpress-popular-posts');
  461.             }
  462.            
  463.             die();
  464.         }
  465.        
  466.         // database install
  467.         function wpp_install() {
  468.             global $wpdb;
  469.             $sql = "";
  470.             $charset_collate = "";
  471.            
  472.             require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
  473.            
  474.             if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
  475.             if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate";
  476.            
  477.             // set table name
  478.             $table = $wpdb->prefix . "popularpostsdata";
  479.            
  480.             // does popularpostsdata table exists?
  481.             if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") != $table ) { // fresh setup
  482.                 // create tables popularpostsdata and popularpostsdatacache
  483.                 $sql = "CREATE TABLE " . $table . " ( UNIQUE KEY id (postid), postid int(10) NOT NULL, day datetime NOT NULL default '0000-00-00 00:00:00', last_viewed datetime NOT NULL default '0000-00-00 00:00:00', pageviews int(10) default 1 ) $charset_collate; CREATE TABLE " . $table ."cache ( UNIQUE KEY id (id, day), id int(10) NOT NULL, day date NOT NULL, pageviews int(10) default 1 ) $charset_collate;";              
  484.             } else {
  485.                 $cache = $table . "cache";
  486.                 if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") != $cache ) {
  487.                     // someone is upgrading from version 1.5.x
  488.                     $sql = "CREATE TABLE " . $table ."cache ( UNIQUE KEY id (id, day), id int(10) NOT NULL, day date NOT NULL, pageviews int(10) default 1 ) $charset_collate;";
  489.                 }
  490.             }
  491.            
  492.             dbDelta($sql);
  493.         }
  494.        
  495.         // prints ajax script to theme's header
  496.         function wpp_print_ajax() {    
  497.             // let's add jQuery
  498.             wp_print_scripts('jquery');
  499.                
  500.             // create security token
  501.             $nonce = wp_create_nonce('wpp-token');
  502.            
  503.             // get current post's ID
  504.             global $wp_query;
  505.             wp_reset_query();
  506.            
  507.             // if we're on a page or post, load the script
  508.             if ( (is_single() || is_page()) && !is_user_logged_in() ) {
  509.                 $id = $wp_query->post->ID;
  510.             ?>
  511. <!-- Wordpress Popular Posts v<?php echo $this->version; ?> -->
  512. <script type="text/javascript" charset="utf-8">
  513.     /* <![CDATA[ */            
  514.     jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {action: 'wpp_update', token: '<?php echo $nonce; ?>', id: <?php echo $id; ?>});
  515.     /* ]]> */
  516. </script>
  517. <!-- End Wordpress Popular Posts v<?php echo $this->version; ?> -->
  518.             <?php
  519.             }
  520.         }      
  521.        
  522.         // prints popular posts
  523.         function get_popular_posts($instance, $echo = true) {      
  524.            
  525.             global $wpdb;
  526.             $table = $wpdb->prefix . "popularpostsdata";
  527.                        
  528.             if ( $instance['pages'] ) {
  529.                 $nopages = '';
  530.             } else {
  531.                 $nopages = "AND $wpdb->posts.post_type = 'post'";
  532.             }
  533.            
  534.             switch( $instance['range'] ) {
  535.                 case 'all':
  536.                     $range = "post_date_gmt < '".gmdate("Y-m-d H:i:s")."'";
  537.                     break;
  538.                 case 'yesterday':
  539.                     $range = $table."cache.day >= '".gmdate("Y-m-d")."' - INTERVAL 1 DAY";
  540.                     break;
  541.                 case 'daily':
  542.                     // RRR modified to use curdate & now functions above
  543.                     //$range = $table."cache.day = CURDATE()";
  544.                     $range = $table."cache.day = ".$this->curdate();
  545.                     break;
  546.                 case 'weekly':
  547.                     $range = $table."cache.day >= '".gmdate("Y-m-d")."' - INTERVAL 7 DAY";
  548.                     break;
  549.                 case 'monthly':
  550.                     $range = $table."cache.day >= '".gmdate("Y-m-d")."' - INTERVAL 30 DAY";
  551.                     break;
  552.                 default:
  553.                     $range = "post_date_gmt < '".gmdate("Y-m-d H:i:s")."'";
  554.                     break;
  555.             }
  556.            
  557.             // sorting options
  558.             switch( $instance['order_by'] ) {
  559.                 case 'comments':
  560.                     $sortby = 'comment_count';
  561.                     break;
  562.                 case 'views':
  563.                     $sortby = 'pageviews';
  564.                     break;
  565.                 case 'avg':
  566.                     $sortby = 'avg_views';
  567.                     break;
  568.                 default:
  569.                     $sortby = 'comment_count';
  570.                     break;
  571.             }
  572.            
  573.            
  574.             // dynamic query fields
  575.             $fields = ', ';        
  576.             if ( $instance['stats_tag']['views'] || ($sortby != 'comment_count') ) {
  577.                 if ( $instance['range'] == 'all') {
  578.                     $fields .= "$table.pageviews AS 'pageviews' ";
  579.                 } else {
  580.                     if ( $sortby == 'avg_views' ) {
  581.                         // RRR modified to use curdate & now functions above
  582.                         //$fields .= "(SUM(".$table."cache.pageviews)/(IF ( DATEDIFF(CURDATE(), MIN(".$table."cache.day)) > 0, DATEDIFF(CURDATE(), MIN(".$table."cache.day)), 1) )) AS 'avg_views' ";
  583.                         $fields .= "(SUM(".$table."cache.pageviews)/(IF ( DATEDIFF(".$this->curdate().", MIN(".$table."cache.day)) > 0, DATEDIFF(".$this->curdate().", MIN(".$table."cache.day)), 1) )) AS 'avg_views' ";
  584.                     } else {
  585.                         $fields .= "(SUM(".$table."cache.pageviews)) AS 'pageviews' ";
  586.                     }
  587.                 }      
  588.             }
  589.            
  590.             if ( $instance['stats_tag']['comment_count'] ) {
  591.                 if ( $fields != ', ' ) {
  592.                     $fields .= ", $wpdb->posts.comment_count AS 'comment_count' ";
  593.                 } else {
  594.                     $fields .= "$wpdb->posts.comment_count AS 'comment_count' ";
  595.                 }
  596.             }
  597.            
  598.             if ( $instance['stats_tag']['author'] ) {
  599.                 if ( $fields != ', ' ) {
  600.                     $fields .= ", (SELECT $wpdb->users.display_name FROM $wpdb->users WHERE $wpdb->users.ID = $wpdb->posts.post_author ) AS 'display_name'";
  601.                 } else {
  602.                     $fields .= "(SELECT $wpdb->users.display_name FROM $wpdb->users WHERE $wpdb->users.ID = $wpdb->posts.post_author ) AS 'display_name'";
  603.                 }
  604.             }
  605.             if ( $instance['stats_tag']['date']['active'] ) {
  606.                 if ( $fields != ', ' ) {
  607.                     $fields .= ", $wpdb->posts.post_date_gmt AS 'date_gmt'";
  608.                 } else {
  609.                     $fields .= "$wpdb->posts.post_date_gmt AS 'date_gmt'";
  610.                 }
  611.             }          
  612.            
  613.             if (strlen($fields) == 2) $fields = '';
  614.  
  615.             if ( $instance['range'] == 'all') {
  616.                 $join = "LEFT JOIN $table ON $wpdb->posts.ID = $table.postid";
  617.                 $force_pv = "AND ".$table.".pageviews > 0 ";
  618.             } else {
  619.                 $join = "RIGHT JOIN ".$table."cache ON $wpdb->posts.ID = ".$table."cache.id";
  620.                 $force_pv = "";
  621.             }
  622.            
  623.             // Category excluding snippet suggested by user raamdev at http://wordpress.org/support/topic/397885
  624.             // Thanks, raamdev!
  625. //Include categories feature, i simplified the select, because I think the double subselect is unnecessary
  626.             if ( $instance['exclude-cats']['active'] && !empty($instance['exclude-cats']['cats']) ) {
  627.                 $exclude = " AND $wpdb->posts.ID NOT IN (
  628.  
  629.                             SELECT  object_id
  630.                             FROM    $wpdb->term_relationships AS r
  631.                                     JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  632.                                     JOIN $wpdb->terms AS t ON t.term_id = x.term_id
  633.                             WHERE   x.taxonomy = 'category'
  634.                                     AND t.term_id IN  (".$instance['exclude-cats']['cats'].")) ";
  635.             } else {
  636.                 $exclude = "";
  637.             }
  638. //Include categories feature
  639.  
  640. //Include categories feature, the select was simplified        
  641.             if ( $instance['include-cats']['active'] && !empty($instance['include-cats']['cats']) ) {
  642.                 $include = " AND $wpdb->posts.ID IN (
  643.  
  644.                             SELECT  object_id
  645.                             FROM    $wpdb->term_relationships AS r
  646.                                     JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  647.                                     JOIN $wpdb->terms AS t ON t.term_id = x.term_id
  648.                             WHERE   x.taxonomy = 'category'
  649.                                     AND t.term_id IN  (".$instance['include-cats']['cats'].")) ";
  650.             } else {
  651.                 $include = "";
  652.             }
  653. //Include categories feature
  654.  
  655. //Include categories feature, include query string in the select           
  656.             $mostpopular = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title $fields FROM $wpdb->posts $join WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_password = '' AND $range $force_pv $nopages $exclude $include GROUP BY $wpdb->posts.ID ORDER BY $sortby DESC LIMIT " . $instance['limit'] . "");
  657. //Include categories feature
  658.            
  659.             $content = '';
  660.            
  661.             if ( !is_array($mostpopular) || empty($mostpopular) ) {
  662.                 $content .= "<p>".__('Sorry. No data so far.', 'wordpress-popular-posts')."</p>"."\n";
  663.             } else {
  664.                
  665.                 if ($instance['markup']['custom_html']) {
  666.                     $content .= htmlspecialchars_decode($instance['markup']['wpp-start'], ENT_QUOTES) ."\n";
  667.                 } else {
  668.                     $content .= "<ul>" . "\n";
  669.                 }
  670.                
  671.                 foreach ($mostpopular as $wppost) {                
  672.                
  673.                     $post_stats = "";
  674.                     $stats = "";
  675.                     $thumb = "";
  676.                     $data = array();
  677.                    
  678.                     // get post title
  679.                     /* qTranslate integration check */
  680.                     ($this->qTrans) ? $tit = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($wppost->post_title) : $tit = $wppost->post_title;
  681.                    
  682.                     $tit = ($this->magicquotes) ? stripslashes($tit) : $tit;
  683.                     $title_attr = htmlentities($tit, ENT_QUOTES, $this->charset);
  684.                    
  685.                     if ( $instance['shorten_title']['active'] && (strlen($tit) > $instance['shorten_title']['length'])) {
  686.                         $tit = mb_substr($tit, 0, $instance['shorten_title']['length'], $this->charset) . "...";
  687.                     }
  688.                    
  689.                     $tit = htmlentities($tit, ENT_QUOTES, $this->charset);
  690.                    
  691.                     // get post excerpt
  692.                     if ( $instance['post-excerpt']['active'] ) {
  693.                         if ($instance['markup']['pattern']['active']) {
  694.                             $post_content = "<span class=\"wpp-excerpt\">" . $this->get_summary($wppost->ID, $instance) . "</span>";
  695.                         } else {
  696.                             $post_content = ": <span class=\"wpp-excerpt\">" . $this->get_summary($wppost->ID, $instance) . "...</span>";
  697.                         }
  698.                     } else {
  699.                         $post_content = "";
  700.                     }
  701.                    
  702.                     // build stats tag
  703.                     if ( $instance['stats_tag']['comment_count'] ) {
  704.                         $comment_count = (int) $wppost->comment_count;
  705.                         $post_stats .= "<span class=\"wpp-comments\">" . $comment_count . " " . __(' comment(s)', 'wordpress-popular-posts') . "</span>";
  706.                     }
  707.                     if ( $instance['stats_tag']['views'] ) {
  708.                         $views_text = __(' view(s)', 'wordpress-popular-posts');
  709.                         if ($instance['order_by'] == 'views') {
  710.                             $pageviews = (int) $wppost->pageviews;
  711.                         } else if ($instance['order_by'] == 'avg') {
  712.                             $pageviews = ceil($wppost->avg_views);
  713.                             if ($instance['range'] != 'daily') $views_text = __(' view(s) per day', 'wordpress-popular-posts');
  714.                         } else {
  715.                             $pageviews = (int) $wppost->pageviews;
  716.                         }          
  717.                        
  718.                         if ($post_stats != "") {
  719.                             $post_stats .= " | <span class=\"wpp-views\">$pageviews $views_text</span>";
  720.                         } else {                           
  721.                             $post_stats .= "<span class=\"wpp-views\">$pageviews $views_text</span>";
  722.                         }                                      
  723.                     }
  724.                     if ( $instance['stats_tag']['author'] ) {
  725.                         if ($post_stats != "") {
  726.                             $post_stats .= " | ".__('by', 'wordpress-popular-posts')." <span class=\"wpp-author\">".$wppost->display_name."</span>";
  727.                         } else {                   
  728.                             $post_stats .= __('by', 'wordpress-popular-posts')." <span class=\"wpp-author\">".$wppost->display_name."</span>";
  729.                         }
  730.                     }
  731.                     if ( $instance['stats_tag']['date']['active'] ) {
  732.                         if ($post_stats != "") {
  733.                             $post_stats .= " | <span class=\"wpp-date\">".__('posted on', 'wordpress-popular-posts')." ".date_i18n($instance['stats_tag']['date']['format'], strtotime($wppost->date_gmt))."</span>";
  734.                         } else {                   
  735.                             $post_stats .= "<span class=\"wpp-date\">".__('posted on', 'wordpress-popular-posts')." ".date_i18n($instance['stats_tag']['date']['format'], strtotime($wppost->date_gmt))."</span>";
  736.                         }
  737.                     }
  738.                    
  739.                     if (!empty($post_stats)) {
  740.                         $stats = ' <span class="post-stats">' . $post_stats . '</span> ';
  741.                     }
  742.                    
  743.                     // get thumbnail
  744.                     if ($instance['thumbnail']['active'] && $this->thumb) {
  745.                         $tbWidth = $instance['thumbnail']['width'];
  746.                         $tbHeight = $instance['thumbnail']['height'];
  747.                        
  748.                         // default image
  749.                         $thumb = "<a href=\"".get_permalink($wppost->ID)."\" class=\"wppnothumb\" title=\"". $title_attr ."\"><img src=\"". $this->pluginDir . "/no_thumb.jpg\" alt=\"".$title_attr."\" border=\"0\" class=\"wpp-thumbnail\" width=\"".$tbWidth."\" height=\"".$tbHeight."\" "."/></a>";
  750.                        
  751.                         // let's try to retrieve the post thumbnail!                       
  752.                         if (function_exists('get_the_post_thumbnail') && has_post_thumbnail( $wppost->ID )) {                              
  753.                             $thumb = "<a href=\"".get_permalink($wppost->ID)."\" title=\"". $title_attr ."\">" . get_the_post_thumbnail($wppost->ID, array($tbWidth, $tbHeight), array('class' => 'wpp-thumbnail', 'alt' => $title_attr, 'title' => $title_attr) ) ."</a>";
  754.                         }
  755.                        
  756.                     }
  757.                    
  758.                     // get rating
  759.                     if ($instance['rating'] && $this->postRating) {
  760.                         $rating = '<span class="wpp-rating">'.the_ratings_results($wppost->ID).'</span>';
  761.                     } else {
  762.                         $rating = '';
  763.                     }
  764.                     $data = array(
  765.                         'title' => '<a href="'.get_permalink($wppost->ID).'" title="'. $title_attr .'"><span class="wpp-post-title">'. $tit .'</span></a>',
  766.                         'summary' => $post_content,
  767.                         'stats' => $stats,
  768.                         'img' => $thumb,
  769.                         'id' => $wppost->ID
  770.                     );     
  771.                    
  772.                     // build custom layout
  773.                     if ($instance['markup']['custom_html']) {
  774.                         if ($instance['markup']['pattern']['active']) {
  775.                             $content .= htmlspecialchars_decode($instance['markup']['post-start'], ENT_QUOTES) . $this->format_content($instance['markup']['pattern']['form'], $data, $instance['rating']) . htmlspecialchars_decode($instance['markup']['post-end'], ENT_QUOTES) . "\n";
  776.                         } else {
  777.                             $content .= htmlspecialchars_decode($instance['markup']['post-start'], ENT_QUOTES) . $thumb . '<a href="'.get_permalink($wppost->ID).'" title="'. $title_attr .'"><span class="wpp-post-title">'. $tit .'</span></a>'.$post_content.' '. $stats . $rating . htmlspecialchars_decode($instance['markup']['post-end'], ENT_QUOTES) . "\n";
  778.                         }
  779.                     } else {
  780.                         $content .= '<li>'. $thumb .'<a href="'. get_permalink($wppost->ID) .'" title="'. $title_attr .'"><span class="wpp-post-title">'. $tit .'</span></a>'. $post_content .' '. $stats . $rating .'</li>' . "\n";
  781.                     }
  782.                 }          
  783.                
  784.                 if ($instance['markup']['custom_html']) {
  785.                     $content .= htmlspecialchars_decode($instance['markup']['wpp-end'], ENT_QUOTES) ."\n";
  786.                 } else {
  787.                     $content .= "\n"."</ul>"."\n";
  788.                 }
  789.                
  790.             }
  791.            
  792.             if ($echo) { echo "<noscript>" . $content . "</noscript>"; } else { return $content; }
  793.         }      
  794.        
  795.         // builds posts' excerpt
  796.         function get_summary($id, $instance){
  797.             if (!is_numeric($id)) return false;
  798.             global $wpdb;          
  799.             $excerpt = "";
  800.             $result = "";
  801.            
  802.             $result = $wpdb->get_results("SELECT post_excerpt FROM $wpdb->posts WHERE ID = " . $id, ARRAY_A);
  803.            
  804.             if (empty($result[0]['post_excerpt'])) {
  805.                 // no custom excerpt defined, how lazy of you!             
  806.                 $result = $wpdb->get_results("SELECT post_content FROM $wpdb->posts WHERE ID = " . $id, ARRAY_A);
  807.                 $excerpt = preg_replace("/\[caption.*\[\/caption\]/", "", $result[0]['post_content']);
  808.             } else {
  809.                 // user has defined a custom excerpt, yay!
  810.                 $excerpt = preg_replace("/\[caption.*\[\/caption\]/", "", $result[0]['post_excerpt']);
  811.             }
  812.            
  813.             // RRR added call to the_content filters, allows qTranslate to hook in.
  814.             if ($this->qTrans) $excerpt = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($excerpt);
  815.            
  816.             $excerpt = preg_replace("/<object[0-9 a-z_?*=\":\-\/\.#\,\\n\\r\\t]+/smi", "", $excerpt);
  817.            
  818.             if ($instance['post-excerpt']['keep_format']) {
  819.                 $excerpt = strip_tags($excerpt, '<a><b><i><strong><em>');
  820.             } else {
  821.                 $excerpt = strip_tags($excerpt);
  822.             }
  823.            
  824.             if (strlen($excerpt) > $instance['post-excerpt']['length']) {
  825.                 $excerpt = $this->truncate($excerpt, $instance['post-excerpt']['length'], '', true, true);
  826.             }
  827.            
  828.             return $excerpt;
  829.         }
  830.        
  831.         // gets the first image of post / page
  832.         function get_img($id = "", $print = false) {
  833.             if ( empty($id) || !is_numeric($id) ) return false;
  834.            
  835.             // get post attachments
  836.             $attachments = get_children(array('post_parent' => $id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order'));
  837.            
  838.             // no image has been found
  839.             if ( ! is_array($attachments) ) return false;
  840.            
  841.             $count = count($attachments);
  842.             $first_attachment = array_shift($attachments);         
  843.             $img = wp_get_attachment_image($first_attachment->ID);
  844.            
  845.             preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'\s>]*)/i', $img, $imgm);
  846.            
  847.             if ($print)
  848.                     echo $imgm[1];
  849.                 else
  850.                     return $imgm;
  851.  
  852.         }
  853.        
  854.         // parses content structure defined by user
  855.         function format_content ($string, $data = array(), $rating) {
  856.             if (empty($string) || (empty($data) || !is_array($data))) return false;
  857.            
  858.             $params = array();
  859.             $pattern = '/\{(summary|stats|title|image|rating)\}/i';    
  860.             preg_match_all($pattern, $string, $matches);
  861.            
  862.             for ($i=0; $i < count($matches[0]); $i++) {    
  863.                 if (strtolower($matches[0][$i]) == "{title}") {
  864.                     $params[$matches[0][$i]] = $data['title'];
  865.                     continue;
  866.                 }
  867.                 if (strtolower($matches[0][$i]) == "{stats}") {
  868.                     $params[$matches[0][$i]] = $data['stats'];
  869.                     continue;
  870.                 }
  871.                 if (strtolower($matches[0][$i]) == "{summary}") {
  872.                     $params[$matches[0][$i]] = $data['summary'];
  873.                     continue;
  874.                 }
  875.                 if (strtolower($matches[0][$i]) == "{image}") {
  876.                     $params[$matches[0][$i]] = $data['img'];
  877.                     continue;
  878.                 }
  879.                 // WP-PostRatings check
  880.                 if ($rating) {
  881.                     if (strtolower($matches[0][$i]) == "{rating}") {
  882.                         $params[$matches[0][$i]] = the_ratings_results($data['id']);
  883.                         continue;
  884.                     }
  885.                 }
  886.             }
  887.            
  888.             for ($i=0; $i < count($params); $i++) {    
  889.                 $string = str_replace($matches[0][$i], $params[$matches[0][$i]], $string);
  890.             }
  891.            
  892.             return $string;
  893.         }      
  894.        
  895.         // code seen at http://www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags/
  896.         // Since 2.0.1
  897.         /**
  898.          * Truncates text.
  899.          *
  900.          * Cuts a string to the length of $length and replaces the last characters
  901.          * with the ending if the text is longer than length.
  902.          *
  903.          * @param string  $text String to truncate.
  904.          * @param integer $length Length of returned string, including ellipsis.
  905.          * @param string  $ending Ending to be appended to the trimmed string.
  906.          * @param boolean $exact If false, $text will not be cut mid-word
  907.          * @param boolean $considerHtml If true, HTML tags would be handled correctly
  908.          * @return string Trimmed string.
  909.          */    
  910.         function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) {
  911.             if ($considerHtml) {
  912.                 // if the plain text is shorter than the maximum length, return the whole text
  913.                 if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  914.                     return $text;
  915.                 }
  916.                 // splits all html-tags to scanable lines
  917.                 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  918.                 $total_length = strlen($ending);
  919.                 $open_tags = array();
  920.                 $truncate = '';
  921.                 foreach ($lines as $line_matchings) {
  922.                     // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  923.                     if (!empty($line_matchings[1])) {
  924.                         // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
  925.                         if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  926.                             // do nothing
  927.                         // if tag is a closing tag (f.e. </b>)
  928.                         } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  929.                             // delete tag from $open_tags list
  930.                             $pos = array_search($tag_matchings[1], $open_tags);
  931.                             if ($pos !== false) {
  932.                                 unset($open_tags[$pos]);
  933.                             }
  934.                         // if tag is an opening tag (f.e. <b>)
  935.                         } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  936.                             // add tag to the beginning of $open_tags list
  937.                             array_unshift($open_tags, strtolower($tag_matchings[1]));
  938.                         }
  939.                         // add html-tag to $truncate'd text
  940.                         $truncate .= $line_matchings[1];
  941.                     }
  942.                     // calculate the length of the plain text part of the line; handle entities as one character
  943.                     $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  944.                     if ($total_length+$content_length> $length) {
  945.                         // the number of characters which are left
  946.                         $left = $length - $total_length;
  947.                         $entities_length = 0;
  948.                         // search for html entities
  949.                         if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  950.                             // calculate the real length of all entities in the legal range
  951.                             foreach ($entities[0] as $entity) {
  952.                                 if ($entity[1]+1-$entities_length <= $left) {
  953.                                     $left--;
  954.                                     $entities_length += strlen($entity[0]);
  955.                                 } else {
  956.                                     // no more characters left
  957.                                     break;
  958.                                 }
  959.                             }
  960.                         }
  961.                         $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
  962.                         // maximum lenght is reached, so get off the loop
  963.                         break;
  964.                     } else {
  965.                         $truncate .= $line_matchings[2];
  966.                         $total_length += $content_length;
  967.                     }
  968.                     // if the maximum length is reached, get off the loop
  969.                     if($total_length>= $length) {
  970.                         break;
  971.                     }
  972.                 }
  973.             } else {
  974.                 if (strlen($text) <= $length) {
  975.                     return $text;
  976.                 } else {
  977.                     $truncate = substr($text, 0, $length - strlen($ending));
  978.                 }
  979.             }
  980.             // if the words shouldn't be cut in the middle...
  981.             if (!$exact) {
  982.                 // ...search the last occurance of a space...
  983.                 $spacepos = strrpos($truncate, ' ');
  984.                 if (isset($spacepos)) {
  985.                     // ...and cut the text in this position
  986.                     $truncate = substr($truncate, 0, $spacepos);
  987.                 }
  988.             }
  989.             // add the defined ending to the text
  990.             $truncate .= $ending;
  991.             if($considerHtml) {
  992.                 // close all unclosed html-tags
  993.                 foreach ($open_tags as $tag) {
  994.                     $truncate .= '</' . $tag . '>';
  995.                 }              
  996.             }
  997.             return $truncate;
  998.         }
  999.        
  1000.         // plugin localization (Credits: Aleksey Timkov at@uadeveloper.com)
  1001.         function wpp_textdomain() {
  1002.             load_plugin_textdomain('wordpress-popular-posts', false, dirname(plugin_basename( __FILE__ )));
  1003.         }
  1004.        
  1005.         // insert Wordpress Popular Posts' stylesheet in theme's head section, just in case someone needs it
  1006.         function wpp_print_stylesheet() {
  1007.             echo "\n"."<!-- Wordpress Popular Posts -->"."\n".'<link rel="stylesheet" href="'.plugin_dir_url( __FILE__ ).'style/wpp.css" type="text/css" media="screen" />'."\n"."<!-- End Wordpress Popular Posts -->"."\n";  
  1008.         }
  1009.        
  1010.         // create Wordpress Popular Posts' maintenance page
  1011.         function wpp_maintenance_page() {
  1012.             require (dirname(__FILE__) . '/maintenance.php');
  1013.         }  
  1014.         function add_wpp_maintenance_page() {          
  1015.             add_submenu_page( 'options-general.php', 'Wordpress Popular Posts', 'Wordpress Popular Posts', 'manage_options', 'wpp_maintenance_page', array(&$this, 'wpp_maintenance_page') );
  1016.         }
  1017.        
  1018.         // version update warning
  1019.         function wpp_update_warning() {
  1020.             $msg = '<div id="wpp-message" class="error fade"><p>'.__('Your Wordpress version is too old. Wordpress Popular Posts Plugin requires at least version 2.8 to function correctly. Please update your blog via Tools &gt; Upgrade.', 'wordpress-popular-posts').'</p></div>';
  1021.             echo trim($msg);
  1022.         }
  1023.        
  1024.         // cache maintenance
  1025.         function wpp_cache_maintenance() {
  1026.             global $wpdb;
  1027.             // RRR modified to use curdate & now functions above
  1028.             //$wpdb->query("DELETE FROM ".$wpdb->prefix."popularpostsdatacache WHERE day < DATE_SUB(CURDATE(), INTERVAL 30 DAY);");
  1029.             $wpdb->query("DELETE FROM ".$wpdb->prefix."popularpostsdatacache WHERE day < DATE_SUB(".$this->curdate().", INTERVAL 30 DAY);");
  1030.         }
  1031.        
  1032.         // plugin deactivation
  1033.         function wpp_deactivation() {
  1034.             wp_clear_scheduled_hook('wpp_cache_event');
  1035.             remove_shortcode('wpp');
  1036.             remove_shortcode('WPP');
  1037.            
  1038.             delete_option('wpp_ver');
  1039.         }
  1040.        
  1041.         // shortcode handler
  1042.         function wpp_shortcode($atts = NULL, $content = NULL) {
  1043.             extract( shortcode_atts( array(
  1044.                 'header' => '',
  1045.                 'limit' => 10,
  1046.                 'range' => 'daily',
  1047.                 'order_by' => 'comments',
  1048.                 'pages' => true,
  1049.                 'title_length' => 0,
  1050.                 'excerpt_length' => 0,
  1051.                 'excerpt_format' => 0,
  1052.                 'cats_to_exclude' => '',
  1053. //Include categories feature
  1054.                 'cats_to_include' => '',
  1055. //Include categories feature
  1056.                 'thumbnail_width' => 0,
  1057.                 'thumbnail_height' => 0,
  1058.                 'thumbnail_selection' => 'wppgenerated',
  1059.                 'rating' => false,
  1060.                 'stats_comments' => true,
  1061.                 'stats_views' => false,
  1062.                 'stats_author' => false,
  1063.                 'stats_date' => false,
  1064.                 'stats_date_format' => 'F j, Y',
  1065.                 'wpp_start' => '<ul>',
  1066.                 'wpp_end' => '</ul>',
  1067.                 'post_start' => '<li>',
  1068.                 'post_end' => '</li>',
  1069.                 'header_start' => '<h2>',
  1070.                 'header_end' => '</h2>',
  1071.                 'do_pattern' => false,
  1072.                 'pattern_form' => '{image} {title}: {summary} {stats}'
  1073.             ), $atts ) );
  1074.            
  1075.             // possible values for "Time Range" and "Order by"
  1076.             $range_values = array("yesterday", "daily", "weekly", "monthly", "all");
  1077.             $order_by_values = array("comments", "views", "avg");
  1078.             $thumbnail_selector = array("wppgenerated", "usergenerated");
  1079.            
  1080.             $shortcode_ops = array(
  1081.                 'title' => strip_tags($header),
  1082.                 'limit' => empty($limit) ? 10 : (is_numeric($limit)) ? (($limit > 0) ? $limit : 10) : 10,
  1083.                 'range' => (in_array($range, $range_values)) ? $range : 'daily',
  1084.                 'order_by' => (in_array($order_by, $order_by_values)) ? $order_by : 'comments',
  1085.                 'pages' => empty($pages) ? false : $pages,
  1086.                 'shorten_title' => array(
  1087.                     'active' => empty($title_length) ? false : (is_numeric($title_length)) ? (($title_length > 0) ? true : false) : false,
  1088.                     'length' => empty($title_length) ? 0 : (is_numeric($title_length)) ? $title_length : 0
  1089.                 ),
  1090.                 'post-excerpt' => array(
  1091.                     'active' => empty($excerpt_length) ? false : (is_numeric($excerpt_length)) ? (($excerpt_length > 0) ? true : false) : false,
  1092.                     'length' => empty($excerpt_length) ? 0 : (is_numeric($excerpt_length)) ? $excerpt_length : 0,
  1093.                     'keep_format' => empty($excerpt_format) ? false : (is_numeric($excerpt_format)) ? (($excerpt_format > 0) ? true : false) : false,
  1094.                 ),
  1095.                 'exclude-cats' => array(
  1096.                     'active' => empty($cats_to_exclude) ? false : (ctype_digit(str_replace(",", "", $cats_to_exclude))) ? true : false,
  1097.                     'cats' => empty($cats_to_exclude) ? '' : (ctype_digit(str_replace(",", "", $cats_to_exclude))) ? $cats_to_exclude : ''
  1098.                 ),
  1099. //Include categories feature       
  1100.                 'include-cats' => array(
  1101.                     'active' => empty($cats_to_include) ? false : (ctype_digit(str_replace(",", "", $cats_to_include))) ? true : false,
  1102.                     'cats' => empty($cats_to_include) ? '' : (ctype_digit(str_replace(",", "", $cats_to_include))) ? $cats_to_include : ''
  1103.                 ),
  1104. //Include categories feature
  1105.                 'thumbnail' => array(
  1106.                     'active' => empty($thumbnail_width) ? false : (is_numeric($thumbnail_width)) ? (($thumbnail_width > 0) ? true : false) : false,
  1107.                     'thumb_selection' => 'usergenerated',
  1108.                     'width' => empty($thumbnail_width) ? 0 : (is_numeric($thumbnail_width)) ? $thumbnail_width : 0,
  1109.                     'height' => empty($thumbnail_height) ? 0 : (is_numeric($thumbnail_height)) ? $thumbnail_height : 0
  1110.                 ),
  1111.                 'rating' => empty($rating) ? false : (bool)$rating,
  1112.                 'stats_tag' => array(
  1113.                     'comment_count' => empty($stats_comments) ? false : $stats_comments,
  1114.                     'views' => empty($stats_views) ? false : $stats_views,
  1115.                     'author' => empty($stats_author) ? false : $stats_author,
  1116.                     'date' => array(
  1117.                         'active' => empty($stats_date) ? false : $stats_date,
  1118.                         'format' => empty($stats_date_format) ? 'F j, Y' : $stats_date_format
  1119.                     )
  1120.                 ),
  1121.                 'markup' => array(
  1122.                     'custom_html' => true,
  1123.                     'wpp-start' => empty($wpp_start) ? '<ul>' : $wpp_start,
  1124.                     'wpp-end' => empty($wpp_end) ? '</ul>' : $wpp_end,
  1125.                     'post-start' => empty($post_start) ? '<li>;' : $post_start,
  1126.                     'post-end' => empty($post_end) ? '</li>' : $post_end,
  1127.                     'title-start' => empty($header_start) ? '' : $header_start,
  1128.                     'title-end' => empty($header_end) ? '' : $header_end,
  1129.                     'pattern' => array(
  1130.                         'active' => empty($do_pattern) ? false : (bool)$do_pattern,
  1131.                         'form' => empty($pattern_form) ? '{image} {title}: {summary} {stats}' : $pattern_form
  1132.                     )
  1133.                 )
  1134.             );
  1135.            
  1136.             $shortcode_content = "";
  1137.            
  1138.             $shortcode_content .= "<!-- Wordpress Popular Posts Plugin v". $this->version ." [SC] [".$shortcode_ops['range']."]". (($shortcode_ops['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
  1139.            
  1140.             // is there a title defined by user?
  1141.             if (!empty($header) && !empty($header_start) && !empty($header_end)) {
  1142.                 $shortcode_content .= $header_start . $header . $header_end;
  1143.             }
  1144.            
  1145.             // print popular posts list
  1146.             $shortcode_content .= $this->get_popular_posts($shortcode_ops, false);
  1147.            
  1148.             $shortcode_content .= "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
  1149.            
  1150.             return $shortcode_content;
  1151.         }
  1152.        
  1153.         // stats page
  1154.         // Since 2.0.3
  1155.         function wpp_stats() {
  1156.             if ( function_exists('add_submenu_page') ) add_submenu_page('index.php', __('Wordpress Popular Posts Stats'), __('Wordpress Popular Posts Stats'), 'manage_options', 'wpp-stats-display', array(&$this, 'wpp_stats_display'));
  1157.         }
  1158.        
  1159.         function wpp_stats_display() {
  1160.             require (dirname(__FILE__) . '/stats.php');
  1161.         }
  1162.     }
  1163.    
  1164.     // database creation
  1165.     register_activation_hook('WordpressPopularPosts', 'wpp_install');
  1166.    
  1167.     // print stylesheet
  1168.     //add_action('wp_head', array('WordpressPopularPosts', 'wpp_print_stylesheet'));
  1169. }
  1170.  
  1171. /**
  1172.  * Wordpress Popular Posts template tags for use in themes.
  1173.  */
  1174.  
  1175. // gets views count
  1176. // Since 2.0.0
  1177. function wpp_get_views($id = NULL) {
  1178.     // have we got an id?
  1179.     if ( empty($id) || is_null($id) || !is_numeric($id) ) {
  1180.         return "-1";
  1181.     } else {       
  1182.         global $wpdb;
  1183.        
  1184.         $table_name = $wpdb->prefix . "popularpostsdata";      
  1185.         $result = $wpdb->get_results("SELECT pageviews FROM $table_name WHERE postid = '$id'", ARRAY_A);
  1186.        
  1187.         if ( !is_array($result) || empty($result) ) {
  1188.             return "0";
  1189.         } else {
  1190.             return $result[0]['pageviews'];
  1191.         }
  1192.     }
  1193. }
  1194.  
  1195. // gets popular posts
  1196. // Since 2.0.3
  1197. function wpp_get_mostpopular($args = NULL) {
  1198.  
  1199.     if (is_null($args)) {
  1200.         echo do_shortcode('[wpp]');
  1201.     } else {
  1202.         $atts = trim(str_replace("&", " ", $args));
  1203.         echo do_shortcode('[wpp '.$atts.']');
  1204.     }
  1205. }
  1206.  
  1207. // gets popular posts
  1208. /**
  1209.  * Deprecated in 2.0.3.
  1210.  * Use wpp_get_mostpopular instead.
  1211.  */
  1212. function get_mostpopular($args = NULL) {
  1213.     return wpp_get_mostpopular($args);
  1214. }
  1215.  
  1216.  
  1217. /**
  1218.  * Wordpress Popular Posts 2.1.6 Changelog.
  1219.  */
  1220.  
  1221. /*
  1222.     = 2.1.6 =
  1223.     * Added DB character set and collate detection.
  1224.     * Fixed excerpt translation issue when the qTrans plugin is present. Thanks r3df!.
  1225.     * Fixed thumbnail dimensions issue.
  1226.     * Fixed widget page link.
  1227.     * Fixed widget title encoding bug.
  1228.     * Fixed deprecated errors on load_plugin_textdomain and add_submenu_page.
  1229. */
  1230.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement