Advertisement
Guest User

Untitled

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