PluginProbe ʕ •ᴥ•ʔ
WP Popular Posts / 2.3.7
WP Popular Posts v2.3.7
4.0.8 4.0.9 4.1.0 4.1.1 4.1.2 4.2.0 4.2.1 4.2.2 5.0.0 5.0.1 5.0.2 5.1.0 5.2.0 5.2.1 5.2.2 5.2.3 5.2.4 5.3.0 5.3.1 5.3.2 5.3.3 5.3.4 5.3.5 5.3.6 5.4.0 5.4.1 5.4.2 5.5.0 5.5.1 6.0.0 6.0.1 6.0.2 6.0.3 6.0.4 6.0.5 6.1.0 6.1.1 6.1.2 6.1.3 6.1.4 6.2.0 6.2.1 6.3.0 6.3.1 6.3.2 6.3.3 6.3.4 6.4.0 6.4.1 6.4.2 7.0.0 7.0.1 7.1.0 7.2.0 7.3.0 7.3.1 7.3.2 7.3.3 7.3.4 7.3.5 7.3.6 7.3.7 7.3.8 7.4.0 trunk 2.3.7 3.0.0 3.0.1 3.0.2 3.0.3 3.1.0 3.1.1 3.2.0 3.2.1 3.2.2 3.2.3 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4 4.0.0 4.0.1 4.0.10 4.0.11 4.0.12 4.0.13 4.0.2 4.0.3 4.0.5 4.0.6
wordpress-popular-posts / wordpress-popular-posts.php
wordpress-popular-posts Last commit date
js 13 years ago lang 12 years ago style 13 years ago admin.php 12 years ago btn_donateCC_LG_global.gif 16 years ago index.php 16 years ago no_thumb.jpg 15 years ago readme.md 12 years ago readme.txt 12 years ago wordpress-popular-posts.php 12 years ago
wordpress-popular-posts.php
2197 lines
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.3.7
7 Author: H&eacute;ctor Cabrera
8 Author URI: http://cabrerahector.com
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 if ( !class_exists('WordpressPopularPosts') ) {
28
29 class WordpressPopularPosts extends WP_Widget {
30 // plugin global variables
31 var $version = "2.3.7";
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 var $default_thumbnail = "";
39 var $user_ops = array();
40 var $defaults = array(
41 'title' => '',
42 'limit' => 10,
43 'range' => 'daily',
44 'order_by' => 'views',
45 'post_type' => 'post,page',
46 'pid' => '',
47 'author' => '',
48 'cat' => '',
49 'shorten_title' => array(
50 'active' => false,
51 'length' => 25,
52 'words' => false
53 ),
54 'post-excerpt' => array(
55 'active' => false,
56 'length' => 55,
57 'keep_format' => false,
58 'words' => false
59 ),
60 'thumbnail' => array(
61 'active' => false,
62 'width' => 15,
63 'height' => 15
64 ),
65 'rating' => false,
66 'stats_tag' => array(
67 'comment_count' => true,
68 'views' => false,
69 'author' => false,
70 'date' => array(
71 'active' => false,
72 'format' => 'F j, Y'
73 ),
74 'category' => false
75 ),
76 'markup' => array(
77 'custom_html' => false,
78 'wpp-start' => '&lt;ul class="wpp-list"&gt;',
79 'wpp-end' => '&lt;/ul&gt;',
80 'post-html' => '&lt;li&gt;{thumb} {title} {stats}&lt;/li&gt;',
81 'post-start' => '&lt;li&gt;',
82 'post-end' => '&lt;/li&gt;',
83 'title-start' => '&lt;h2&gt;',
84 'title-end' => '&lt;/h2&gt;'
85 )
86 );
87 var $wpp_user_settings_def = array(
88 'stats' => array(
89 'order_by' => 'views',
90 'limit' => 10,
91 'post_type' => 'post,page'
92 ),
93 'tools' => array(
94 'ajax' => false,
95 'css' => true,
96 'stylesheet' => true,
97 'link' => array(
98 'target' => '_self'
99 ),
100 'thumbnail' => array(
101 'source' => 'featured',
102 'field' => '',
103 'resize' => false,
104 'default' => ''
105 ),
106 'log_loggedin' => false,
107 'cache' => array(
108 'active' => false,
109 'interval' => array(
110 'time' => 'hour',
111 'value' => 1
112 )
113 )
114 )
115 );
116
117 /**
118 * WPP's Constructor
119 * Since 1.4.0
120 */
121 function WordpressPopularPosts() {
122 global $wp_version;
123
124 // Set default title
125 $this->defaults['title'] = __('Popular Posts', 'wordpress-popular-posts');
126
127 // widget settings
128 $widget_ops = array( 'classname' => 'popular-posts', 'description' => __('The most Popular Posts on your blog.', 'wordpress-popular-posts') );
129
130 // widget control settings
131 $control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'wpp' );
132
133 // create the widget
134 $this->WP_Widget( 'wpp', 'Wordpress Popular Posts', $widget_ops, $control_ops );
135
136 // set plugin path
137 if (empty($this->pluginDir)) $this->pluginDir = plugin_dir_url(__FILE__);
138
139 // set charset
140 $this->charset = get_bloginfo('charset');
141
142 // detect PHP magic quotes
143 $this->magicquotes = get_magic_quotes_gpc();
144
145 // get user options
146 $this->user_ops = get_option('wpp_settings_config');
147 if ( !$this->user_ops ) {
148 add_option('wpp_settings_config', $this->wpp_user_settings_def);
149 $this->user_ops = $this->wpp_user_settings_def;
150 }
151
152 // set default thumbnail
153 $this->default_thumbnail = $this->pluginDir . "no_thumb.jpg";
154 $this->wpp_user_settings_def['tools']['thumbnail']['default'] = $this->default_thumbnail;
155
156 if ( !empty($this->user_ops['tools']['thumbnail']['default']) ) {
157 $this->default_thumbnail = $this->user_ops['tools']['thumbnail']['default'];
158 }
159
160 // set version and check for upgrades
161 $wpp_ver = get_option('wpp_ver');
162 if ( !$wpp_ver ) {
163 add_option('wpp_ver', $this->version);
164 } else if ( version_compare($wpp_ver, $this->version, '<') ) {
165 $this->wpp_upgrade();
166 }
167
168 // print stylesheet
169 if ($this->user_ops['tools']['css']) {
170 add_action('get_header', array(&$this, 'wpp_print_stylesheet'));
171 }
172
173 //wpp_ajax_get_popular
174 add_action('wp_ajax_wpp_ajax_get_popular', array(&$this, 'ajax_getpopular'));
175 add_action('wp_ajax_nopriv_wpp_ajax_get_popular', array(&$this, 'ajax_getpopular'));
176
177 if ($this->user_ops['tools']['ajax']) {
178 remove_action('the_content', array(&$this,'wpp_update') );
179 // add ajax update to wp_ajax_ hook
180 if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 1 ) {
181 add_action('wp_ajax_wpp_update', array(&$this, 'wpp_ajax_update'));
182 }
183 add_action('wp_ajax_nopriv_wpp_update', array(&$this, 'wpp_ajax_update'));
184 add_action('wp_head', array(&$this, 'wpp_print_ajax'));
185
186 } else {
187 // stop Wordpress from preloading next post and thus calling single.php twice!
188 remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
189
190 if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 1 ) {
191 remove_action('wp_ajax_wpp_update', array(&$this, 'wpp_ajax_update'));
192 }
193 remove_action('wp_ajax_nopriv_wpp_update', array(&$this, 'wpp_ajax_update'));
194 remove_action('wp_head', array(&$this, 'wpp_print_ajax'));
195 // add update action, no ajax
196 add_action('the_content', array(&$this,'wpp_update') );
197 }
198
199 // add ajax table truncation to wp_ajax_ hook
200 add_action('wp_ajax_wpp_clear_cache', array(&$this, 'wpp_clear_data'));
201 add_action('wp_ajax_wpp_clear_all', array(&$this, 'wpp_clear_data'));
202
203 // activate textdomain for translations
204 add_action('init', array(&$this, 'wpp_textdomain'));
205
206 // activate admin page
207 add_action('admin_menu', array(&$this, 'add_wpp_admin'));
208 // enqueue scripts
209 add_action('admin_enqueue_scripts', array(&$this, 'wpp_admin_enqueue_scripts'));
210 add_action('admin_init', array(&$this, 'wpp_tb_setup') );
211
212 // cache maintenance schedule
213 register_deactivation_hook(__FILE__, array(&$this, 'wpp_deactivation'));
214 add_action('wpp_cache_event', array(&$this, 'wpp_cache_maintenance'));
215 if (!wp_next_scheduled('wpp_cache_event')) {
216 $tomorrow = time() + 86400;
217 $midnight = mktime(0, 0, 0,
218 date("m", $tomorrow),
219 date("d", $tomorrow),
220 date("Y", $tomorrow));
221 wp_schedule_event( $midnight, 'daily', 'wpp_cache_event' );
222 }
223
224 // Wordpress version check
225 if (version_compare($wp_version, '3.3', '<')) add_action('admin_notices', array(&$this, 'wpp_update_warning'));
226
227 // PHP version check
228 if ( version_compare(phpversion(), '5.2.0', '<') ) add_action('admin_notices', array(&$this, 'php_update_warning'));
229
230 // qTrans plugin support
231 if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) $this->qTrans = true;
232
233 // WP-Post Ratings plugin support
234 if (function_exists('the_ratings_results')) $this->postRating = true;
235
236 // Can we create thumbnails?
237 if (extension_loaded('gd') && function_exists('gd_info') && version_compare(phpversion(), '5.2.0', '>=')) $this->thumb = true;
238
239 // shortcode
240 if( function_exists('add_shortcode') ){
241 add_shortcode('wpp', array(&$this, 'wpp_shortcode'));
242 add_shortcode('WPP', array(&$this, 'wpp_shortcode'));
243 }
244
245 // add plugin action link
246 add_filter('plugin_action_links', array(&$this, 'wpp_action_links'), 10, 2);
247 }
248
249 /**
250 * Builds WPP's widget
251 * Since 2.0.0
252 */
253 function widget($args, $instance) {
254 extract($args);
255 //echo $widget_id;
256
257 echo "<!-- Wordpress Popular Posts Plugin v". $this->version ." [W] [".$instance['range']."] [".$instance['order_by']."]". (($instance['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
258
259 echo $before_widget . "\n";
260
261 // has user set a title?
262 if ($instance['title'] != '') {
263
264 $title = apply_filters( 'widget_title', $instance['title'] );
265
266 if ($instance['markup']['custom_html'] && $instance['markup']['title-start'] != "" && $instance['markup']['title-end'] != "" ) {
267 echo htmlspecialchars_decode($instance['markup']['title-start'], ENT_QUOTES) . $title . htmlspecialchars_decode($instance['markup']['title-end'], ENT_QUOTES);
268 } else {
269 echo $before_title . $title . $after_title;
270 }
271 }
272
273 if ( $this->user_ops['tools']['ajax'] ) {
274 ?>
275 <script type="text/javascript">
276 /* <![CDATA[ */
277 jQuery(document).ready(function(){
278 jQuery.get('<?php echo admin_url('admin-ajax.php'); ?>', {action: 'wpp_ajax_get_popular', id: '<?php echo $this->number; ?>'}, function(data){
279 jQuery('#<?php echo $widget_id; ?>').append(data);
280 });
281 });
282 /* ]]> */
283 </script>
284 <?php
285 } else {
286 echo $this->get_popular_posts( $instance );
287 }
288
289 echo $after_widget . "\n";
290 echo "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
291 }
292
293 /**
294 * Updates each widget instance when user clicks the "save" button
295 * Since 2.0.0
296 */
297 function update($new_instance, $old_instance) {
298
299 $instance = $old_instance;
300
301 $instance['title'] = ($this->magicquotes) ? htmlspecialchars( stripslashes(strip_tags( $new_instance['title'] )), ENT_QUOTES ) : htmlspecialchars( strip_tags( $new_instance['title'] ), ENT_QUOTES );
302 $instance['limit'] = is_numeric($new_instance['limit']) ? $new_instance['limit'] : 10;
303 $instance['range'] = $new_instance['range'];
304 $instance['order_by'] = $new_instance['order_by'];
305
306 // FILTERS
307 if ($new_instance['post_type'] == "") { // user did not define the custom post type name, so we fall back to default
308 $instance['post_type'] = 'post,page';
309 } else {
310 $instance['post_type'] = $new_instance['post_type'];
311 }
312
313 $instance['pid'] = implode(",", array_filter(explode(",", preg_replace( '|[^0-9,]|', '', $new_instance['pid'] ))));
314
315 $instance['cat'] = implode(",", array_filter(explode(",", preg_replace( '|[^0-9,-]|', '', $new_instance['cat'] ))));
316 $instance['author'] = implode(",", array_filter(explode(",", preg_replace( '|[^0-9,]|', '', $new_instance['uid'] ))));
317
318 $instance['shorten_title']['active'] = (bool) $new_instance['shorten_title-active'];
319 $instance['shorten_title']['length'] = is_numeric($new_instance['shorten_title-length']) ? $new_instance['shorten_title-length'] : 25;
320 $instance['shorten_title']['words'] = $new_instance['shorten_title-words'];
321 $instance['post-excerpt']['active'] = (bool) $new_instance['post-excerpt-active'];
322 $instance['post-excerpt']['length'] = is_numeric($new_instance['post-excerpt-length']) ? $new_instance['post-excerpt-length'] : 55;
323 $instance['post-excerpt']['keep_format'] = $new_instance['post-excerpt-format'];
324 $instance['post-excerpt']['words'] = $new_instance['post-excerpt-words'];
325
326 if ($this->thumb) { // can create thumbnails
327 $instance['thumbnail']['active'] = (bool) $new_instance['thumbnail-active'];
328
329 if (is_numeric($new_instance['thumbnail-width']) && is_numeric($new_instance['thumbnail-height'])) {
330 $instance['thumbnail']['width'] = $new_instance['thumbnail-width'];
331 $instance['thumbnail']['height'] = $new_instance['thumbnail-height'];
332 } else {
333 $instance['thumbnail']['width'] = 15;
334 $instance['thumbnail']['height'] = 15;
335 }
336
337 } else { // cannot create thumbnails
338 $instance['thumbnail']['active'] = false;
339 $instance['thumbnail']['width'] = 15;
340 $instance['thumbnail']['height'] = 15;
341 }
342
343 if ( isset($instance['thumbnail']['thumb_selection']) )
344 unset( $instance['thumbnail']['thumb_selection'] );
345
346 $instance['rating'] = (bool) $new_instance['rating'];
347 $instance['stats_tag']['comment_count'] = (bool) $new_instance['comment_count'];
348 $instance['stats_tag']['views'] = (bool) $new_instance['views'];
349 $instance['stats_tag']['author'] = (bool) $new_instance['author'];
350 $instance['stats_tag']['date']['active'] = (bool) $new_instance['date'];
351 $instance['stats_tag']['date']['format'] = empty($new_instance['date_format']) ? 'F j, Y' : $new_instance['date_format'];
352 $instance['stats_tag']['category'] = (bool) $new_instance['category'];
353 $instance['markup']['custom_html'] = $new_instance['custom_html'];
354 $instance['markup']['wpp-start'] = empty($new_instance['wpp-start']) ? '&lt;ul&gt;' : htmlspecialchars( $new_instance['wpp-start'], ENT_QUOTES );
355 $instance['markup']['wpp-end'] = empty($new_instance['wpp-end']) ? '&lt;/ul&gt;' : htmlspecialchars( $new_instance['wpp-end'], ENT_QUOTES );
356 $instance['markup']['post-html'] = empty ($new_instance['post-html']) ? '&lt;li&gt;{thumb} {title} {stats}&lt;/li&gt;' : htmlspecialchars( $new_instance['post-html'], ENT_QUOTES );
357 $instance['markup']['post-start'] = empty ($new_instance['post-start']) ? '&lt;li&gt;' : htmlspecialchars( $new_instance['post-start'], ENT_QUOTES );
358 $instance['markup']['post-end'] = empty ($new_instance['post-end']) ? '&lt;/li&gt;' : htmlspecialchars( $new_instance['post-end'], ENT_QUOTES );
359 $instance['markup']['title-start'] = empty($new_instance['title-start']) ? '' : htmlspecialchars( $new_instance['title-start'], ENT_QUOTES );
360 $instance['markup']['title-end'] = empty($new_instance['title-end']) ? '' : htmlspecialchars( $new_instance['title-end'], ENT_QUOTES );
361
362 return $instance;
363 }
364
365 /**
366 * WPP widget's form
367 * Since 2.0.0
368 */
369 function form($instance) {
370
371 // update instance's settings
372 /*echo "<pre>"; print_r($instance); echo "</pre>";*/
373 $instance = $this->array_merge_recursive_distinct($this->defaults, $instance);
374 /*echo "<pre>"; print_r($instance); echo "</pre>";*/
375
376 // form
377 ?>
378 <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small> <br />
379 <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>
380 <p><label for="<?php echo $this->get_field_id( 'limit' ); ?>"><?php _e('Show up to:', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
381 <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>
382 <p><label for="<?php echo $this->get_field_id( 'range' ); ?>"><?php _e('Time Range:', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
383 <select id="<?php echo $this->get_field_id( 'range' ); ?>" name="<?php echo $this->get_field_name( 'range' ); ?>" class="widefat">
384 <option value="daily" <?php if ( 'daily' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 24 hours', 'wordpress-popular-posts'); ?></option>
385 <option value="weekly" <?php if ( 'weekly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 7 days', 'wordpress-popular-posts'); ?></option>
386 <option value="monthly" <?php if ( 'monthly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 30 days', 'wordpress-popular-posts'); ?></option>
387 <option value="all" <?php if ( 'all' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('All-time', 'wordpress-popular-posts'); ?></option>
388 </select>
389 </p>
390 <p><label for="<?php echo $this->get_field_id( 'order_by' ); ?>"><?php _e('Sort posts by:', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small> <br />
391 <select id="<?php echo $this->get_field_id( 'order_by' ); ?>" name="<?php echo $this->get_field_name( 'order_by' ); ?>" class="widefat">
392 <option value="comments" <?php if ( 'comments' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Comments', 'wordpress-popular-posts'); ?></option>
393 <option value="views" <?php if ( 'views' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Total views', 'wordpress-popular-posts'); ?></option>
394 <option value="avg" <?php if ( 'avg' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Avg. daily views', 'wordpress-popular-posts'); ?></option>
395 </select>
396 </p>
397
398 <fieldset style="width:214px; padding:5px;" class="widefat">
399 <legend><?php _e('Posts settings', 'wordpress-popular-posts'); ?></legend>
400 <div style="display:<?php if ($this->postRating) : ?>block<?php else: ?>none<?php endif; ?>">
401 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
402 </div>
403 <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', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
404 <div style="display:<?php if ($instance['shorten_title']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
405 <br />
406 <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" /></label><br />
407 <label for="<?php echo $this->get_field_id( 'shorten_title-words' ); ?>"><input type="radio" name="<?php echo $this->get_field_name( 'shorten_title-words' ); ?>" value="0" <?php echo (!isset($instance['shorten_title']['words']) || !$instance['shorten_title']['words']) ? 'checked="checked"' : ''; ?> /> <?php _e('characters', 'wordpress-popular-posts'); ?></label><br />
408 <label for="<?php echo $this->get_field_id( 'shorten_title-words' ); ?>"><input type="radio" name="<?php echo $this->get_field_name( 'shorten_title-words' ); ?>" value="1" <?php echo (isset($instance['shorten_title']['words']) && $instance['shorten_title']['words']) ? 'checked="checked"' : ''; ?> /> <?php _e('words', 'wordpress-popular-posts'); ?></label><br /><br />
409 </div>
410 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
411 <div style="display:<?php if ($instance['post-excerpt']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
412 <fieldset class="widefat">
413 <legend><?php _e('Excerpt Properties', 'wordpress-popular-posts'); ?></legend><br />
414 &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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br /><br />
415 &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:50px!important" /></label><br />
416
417 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'post-excerpt-words' ); ?>"><input type="radio" name="<?php echo $this->get_field_name( 'post-excerpt-words' ); ?>" value="0" <?php echo (!isset($instance['post-excerpt']['words']) || !$instance['post-excerpt']['words']) ? 'checked="checked"' : ''; ?> /> <?php _e('characters', 'wordpress-popular-posts'); ?></label><br />
418 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'post-excerpt-words' ); ?>"><input type="radio" name="<?php echo $this->get_field_name( 'post-excerpt-words' ); ?>" value="1" <?php echo (isset($instance['post-excerpt']['words']) && $instance['post-excerpt']['words']) ? 'checked="checked"' : ''; ?> /> <?php _e('words', 'wordpress-popular-posts'); ?></label><br /><br />
419
420 </fieldset>
421 <br />
422 </div>
423 </fieldset>
424 <br />
425
426 <fieldset class="widefat">
427 <legend><?php _e('Filters:', 'wordpress-popular-posts'); ?> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small></legend><br />
428 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'post_type' ); ?>"><?php _e('Post type(s):', 'wordpress-popular-posts'); ?></label><br />
429 &nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'post_type' ); ?>" name="<?php echo $this->get_field_name( 'post_type' ); ?>" value="<?php echo $instance['post_type']; ?>" class="widefat" style="width:150px" /><br /><br />
430 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'pid' ); ?>"><?php _e('Post(s) ID(s) to exclude:', 'wordpress-popular-posts'); ?></label><br />
431 &nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'pid' ); ?>" name="<?php echo $this->get_field_name( 'pid' ); ?>" value="<?php echo $instance['pid']; ?>" class="widefat" style="width:150px" /><br /><br />
432 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'cat' ); ?>"><?php _e('Category(ies) ID(s):', 'wordpress-popular-posts'); ?></label><br />
433 &nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'cat' ); ?>" name="<?php echo $this->get_field_name( 'cat' ); ?>" value="<?php echo $instance['cat']; ?>" class="widefat" style="width:150px" /><br /><br />
434 &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'uid' ); ?>"><?php _e('Author(s) ID(s):', 'wordpress-popular-posts'); ?></label><br />
435 &nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'uid' ); ?>" name="<?php echo $this->get_field_name( 'uid' ); ?>" value="<?php echo $instance['author']; ?>" class="widefat" style="width:150px" /><br /><br />
436 </fieldset>
437 <br />
438
439 <fieldset style="width:214px; padding:5px;" class="widefat">
440 <legend><?php _e('Thumbnail settings', 'wordpress-popular-posts'); ?></legend>
441 <input type="checkbox" class="checkbox" <?php echo ($instance['thumbnail']['active'] && $this->thumb) ? '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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
442 <div style="display:<?php if ($instance['thumbnail']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
443 <label for="<?php echo $this->get_field_id( 'thumbnail-width' ); ?>"><?php _e('Width:', 'wordpress-popular-posts'); ?></label>
444 <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 />
445 <label for="<?php echo $this->get_field_id( 'thumbnail-height' ); ?>"><?php _e('Height:', 'wordpress-popular-posts'); ?></label>
446 <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 />
447 </div>
448 </fieldset>
449
450 <br />
451 <fieldset style="width:214px; padding:5px;" class="widefat">
452 <legend><?php _e('Stats Tag settings', 'wordpress-popular-posts'); ?></legend>
453 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
454 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
455 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
456 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small>
457 <div style="display:<?php if ($instance['stats_tag']['date']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
458 <fieldset class="widefat">
459 <legend><?php _e('Date Format', 'wordpress-popular-posts'); ?></legend>
460 <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 />
461 <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 />
462 <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 />
463 <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 />
464 </fieldset>
465 </div>
466 <br /><input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['category']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'category' ); ?>" name="<?php echo $this->get_field_name( 'category' ); ?>" /> <label for="<?php echo $this->get_field_id( 'category' ); ?>"><?php _e('Display category', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
467 </fieldset>
468 <br />
469
470 <fieldset style="width:214px; padding:5px;" class="widefat">
471 <legend><?php _e('HTML Markup settings', 'wordpress-popular-posts'); ?></legend>
472 <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('wpurl'); ?>/wp-admin/options-general.php?page=wpp_admin" title="<?php _e('What is this?', 'wordpress-popular-posts'); ?>">?</a>]</small><br />
473 <div style="display:<?php if ($instance['markup']['custom_html']) : ?>block<?php else: ?>none<?php endif; ?>">
474 <br />
475 <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 />
476 <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>
477 <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 />
478 <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>
479
480 <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'post-html' ); ?>"><?php _e('Post HTML Markup:', 'wordpress-popular-posts'); ?></label> <br />
481 <textarea class="widefat" rows="10" id="<?php echo $this->get_field_id( 'post-html' ); ?>" name="<?php echo $this->get_field_name( 'post-html' ); ?>"><?php echo $instance['markup']['post-html']; ?></textarea>
482 </div>
483 </fieldset>
484 <?php
485 }
486
487 /**
488 * RRR Added to get local time as per WP settings
489 * Since 2.1.6
490 */
491 function curdate() {
492 return gmdate( 'Y-m-d', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ));
493 }
494
495 function now() {
496 return current_time('mysql');
497 }
498
499 /**
500 * Calculates script execution time
501 * Since 2.3.0
502 */
503 function microtime_float() {
504 list( $msec, $sec ) = explode( ' ', microtime() );
505 $microtime = (float) $msec + (float) $sec;
506 return $microtime;
507 }
508
509 /**
510 * Updates popular posts data table via AJAX on post/page view
511 * Since 2.0.0
512 */
513 function wpp_ajax_update() {
514 $nonce = $_POST['token'];
515
516 // is this a valid request?
517 if ( !wp_verify_nonce($nonce, 'wpp-token') ) die("Invalid token");
518
519 if (is_numeric($_POST['id']) && (intval($_POST['id']) == floatval($_POST['id'])) && ($_POST['id'] != '')) {
520 $id = $_POST['id'];
521 } else {
522 die("Invalid ID");
523 }
524
525 // if we got an ID, let's update the data table
526 global $wpdb;
527
528 $wpdb->show_errors();
529
530 $table = $wpdb->prefix . 'popularpostsdata';
531 $exec_time = 0;
532
533
534 // update popularpostsdata table
535 $start = $this->microtime_float();
536 $result = $wpdb->query("INSERT INTO {$table} (postid, day, last_viewed) VALUES ({$id}, '{$this->now()}', '{$this->now()}') ON DUPLICATE KEY UPDATE last_viewed = '{$this->now()}', pageviews = pageviews + 1;");
537 $end = $this->microtime_float();
538
539 $exec_time += round($end - $start, 6);
540
541 // update popularpostsdatacache table
542 $start = $this->microtime_float();
543
544 $result2 = $wpdb->query("INSERT INTO {$table}cache (id, day, day_no_time) VALUES ({$id}, '{$this->now()}', '{$this->curdate()}') ON DUPLICATE KEY UPDATE pageviews = pageviews + 1, day = '{$this->now()}', day_no_time = '{$this->curdate()}';");
545
546 $exec_time += round($end - $start, 6);
547
548 if ($result && $result2) {
549 die( "OK. Execution time: " . $exec_time . " seconds" );
550 } else {
551 die( "Oops: " . $wpdb->print_error() );
552 }
553 }
554
555 /**
556 * Updates popular posts data table on post/page view
557 * Since 2.3.0
558 */
559 function wpp_update($content) {
560
561 //if ( (is_single() || is_page()) && !is_user_logged_in() && !is_front_page() ) {
562 if ( (is_single() || is_page()) && !is_front_page() && !is_preview() ) {
563
564 if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 0 && is_user_logged_in() )
565 return $content;
566
567 global $wpdb, $post;
568
569 $table = $wpdb->prefix . 'popularpostsdata';
570 $result = $wpdb->query("INSERT INTO {$table} (postid, day, last_viewed) VALUES ({$post->ID}, '{$this->now()}', '{$this->now()}') ON DUPLICATE KEY UPDATE last_viewed = '{$this->now()}', pageviews = pageviews + 1;");
571 $result2 = $wpdb->query("INSERT INTO {$table}cache (id, day, day_no_time) VALUES ({$post->ID}, '{$this->now()}', '{$this->curdate()}') ON DUPLICATE KEY UPDATE pageviews = pageviews + 1, day = '{$this->now()}', day_no_time = '{$this->curdate()}';");
572
573 if (!$result || !$result2) {
574 print_r( $wpdb->print_error() );
575 }
576
577 }
578
579 return $content;
580
581 }
582
583 /**
584 * Builds list via AJAX
585 * Since 2.3.3
586 */
587 function ajax_getpopular() {
588
589 if ( is_numeric($_GET['id']) && (intval($_GET['id']) == floatval($_GET['id'])) && ($_GET['id'] != '') ) {
590 $id = $_GET['id'];
591 } else {
592 die("Invalid ID");
593 }
594
595 $settings = $this->get_settings();
596
597 if ( isset($settings[$id]) ) {
598
599 $instance = $settings[$id];
600 echo $this->get_popular_posts( $instance );
601
602 } else {
603
604 echo "Invalid Widget ID";
605
606 }
607
608 die();
609
610 }
611
612 /**
613 * Clears WPP datacache table
614 * Since 2.0.0
615 */
616 function wpp_clear_data() {
617 $token = $_POST['token'];
618 $clear = isset($_POST['clear']) ? $_POST['clear'] : '';
619 $key = get_option("wpp_rand");
620
621 if (current_user_can('manage_options') && ($token === $key) && !empty($clear)) {
622 global $wpdb;
623 // set table name
624 $table = $wpdb->prefix . "popularpostsdata";
625 $cache = $wpdb->prefix . "popularpostsdatacache";
626
627 if ($clear == 'cache') {
628 if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
629 $wpdb->query("TRUNCATE TABLE $cache;");
630 _e('Success! The cache table has been cleared!', 'wordpress-popular-posts');
631 } else {
632 _e('Error: cache table does not exist.', 'wordpress-popular-posts');
633 }
634 } else if ($clear == 'all') {
635 if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") == $table && $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
636 $wpdb->query("TRUNCATE TABLE $table;");
637 $wpdb->query("TRUNCATE TABLE $cache;");
638 _e('Success! All data have been cleared!', 'wordpress-popular-posts');
639 } else {
640 _e('Error: one or both data tables are missing.', 'wordpress-popular-posts');
641 }
642 } else {
643 _e('Invalid action.', 'wordpress-popular-posts');
644 }
645 } else {
646 _e('Sorry, you do not have enough permissions to do this. Please contact the site administrator for support.', 'wordpress-popular-posts');
647 }
648
649 die();
650 }
651
652 /**
653 * Installs WPP DB tables
654 * Since 2.0.0
655 */
656 function wpp_install() {
657 global $wpdb;
658
659 $wpdb->show_errors();
660
661 $sql = "";
662 $charset_collate = "";
663
664 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
665
666 if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
667 if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate";
668
669 // set table name
670 $table = $wpdb->prefix . "popularpostsdata";
671
672 // does popularpostsdata table exists?
673 if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") != $table ) { // fresh setup
674 $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 compositeID (id, day_no_time), id int(10) NOT NULL, day datetime NOT NULL default '0000-00-00 00:00:00', day_no_time date NOT NULL default '0000-00-00', pageviews int(10) default 1 ) $charset_collate;";
675 } else {
676
677 // check if cahe table is missing
678 $cache = $table . "cache";
679
680 if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") != $cache ) {
681 $sql = "CREATE TABLE $cache ( UNIQUE KEY compositeID (id, day_no_time), id int(10) NOT NULL, day datetime NOT NULL default '0000-00-00 00:00:00', day_no_time date NOT NULL default '0000-00-00', pageviews int(10) default 1 ) $charset_collate;";
682 } else { // check if any column is missing
683
684 // get table columns
685 $cacheFields = $wpdb->get_results("SHOW FIELDS FROM $cache", ARRAY_A);
686
687 $alter_day = true;
688 $add_daynotime = true;
689
690 foreach ($cacheFields as $column) {
691 // check if day column is type datetime
692 if ($column['Field'] == 'day') {
693 if ($column['Type'] == 'datetime') {
694 $alter_day = false;
695 }
696 }
697
698 // check if day_no_time field exists
699 if ($column['Field'] == 'day_no_time') {
700 $add_daynotime = false;
701 }
702 }
703
704 if ($alter_day) { // day column is not datimetime, so change it
705 $wpdb->query("ALTER TABLE $cache CHANGE day day datetime NOT NULL default '0000-00-00 00:00:00';");
706 }
707
708 if ($add_daynotime) { // day_no_time column is missing, add it
709 $wpdb->query("ALTER TABLE $cache ADD day_no_time date NOT NULL default '0000-00-00';");
710 $wpdb->query("UPDATE $cache SET day_no_time = day;");
711 }
712
713 $cacheIndex = $wpdb->get_results("SHOW INDEX FROM $cache", ARRAY_A);
714 if ($cacheIndex[0]['Key_name'] == "id") { // if index is id-day change to id-day_no_time
715 $wpdb->query("ALTER TABLE $cache DROP INDEX id, ADD UNIQUE KEY compositeID (id, day_no_time);");
716 }
717
718 }
719 }
720
721 dbDelta($sql);
722 }
723
724 /**
725 * Checks for stuff that needs updating on plugin upgrade
726 * Since 2.3.1
727 */
728 function wpp_upgrade() {
729
730 update_option('wpp_ver', $this->version); // update wpp version in db
731
732 // update user options
733 $this->user_ops = $this->array_merge_recursive_distinct( $this->wpp_user_settings_def, $this->user_ops );
734 update_option('wpp_settings_config', $this->user_ops);
735
736 global $wpdb;
737 $wpdb->show_errors();
738
739 $sql = "";
740 $charset_collate = "";
741
742 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
743
744 if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
745 if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate";
746
747 // set table name
748 $data = $wpdb->prefix . "popularpostsdata";
749 $cache = $data . "cache";
750
751 // if the cache table is missing, create it
752 if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") != $cache ) {
753 $sql = "CREATE TABLE $cache ( UNIQUE KEY compositeID (id, day_no_time), id int(10) NOT NULL, day datetime NOT NULL default '0000-00-00 00:00:00', day_no_time date NOT NULL default '0000-00-00', pageviews int(10) default 1 ) $charset_collate;";
754 } else { // check if any column is missing
755
756 // get table columns
757 $cacheFields = $wpdb->get_results("SHOW FIELDS FROM $cache", ARRAY_A);
758
759 $alter_day = true;
760 $add_daynotime = true;
761
762 foreach ($cacheFields as $column) {
763 // check if day column is type datetime
764 if ($column['Field'] == 'day') {
765 if ($column['Type'] == 'datetime') {
766 $alter_day = false;
767 }
768 }
769
770 // check if day_no_time field exists
771 if ($column['Field'] == 'day_no_time') {
772 $add_daynotime = false;
773 }
774 }
775
776 if ($alter_day) { // day column is not datimetime, so change it
777 $wpdb->query("ALTER TABLE $cache CHANGE day day datetime NOT NULL default '0000-00-00 00:00:00';");
778 }
779
780 if ($add_daynotime) { // day_no_time column is missing, add it
781 $wpdb->query("ALTER TABLE $cache ADD day_no_time date NOT NULL default '0000-00-00';");
782 $wpdb->query("UPDATE $cache SET day_no_time = day;");
783 }
784
785 $cacheIndex = $wpdb->get_results("SHOW INDEX FROM $cache", ARRAY_A);
786 if ($cacheIndex[0]['Key_name'] == "id") { // if index is id-day change to id-day_no_time
787 $wpdb->query("ALTER TABLE $cache DROP INDEX id, ADD UNIQUE KEY compositeID (id, day_no_time);");
788 }
789 }
790
791 dbDelta($sql);
792
793 }
794
795 /**
796 * Prints AJAX script to wp_head()
797 * Since 2.0.0
798 */
799 function wpp_print_ajax() {
800
801 wp_print_scripts('jquery');
802
803 // if we're on a page or post, load the script
804 if ( (is_single() || is_page()) && !is_front_page() && !is_preview() ) {
805
806 if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 0 && is_user_logged_in() )
807 return;
808
809 // create security token
810 $nonce = wp_create_nonce('wpp-token');
811
812 // get current post's ID
813 global $wp_query;
814 wp_reset_query();
815
816 $id = $wp_query->post->ID;
817 ?>
818 <!-- Wordpress Popular Posts v<?php echo $this->version; ?> -->
819 <script type="text/javascript">
820 /* <![CDATA[ */
821 jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {action: 'wpp_update', token: '<?php echo $nonce; ?>', id: <?php echo $id; ?>}, function(data){/*alert(data);*/});
822 /* ]]> */
823 </script>
824 <!-- End Wordpress Popular Posts v<?php echo $this->version; ?> -->
825 <?php
826 }
827 }
828
829 /**
830 * Builds popular posts list
831 * Since 1.4.0
832 */
833 function get_popular_posts($instance, $return = false) {
834
835 // update instance's settings
836 /*echo "<pre>"; print_r($instance); echo "</pre>";*/
837 $instance = $this->array_merge_recursive_distinct($this->defaults, $instance);
838 /*echo "<pre>"; print_r($instance); echo "</pre>";*/
839
840 global $wpdb;
841 $table = $wpdb->prefix . "popularpostsdata";
842 $fields = "";
843 $from = "";
844 $where = "";
845 $post_types = "";
846 $pids = "";
847 $cats = "";
848 $authors = "";
849 $content = "";
850
851 // post filters
852 // * post types - based on code seen at https://github.com/williamsba/WordPress-Popular-Posts-with-Custom-Post-Type-Support
853 $types = explode(",", $instance['post_type']);
854 $i = 0;
855 $len = count($types);
856 $sql_post_types = "";
857 $join_cats = true;
858
859 if ($len > 1) { // we are getting posts from more that one ctp
860 foreach ( $types as $post_type ) {
861 $sql_post_types .= "'" .$post_type. "'";
862
863 if ($i != $len - 1) $sql_post_types .= ",";
864
865 $i++;
866 }
867
868 $post_types = " p.post_type IN({$sql_post_types}) ";
869 } else if ($len == 1) { // post from one ctp only
870
871 $post_types = " p.post_type = '".$instance['post_type']."' ";
872
873 // if we're getting just pages, why join the categories table?
874 if ( strtolower($instance['post_type']) == 'page' )
875 $join_cats = false;
876
877 }
878
879 // * posts exclusion
880 if ( !empty($instance['pid']) ) {
881 $ath = explode(",", $instance['pid']);
882 $len = count($ath);
883
884 if ($len > 1) { // we are excluding more than one post
885 $pids = " AND p.ID NOT IN(".$instance['pid'].") ";
886 } else if ($len == 1) { // exclude one post only
887 $pids = " AND p.ID <> '".$instance['pid']."' ";
888 }
889 }
890
891 // * categories
892 if ( !empty($instance['cat']) && $join_cats ) {
893 $cat_ids = explode(",", $instance['cat']);
894 $in = array();
895 $out = array();
896 $not_in = "";
897
898 usort($cat_ids, array(&$this, 'sorter'));
899
900 for ($i=0; $i < count($cat_ids); $i++) {
901 if ($cat_ids[$i] >= 0) $in[] = $cat_ids[$i];
902 if ($cat_ids[$i] < 0) $out[] = $cat_ids[$i];
903 }
904
905 $in_cats = implode(",", $in);
906 $out_cats = implode(",", $out);
907 $out_cats = preg_replace( '|[^0-9,]|', '', $out_cats );
908
909 if ($in_cats != "" && $out_cats == "") { // get posts from from given cats only
910 $cats = " AND p.ID IN (
911 SELECT object_id
912 FROM $wpdb->term_relationships AS r
913 JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
914 JOIN $wpdb->terms AS t ON t.term_id = x.term_id
915 WHERE x.taxonomy = 'category' AND t.term_id IN($in_cats)
916 ) ";
917 } else if ($in_cats == "" && $out_cats != "") { // exclude posts from given cats only
918 $cats = " AND p.ID NOT IN (
919 SELECT object_id
920 FROM $wpdb->term_relationships AS r
921 JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
922 JOIN $wpdb->terms AS t ON t.term_id = x.term_id
923 WHERE x.taxonomy = 'category' AND t.term_id IN($out_cats)
924 ) ";
925 } else { // mixed, and possibly a heavy load on the DB
926 $cats = " AND p.ID IN (
927 SELECT object_id
928 FROM $wpdb->term_relationships AS r
929 JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
930 JOIN $wpdb->terms AS t ON t.term_id = x.term_id
931 WHERE x.taxonomy = 'category' AND t.term_id IN($in_cats)
932 ) AND p.ID NOT IN (
933 SELECT object_id
934 FROM $wpdb->term_relationships AS r
935 JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
936 JOIN $wpdb->terms AS t ON t.term_id = x.term_id
937 WHERE x.taxonomy = 'category' AND t.term_id IN($out_cats)
938 ) ";
939 }
940 }
941
942 // * authors
943 if ( !empty($instance['author']) ) {
944 $ath = explode(",", $instance['author']);
945 $len = count($ath);
946
947 if ($len > 1) { // we are getting posts from more that one author
948 $authors = " AND p.post_author IN(".$instance['author'].") ";
949 } else if ($len == 1) { // post from one author only
950 $authors = " AND p.post_author = '".$instance['author']."' ";
951 }
952 }
953
954 $fields = "p.ID AS 'id', p.post_title AS 'title', p.post_date AS 'date', p.post_author AS 'uid' ";
955
956 if ($instance['range'] == "all") { // ALL TIME
957
958 $fields .= ", p.comment_count AS 'comment_count' ";
959
960 if ($instance['order_by'] == "comments") { // ordered by comments
961
962 if ($instance['stats_tag']['views']) { // get views, too
963
964 $fields .= ", IFNULL(v.pageviews, 0) AS 'pageviews' ";
965 $from = " {$wpdb->posts} p LEFT JOIN {$table} v ON p.ID = v.postid WHERE {$post_types} {$pids} {$authors} {$cats} AND p.comment_count > 0 AND p.post_password = '' AND p.post_status = 'publish' ORDER BY p.comment_count DESC LIMIT {$instance['limit']} ";
966
967 } else { // get data from wp_posts only
968 $from = " {$wpdb->posts} p WHERE {$post_types} {$pids} {$authors} {$cats} AND p.comment_count > 0 AND p.post_password = '' AND p.post_status = 'publish' ORDER BY p.comment_count DESC LIMIT {$instance['limit']} ";
969 }
970
971 } else { // ordered by views / avg
972
973 if ( $instance['order_by'] == "views" ) {
974
975 $fields .= ", v.pageviews AS 'pageviews' ";
976 $from = " {$table} v LEFT JOIN {$wpdb->posts} p ON v.postid = p.ID WHERE {$post_types} {$pids} {$authors} {$cats} AND p.post_password = '' AND p.post_status = 'publish' ORDER BY pageviews DESC LIMIT {$instance['limit']} ";
977
978 } else if ( $instance['order_by'] == "avg" ) {
979
980 $fields .= ", ( v.pageviews/(IF ( DATEDIFF('{$this->now()}', MIN(v.day)) > 0, DATEDIFF('{$this->now()}', MIN(v.day)), 1) ) ) AS 'avg_views' ";
981 $from = " {$table} v LEFT JOIN {$wpdb->posts} p ON v.postid = p.ID WHERE {$post_types} {$pids} {$authors} {$cats} AND p.post_password = '' AND p.post_status = 'publish' GROUP BY p.ID ORDER BY avg_views DESC LIMIT {$instance['limit']} ";
982
983 }
984
985 }
986
987 } else { // CUSTOM RANGE
988
989 $interval = "";
990
991 switch( $instance['range'] ){
992 case "yesterday":
993 $interval = "1 DAY";
994 break;
995
996 case "daily":
997 $interval = "1 DAY";
998 break;
999
1000 case "weekly":
1001 $interval = "1 WEEK";
1002 break;
1003
1004 case "monthly":
1005 $interval = "1 MONTH";
1006 break;
1007
1008 default:
1009 $interval = "1 DAY";
1010 break;
1011 }
1012
1013 if ($instance['order_by'] == "comments") { // ordered by comments
1014
1015 $fields .= ", c.comment_count AS 'comment_count' ";
1016 $from = " (SELECT comment_post_ID AS 'id', COUNT(comment_post_ID) AS 'comment_count', MAX(comment_date) AS comment_date FROM {$wpdb->comments} WHERE comment_date > DATE_SUB('{$this->now()}', INTERVAL {$interval}) AND comment_approved = 1 GROUP BY id ORDER BY comment_count DESC, comment_date DESC) c LEFT JOIN {$wpdb->posts} p ON p.ID = c.id ";
1017
1018 if ($instance['stats_tag']['views']) { // get views, too
1019
1020 $fields .= ", IFNULL(v.pageviews, 0) AS 'pageviews' ";
1021 $from .= " LEFT JOIN (SELECT id, SUM(pageviews) AS pageviews, MAX(day) AS day FROM {$table}cache WHERE day > DATE_SUB('{$this->now()}', INTERVAL {$interval}) GROUP BY id ORDER BY pageviews DESC, day DESC) v ON p.ID = v.id ";
1022
1023 }
1024
1025 $from .= " WHERE {$post_types} {$pids} {$authors} {$cats} AND p.post_password = '' AND p.post_status = 'publish' LIMIT {$instance['limit']} ";
1026
1027 } else { // ordered by views / avg
1028
1029 if ( $instance['order_by'] == "views" ) {
1030
1031 $fields .= ", v.pageviews AS 'pageviews' ";
1032 $from = " (SELECT id, SUM(pageviews) AS pageviews, MAX(day) AS day FROM {$table}cache WHERE day > DATE_SUB('{$this->now()}', INTERVAL {$interval}) GROUP BY id ORDER BY pageviews DESC, day DESC) v LEFT JOIN {$wpdb->posts} p ON v.id = p.ID ";
1033
1034 } else if ( $instance['order_by'] == "avg" ) {
1035
1036 $fields .= ", ( v.pageviews/(IF ( DATEDIFF('{$this->now()}', DATE_SUB('{$this->now()}', INTERVAL {$interval})) > 0, DATEDIFF('{$this->now()}', DATE_SUB('{$this->now()}', INTERVAL {$interval})), 1) ) ) AS 'avg_views' ";
1037 $from = " (SELECT id, SUM(pageviews) AS pageviews, MAX(day) AS day FROM {$table}cache WHERE day > DATE_SUB('{$this->now()}', INTERVAL {$interval}) GROUP BY id ORDER BY pageviews DESC, day DESC) v LEFT JOIN {$wpdb->posts} p ON v.id = p.ID ";
1038
1039 }
1040
1041 if ( $instance['stats_tag']['comment_count'] ) { // get comments, too
1042
1043 $fields .= ", IFNULL(c.comment_count, 0) AS 'comment_count' ";
1044 $from .= " LEFT JOIN (SELECT comment_post_ID AS 'id', COUNT(comment_post_ID) AS 'comment_count', MAX(comment_date) AS comment_date FROM {$wpdb->comments} WHERE comment_date > DATE_SUB('{$this->now()}', INTERVAL {$interval}) AND comment_approved = 1 GROUP BY id ORDER BY comment_count DESC, comment_date DESC) c ON p.ID = c.id ";
1045
1046 }
1047
1048 $from .= " WHERE {$post_types} {$pids} {$authors} {$cats} AND p.post_password = '' AND p.post_status = 'publish' ";
1049
1050 if ( $instance['order_by'] == "avg" ) {
1051 $from .= " GROUP BY v.id ORDER BY avg_views DESC ";
1052 }
1053
1054 $from .= " LIMIT {$instance['limit']} ";
1055
1056 }
1057
1058 }
1059
1060 $query = "SELECT {$fields} FROM {$from}";
1061 //echo $query;
1062
1063 $mostpopular = $wpdb->get_results($query);
1064 /*echo "<pre>"; print_r($mostpopular); echo "</pre>";*/
1065
1066 // posts array
1067 $posts_data = array();
1068
1069 if ( !is_array($mostpopular) || empty($mostpopular) ) { // no posts to show
1070 $content .= "<p>".__('Sorry. No data so far.', 'wordpress-popular-posts')."</p>"."\n";
1071 } else { // list posts
1072
1073 // HTML wrapper
1074 if ($instance['markup']['custom_html']) {
1075 $content .= htmlspecialchars_decode($instance['markup']['wpp-start'], ENT_QUOTES) ."\n";
1076 } else {
1077 $content .= "<ul class=\"wpp-list\">" . "\n";
1078 }
1079
1080 foreach($mostpopular as $p) {
1081
1082 $stats = "";
1083 $thumb = "";
1084 $title = "";
1085 $title_sub = "";
1086 $permalink = get_permalink( $p->id );
1087 $author = ($instance['stats_tag']['author']) ? get_the_author_meta('display_name', $p->uid) : "";
1088 $date = date_i18n( $instance['stats_tag']['date']['format'], strtotime($p->date) );
1089 $pageviews = ($instance['order_by'] == "views" || $instance['order_by'] == "avg" || $instance['stats_tag']['views']) ? (($instance['order_by'] == "views" || $instance['order_by'] == "comments") ? $p->pageviews : $p->avg_views ) : 0;
1090 $comments = ($instance['order_by'] == "comments" || $instance['stats_tag']['comment_count']) ? $p->comment_count : 0;
1091
1092 $post_cat = "";
1093 $excerpt = "";
1094 $rating = "";
1095 $data = array();
1096
1097 // TITLE
1098 $title = ($this->qTrans) ? qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($p->title) : $p->title;
1099 $title = strip_tags($title);
1100 $title_sub = strip_tags($title);
1101
1102 // truncate title
1103 if ( $instance['shorten_title']['active'] ) {
1104
1105 if ( isset($instance['shorten_title']['words']) && $instance['shorten_title']['words'] ) { // by words
1106
1107 $words = explode(" ", $title, $instance['shorten_title']['length'] + 1);
1108
1109 if ( count($words) > $instance['shorten_title']['length'] ) {
1110
1111 array_pop($words);
1112 $title_sub = implode(" ", $words) . "...";
1113
1114 }
1115
1116 } else { // by characters
1117
1118 if ( strlen($title) > $instance['shorten_title']['length'] ) {
1119 $title_sub = mb_substr($title, 0, $instance['shorten_title']['length'], $this->charset) . "...";
1120 }
1121
1122 }
1123
1124 }
1125
1126 $title = htmlspecialchars( $title, ENT_QUOTES, $this->charset );
1127 $title_sub = htmlspecialchars( $title_sub, ENT_QUOTES, $this->charset );
1128
1129 $title = apply_filters('the_title', $title, $p->id);
1130 $title_sub = apply_filters('the_title', $title_sub, $p->id);
1131
1132 // EXCERPT
1133 if ( $instance['post-excerpt']['active'] ) {
1134
1135 $excerpt = trim( $this->get_summary($p->id, $instance) );
1136
1137 if ( !empty($excerpt) ) {
1138
1139 if ( !$instance['markup']['custom_html'] ) {
1140 $excerpt = ": <span class=\"wpp-excerpt\">" . $excerpt . "</span>";
1141 }
1142
1143 }
1144
1145 }
1146
1147 // STATS
1148 // comments
1149 if ( $instance['stats_tag']['comment_count'] ) {
1150 $comments_text =sprintf(
1151 _n('1 comment', '%s comments', $comments, 'wordpress-popular-posts'),
1152 number_format_i18n($comments));
1153 $stats .= "<span class=\"wpp-comments\">" . $comments_text . "</span>";
1154 } else {
1155 }
1156 // views
1157 if ( $instance['stats_tag']['views'] ) {
1158
1159 if ($instance['order_by'] == 'avg') {
1160 $views_text = sprintf(
1161 _n('1 view per day', '%s views per day', intval($pageviews), 'wordpress-popular-posts'),
1162 number_format_i18n($pageviews, 2)
1163 );
1164 }
1165 else {
1166 $views_text = sprintf(
1167 _n('1 view', '%s views', intval($pageviews), 'wordpress-popular-posts'),
1168 number_format_i18n($pageviews)
1169 );
1170 }
1171
1172 $stats .= ($stats == "") ? "<span class=\"wpp-views\">" . $views_text . "</span>" : " | <span class=\"wpp-views\">" . $views_text . "</span>";
1173
1174 }
1175 //author
1176 if ( $instance['stats_tag']['author'] ) {
1177 $display_name = "<a href=\"".get_author_posts_url($p->uid)."\">{$author}</a>";
1178 $stats .= ($stats == "") ? "<span class=\"wpp-author\">" . __('by', 'wordpress-popular-posts')." {$display_name}</span>" : " | <span class=\"wpp-author\">" . __('by', 'wordpress-popular-posts') . " {$display_name}</span>";
1179 }
1180 // date
1181 if ( $instance['stats_tag']['date']['active'] ) {
1182 $stats .= ($stats == "") ? "<span class=\"wpp-date\">" . __('posted on', 'wordpress-popular-posts')." {$date}</span>" : " | <span class=\"wpp-date\">" . __('posted on', 'wordpress-popular-posts') . " {$date}</span>";
1183 }
1184 // category
1185 if ( $instance['stats_tag']['category'] ) {
1186 $post_cat = get_the_category( $p->id );
1187 $post_cat = ( isset($post_cat[0]) ) ? '<a href="'.get_category_link($post_cat[0]->term_id ).'">'.$post_cat[0]->cat_name.'</a>' : '';
1188
1189 if ( $post_cat != '' ) {
1190 $stats .= ($stats == "") ? "<span class=\"wpp-category\">" . __('under', 'wordpress-popular-posts'). " {$post_cat}</span>" : " | <span class=\"wpp-category\">" . __('under', 'wordpress-popular-posts') . " {$post_cat}</span>";
1191 }
1192 }
1193
1194 // RATING
1195 if ( $instance['rating'] && $this->postRating && function_exists('the_ratings') ) {
1196 $rating = '<span class="wpp-rating">'.the_ratings( 'span', $p->id, false ).'</span>';
1197 }
1198
1199 // POST THUMBNAIL
1200 if ($instance['thumbnail']['active'] && $this->thumb) {
1201
1202 $tbWidth = $instance['thumbnail']['width'];
1203 $tbHeight = $instance['thumbnail']['height'];
1204
1205 $thumb = "<a href=\"". $permalink ."\" title=\"{$title}\" target=\"".$this->user_ops['tools']['link']['target']."\">";
1206
1207 if ( $this->user_ops['tools']['thumbnail']['source'] == "custom_field" ) { // get image from custom field
1208
1209 $path = get_post_meta($p->id, $this->user_ops['tools']['thumbnail']['field'], true);
1210
1211 if ( $path != "" ) {
1212
1213 if ( $this->user_ops['tools']['thumbnail']['resize'] ) {
1214
1215 $thumb .= $this->get_img( $p->id, array($tbWidth, $tbHeight), $this->user_ops['tools']['thumbnail']['source'] );
1216
1217 } else {
1218 $thumb .= "<img src=\"{$path}\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" alt=\"{$title}\" border=\"0\" class=\"wpp-thumbnail wpp_cf\" />";
1219 }
1220
1221 } else {
1222 $thumb .= "<img src=\"". $this->default_thumbnail ."\" alt=\"{$title}\" border=\"0\" width=\"{$tbWidth}\" height=\"{$tbHeight}\" class=\"wpp-thumbnail wpp_cf_def\" />";
1223 }
1224
1225 } else { // get image from post / Featured Image
1226 $thumb .= $this->get_img( $p->id, array($tbWidth, $tbHeight), $this->user_ops['tools']['thumbnail']['source'] );
1227 }
1228
1229 $thumb .= "</a>";
1230 }
1231
1232 $data = array(
1233 'id' => $p->id,
1234 'title' => '<a href="'.$permalink.'" title="'.$title.'">'.$title_sub.'</a>',
1235 'summary' => $excerpt,
1236 'stats' => $stats,
1237 'img' => $thumb,
1238 'url' => $permalink,
1239 'text_title' => $title,
1240 'category' => $post_cat,
1241 'author' => "<a href=\"".get_author_posts_url($p->uid)."\">{$author}</a>",
1242 'views' => $pageviews,
1243 'comments' => $comments
1244 );
1245
1246 $posts_data[] = (object) $data;
1247
1248 // PUTTING IT ALL TOGETHER
1249 if ($instance['markup']['custom_html']) { // build custom layout
1250
1251 $content .= htmlspecialchars_decode( $this->format_content($instance['markup']['post-html'], $data, $instance['rating']), ENT_QUOTES ) . "\n";
1252
1253 } else { // build regular layout
1254 $content .= "<li>{$thumb}<a href=\"{$permalink}\" title=\"{$title}\" class=\"wpp-post-title\" target=\"".$this->user_ops['tools']['link']['target']."\">{$title_sub}</a> {$excerpt}<span class=\"post-stats\">{$stats}</span>{$rating}</li>" . "\n";
1255 }
1256 }
1257
1258 // END HTML wrapper
1259 if ($instance['markup']['custom_html']) {
1260 $content .= htmlspecialchars_decode($instance['markup']['wpp-end'], ENT_QUOTES) ."\n";
1261 } else {
1262 $content .= "\n"."</ul>"."\n";
1263 }
1264 }
1265
1266 //return $content;
1267 return apply_filters( 'wpp_html', $content, $posts_data );
1268 die();
1269
1270 }
1271
1272 /**
1273 * Builds post's excerpt
1274 * Since 1.4.6
1275 */
1276 function get_summary($id, $instance){
1277
1278 if ( !is_numeric($id) )
1279 return false;
1280
1281 global $wpdb;
1282
1283 $excerpt = "";
1284 $the_post = get_post( $id );
1285 $excerpt = ( $the_post->post_excerpt == "" ) ? $the_post->post_content : $the_post->post_excerpt;
1286
1287 // RRR added call to the_content filters, allows qTranslate to hook in.
1288 if ( $this->qTrans )
1289 $excerpt = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage( $excerpt );
1290
1291 // remove WP shortcodes (and HTML tags if requested)
1292 if ( $instance['post-excerpt']['keep_format'] ) {
1293 $excerpt = strip_shortcodes( strip_tags($excerpt, '<a><b><i><em><strong>') );
1294 } else {
1295 $excerpt = strip_shortcodes( strip_tags($excerpt) );
1296 }
1297
1298 // remove caption tags
1299 $excerpt = preg_replace( "/\[caption.*\[\/caption\]/", "", $excerpt );
1300
1301 // remove Flash objects
1302 $excerpt = preg_replace( "/<object[0-9 a-z_?*=\":\-\/\.#\,\\n\\r\\t]+/smi", "", $excerpt );
1303
1304 // remove Iframes
1305 $excerpt = preg_replace( "/<iframe.*?\/iframe>/i", "", $excerpt);
1306
1307 // remove URLs
1308 $excerpt = preg_replace( '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS', '', $excerpt );
1309
1310 // do we still have something to display?
1311 if ( !empty($excerpt) ) {
1312
1313 // truncate excerpt
1314 if ( isset($instance['post-excerpt']['words']) && $instance['post-excerpt']['words'] ) { // by words
1315
1316 $words = explode(" ", $excerpt, $instance['post-excerpt']['length'] + 1);
1317
1318 if ( count($words) > $instance['post-excerpt']['length'] ) {
1319
1320 array_pop($words);
1321 $excerpt = implode(" ", $words) . "...";
1322
1323 }
1324
1325 } else { // by characters
1326
1327 if ( strlen($excerpt) > $instance['post-excerpt']['length'] ) {
1328 $excerpt = mb_substr( $excerpt, 0, $instance['post-excerpt']['length'] ) . "...";
1329 }
1330
1331 }
1332
1333 }
1334
1335 // remove HTML tags if requested
1336 if ( $instance['post-excerpt']['keep_format'] ) {
1337 $excerpt = force_balance_tags(strip_tags($excerpt, '<a><b><i><em><strong>'));
1338 } else {
1339 $excerpt = strip_tags($excerpt);
1340 }
1341
1342 // remove WP shortcodes
1343 $excerpt = strip_shortcodes( $excerpt );
1344
1345 return $excerpt;
1346
1347 }
1348
1349 /**
1350 * Retrieves post's image
1351 * Since 1.4.6
1352 * Last modified: 2.3.3
1353 * Borrowed some ideas from Victor Teixeira's VT function http://core.trac.wordpress.org/ticket/15311
1354 * and added a check for the WP_Image_Editor Class
1355 */
1356 function get_img( $id = NULL, $dim = array(80, 80), $source = "featured" ) {
1357
1358 if ( !$id || empty($id) || !is_numeric($id) )
1359 return "<img src=\"". $this->default_thumbnail ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_def_noID\" />";
1360
1361 $file_path = '';
1362
1363 if ( $source == "featured" ) { // get thumbnail path from the Featured Image
1364
1365 $thumbnail_id = get_post_thumbnail_id( $id ); // thumb attachment ID
1366
1367 if ( $thumbnail_id ) {
1368
1369 $thumbnail = wp_get_attachment_image_src( $thumbnail_id, 'full' ); // full size image
1370 $file_path = get_attached_file( $thumbnail_id ); // image path
1371
1372 }
1373
1374 } else if ( $source == "first_image" ) { // get thumbnail path from post content
1375
1376 global $wpdb;
1377
1378 $content = $wpdb->get_var( "SELECT post_content FROM $wpdb->posts WHERE ID = {$id}" );
1379 $count = substr_count($content, '<img');
1380
1381 if ($count > 0) { // images have been found
1382
1383 $output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $ContentImages );
1384
1385 if ( isset($ContentImages[1][0]) ) {
1386
1387 $image_url = esc_url( $ContentImages[1][0] ); // sanitize URL, just in case
1388 preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $image_url, $matches); // remove querystring
1389 $image_url = $matches[0];
1390
1391 $attachment_id = $this->wpp_get_attachment_id( $image_url );
1392
1393 if ( $attachment_id ) { // image comes from Media library
1394
1395 $thumbnail[0] = $image_url;
1396 $file_path = get_attached_file( $attachment_id );
1397
1398 } else { // image not found in Media library, maybe external image?
1399
1400 $result = $this->download_image( $image_url, $id );
1401
1402 if ( is_array($result) && !empty($result) ) {
1403
1404 $thumbnail[0] = $result[0];
1405 $file_path = $result[1];
1406
1407 }
1408
1409 }
1410
1411 }
1412
1413 }
1414
1415 } else if ( $source == "custom_field" ) { // get thumbnail path from custom field
1416
1417 $image_url = get_post_meta($id, $this->user_ops['tools']['thumbnail']['field'], true);
1418 $image_url = esc_url( $image_url ); // sanitize URL, just in case
1419 preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $image_url, $matches); // remove querystring
1420 $image_url = $matches[0];
1421
1422 $result = $this->download_image( $image_url, $id );
1423
1424 if ( is_array($result) && !empty($result) ) {
1425
1426 $thumbnail[0] = $result[0];
1427 $file_path = $result[1];
1428
1429 }
1430
1431 }
1432
1433 if ( $file_path == '' ) {
1434 return "<img src=\"". $this->default_thumbnail ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_def_noPath wpp_{$source}\" />";
1435 }
1436
1437 $file_info = pathinfo( $file_path );
1438 $extension = '.'. $file_info['extension'];
1439
1440 $cropped_thumb = $file_info['dirname'].'/'.$file_info['filename'].'-'.$dim[0].'x'.$dim[1].$extension;
1441
1442 if ( file_exists( $cropped_thumb ) ) { // there is a thumbnail already, use it
1443
1444 $new_img = str_replace( wp_basename( $thumbnail[0] ), wp_basename( $cropped_thumb ), $thumbnail[0] );
1445 return "<img src=\"". $new_img ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_cached_thumb wpp_{$source}\" />";
1446
1447 } else { // no thumbnail or image file missing, try to create it
1448
1449 if ( function_exists('wp_get_image_editor') ) { // if supported, use WP_Image_Editor Class
1450
1451 $image = wp_get_image_editor( $file_path );
1452
1453 if ( is_wp_error( $image ) ) { // image file path is invalid
1454 return "<!-- " . $image->get_error_message() ." --> <img src=\"". $this->default_thumbnail ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_imgeditor_error wpp_{$source}\" />";
1455 }
1456
1457 $image->resize( $dim[0], $dim[1], true );
1458 $new_img = $image->save();
1459
1460 if ( is_wp_error( $new_img ) ) {
1461 return "<!-- " . $new_img->get_error_message() ." --> <img src=\"". $this->default_thumbnail ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_imgeditor_error wpp_{$source}\" />";
1462 }
1463
1464 $new_img = str_replace( wp_basename( $thumbnail[0] ), $new_img['file'], $thumbnail[0] );
1465 return "<img src=\"". $new_img ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_imgeditor_thumb wpp_{$source}\" />";
1466
1467 } else { // create thumb using image_resize()
1468
1469 $new_img_path = image_resize( $file_path, $dim[0], $dim[1], true );
1470
1471 if ( is_wp_error( $new_img_path ) ) { // image file path is invalid
1472 return "<!-- " . $new_img_path->get_error_message() ." --> <img src=\"". $this->default_thumbnail ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_image_resize_error wpp_{$source}\" />";
1473 }
1474
1475 $new_img_size = getimagesize( $new_img_path );
1476 $new_img = str_replace( wp_basename( $thumbnail[0] ), wp_basename( $new_img_path ), $thumbnail[0] );
1477 return "<img src=\"". $new_img ."\" alt=\"\" border=\"0\" width=\"{$dim[0]}\" height=\"{$dim[1]}\" class=\"wpp-thumbnail wpp_image_resize_thumb wpp_{$source}\" />";
1478
1479 }
1480
1481 }
1482
1483 }
1484
1485 function is_external_image( $url ){
1486
1487 $dir = wp_upload_dir();
1488
1489 // baseurl never has a trailing slash
1490 if ( false === strpos( $url, $dir['baseurl'] . '/' ) ) {
1491 // URL points to a place outside of upload directory
1492 return true;
1493 }
1494
1495 return false;
1496
1497 }
1498
1499 function download_image( $url, $id ){
1500
1501 $image = array();
1502
1503 $uploads = wp_upload_dir();
1504 $image[0] = trailingslashit( $uploads['baseurl'] ) . "{$id}_". sanitize_file_name( rawurldecode(wp_basename( $url )) );
1505 $image[1] = trailingslashit( $uploads['basedir'] ) . "{$id}_". sanitize_file_name( rawurldecode(wp_basename( $url )) );
1506
1507 // if the file exists already, return URL and path
1508 if ( file_exists($image[1]) )
1509 return $image;
1510
1511 $accepted_status_codes = array( 200, 301, 302 );
1512 $response = wp_remote_head( $url, array( 'timeout' => 5, 'sslverify' => false ) );
1513
1514 if ( !is_wp_error($response) && in_array(wp_remote_retrieve_response_code($response), $accepted_status_codes) ) {
1515
1516 $image_data = getimagesize( $url );
1517
1518 if ( is_array($image_data) && !empty($image_data) ) {
1519
1520 require_once( ABSPATH . 'wp-admin/includes/file.php' );
1521
1522 $url = str_replace( 'https://', 'http://', $url );
1523 $tmp = download_url( $url );
1524
1525 // move file to Uploads
1526 if ( !is_wp_error( $tmp ) && rename($tmp, $image[1]) ) {
1527
1528 // borrowed from WP - set correct file permissions
1529 $stat = stat( dirname( $image[1] ));
1530 $perms = $stat['mode'] & 0000666;
1531 @chmod( $image[1], $perms );
1532
1533 return $image;
1534
1535 }
1536
1537 }
1538
1539 }
1540
1541 return false;
1542
1543 }
1544
1545 /**
1546 * Get the Attachment ID for a given image URL.
1547 * Source: http://wordpress.stackexchange.com/a/7094
1548 * @param string $url
1549 * @return boolean|integer
1550 */
1551 function wpp_get_attachment_id( $url ) {
1552
1553 if ( $this->is_external_image($url) )
1554 return false;
1555
1556 $file = wp_basename( $url );
1557 $query = array(
1558 'post_type' => 'attachment',
1559 'fields' => 'ids',
1560 'meta_query' => array(
1561 array(
1562 'value' => $file,
1563 'compare' => 'LIKE',
1564 ),
1565 )
1566 );
1567
1568 $query['meta_query'][0]['key'] = '_wp_attached_file';
1569
1570 // query attachments
1571 $ids = get_posts( $query );
1572
1573 if ( ! empty( $ids ) ) {
1574
1575 foreach ( $ids as $id ) {
1576
1577 // first entry of returned array is the URL
1578 if ( $url === array_shift( wp_get_attachment_image_src( $id, 'full' ) ) )
1579 return $id;
1580 }
1581 }
1582
1583 $query['meta_query'][0]['key'] = '_wp_attachment_metadata';
1584
1585 // query attachments again
1586 $ids = get_posts( $query );
1587
1588 if ( empty( $ids) )
1589 return false;
1590
1591 foreach ( $ids as $id ) {
1592
1593 $meta = wp_get_attachment_metadata( $id );
1594
1595 foreach ( $meta['sizes'] as $size => $values ) {
1596
1597 if ( $values['file'] === $file && $url === array_shift( wp_get_attachment_image_src( $id, $size ) ) )
1598 return $id;
1599 }
1600 }
1601
1602 return false;
1603 }
1604
1605 /**
1606 * Parses content tags
1607 * Since 1.4.6
1608 */
1609 function format_content($string, $data = array(), $rating) {
1610
1611 if (empty($string) || (empty($data) || !is_array($data)))
1612 return false;
1613
1614 $string = htmlentities( $string );
1615
1616 $params = array();
1617 $pattern = '/\{(excerpt|summary|stats|title|image|thumb|rating|score|url|text_title|author|category|views|comments)\}/i';
1618 preg_match_all($pattern, $string, $matches);
1619
1620 array_map('strtolower', $matches[0]);
1621
1622 if ( in_array("{title}", $matches[0]) ) {
1623 $string = str_replace( "{title}", $data['title'], $string );
1624 }
1625
1626 if ( in_array("{stats}", $matches[0]) ) {
1627 $string = str_replace( "{stats}", $data['stats'], $string );
1628 }
1629
1630 if ( in_array("{excerpt}", $matches[0]) ) {
1631 $string = str_replace( "{excerpt}", htmlentities($data['summary'], ENT_QUOTES), $string );
1632 }
1633
1634 if ( in_array("{summary}", $matches[0]) ) {
1635 $string = str_replace( "{summary}", htmlentities($data['summary'], ENT_QUOTES), $string );
1636 }
1637
1638 if ( in_array("{image}", $matches[0]) ) {
1639 $string = str_replace( "{image}", $data['img'], $string );
1640 }
1641
1642 if ( in_array("{thumb}", $matches[0]) ) {
1643 $string = str_replace( "{thumb}", $data['img'], $string );
1644 }
1645
1646 // WP-PostRatings check
1647 if ($rating && $this->postRating) {
1648 if ( in_array("{rating}", $matches[0]) ) {
1649 $string = str_replace( "{rating}", the_ratings_results($data['id']), $string );
1650 }
1651
1652 if ( in_array("{score}", $matches[0]) ) {
1653 $string = str_replace( "{score}", expand_ratings_template('%RATINGS_SCORE%', $data['id']), $string);
1654 // removing the redundant plus sign
1655 $string = str_replace('+', '', $string);
1656 }
1657 }
1658
1659 if ( in_array("{url}", $matches[0]) ) {
1660 $string = str_replace( "{url}", $data['url'], $string );
1661 }
1662
1663 if ( in_array("{text_title}", $matches[0]) ) {
1664 $string = str_replace( "{text_title}", $data['text_title'], $string );
1665 }
1666
1667 if ( in_array("{author}", $matches[0]) ) {
1668 $string = str_replace( "{author}", $data['author'], $string );
1669 }
1670
1671 if ( in_array("{category}", $matches[0]) ) {
1672 $string = str_replace( "{category}", $data['category'], $string );
1673 }
1674
1675 if ( in_array("{views}", $matches[0]) ) {
1676 $string = str_replace( "{views}", $data['views'], $string );
1677 }
1678
1679 if ( in_array("{comments}", $matches[0]) ) {
1680 $string = str_replace( "{comments}", $data['comments'], $string );
1681 }
1682
1683 return html_entity_decode( $string );
1684 }
1685
1686 // code seen at http://www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags/
1687 // Since 2.0.1
1688 /**
1689 * Truncates text.
1690 *
1691 * Cuts a string to the length of $length and replaces the last characters
1692 * with the ending if the text is longer than length.
1693 *
1694 * @param string $text String to truncate.
1695 * @param integer $length Length of returned string, including ellipsis.
1696 * @param string $ending Ending to be appended to the trimmed string.
1697 * @param boolean $exact If false, $text will not be cut mid-word
1698 * @param boolean $considerHtml If true, HTML tags would be handled correctly
1699 * @return string Trimmed string.
1700 */
1701 function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) {
1702 if ($considerHtml) {
1703 // if the plain text is shorter than the maximum length, return the whole text
1704 if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
1705 return $text;
1706 }
1707 // splits all html-tags to scanable lines
1708 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
1709 $total_length = strlen($ending);
1710 $open_tags = array();
1711 $truncate = '';
1712 foreach ($lines as $line_matchings) {
1713 // if there is any html-tag in this line, handle it and add it (uncounted) to the output
1714 if (!empty($line_matchings[1])) {
1715 // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
1716 if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
1717 // do nothing
1718 // if tag is a closing tag (f.e. </b>)
1719 } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
1720 // delete tag from $open_tags list
1721 $pos = array_search($tag_matchings[1], $open_tags);
1722 if ($pos !== false) {
1723 unset($open_tags[$pos]);
1724 }
1725 // if tag is an opening tag (f.e. <b>)
1726 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
1727 // add tag to the beginning of $open_tags list
1728 array_unshift($open_tags, strtolower($tag_matchings[1]));
1729 }
1730 // add html-tag to $truncate'd text
1731 $truncate .= $line_matchings[1];
1732 }
1733 // calculate the length of the plain text part of the line; handle entities as one character
1734 $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
1735 if ($total_length+$content_length> $length) {
1736 // the number of characters which are left
1737 $left = $length - $total_length;
1738 $entities_length = 0;
1739 // search for html entities
1740 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)) {
1741 // calculate the real length of all entities in the legal range
1742 foreach ($entities[0] as $entity) {
1743 if ($entity[1]+1-$entities_length <= $left) {
1744 $left--;
1745 $entities_length += strlen($entity[0]);
1746 } else {
1747 // no more characters left
1748 break;
1749 }
1750 }
1751 }
1752 //$truncate .= substr($line_matchings[2], 0, $left+$entities_length);
1753 $truncate .= mb_substr($line_matchings[2], 0, $left+$entities_length);
1754 // maximum length is reached, so get off the loop
1755 break;
1756 } else {
1757 $truncate .= $line_matchings[2];
1758 $total_length += $content_length;
1759 }
1760 // if the maximum length is reached, get off the loop
1761 if($total_length>= $length) {
1762 break;
1763 }
1764 }
1765 } else {
1766 if (strlen($text) <= $length) {
1767 return $text;
1768 } else {
1769 //$truncate = substr($text, 0, $length - strlen($ending));
1770 $truncate = mb_substr($text, 0, $length - strlen($ending));
1771 }
1772 }
1773 // if the words shouldn't be cut in the middle...
1774 if (!$exact) {
1775 // ...search the last occurance of a space...
1776 $spacepos = strrpos($truncate, ' ');
1777 if (isset($spacepos)) {
1778 // ...and cut the text in this position
1779 //$truncate = substr($truncate, 0, $spacepos);
1780 $truncate = mb_substr($truncate, 0, $spacepos);
1781 }
1782 }
1783 // add the defined ending to the text
1784 $truncate .= $ending;
1785 if($considerHtml) {
1786 // close all unclosed html-tags
1787 foreach ($open_tags as $tag) {
1788 $truncate .= '</' . $tag . '>';
1789 }
1790 }
1791 return $truncate;
1792 }
1793
1794 /**
1795 * Loads translations
1796 * Since 2.0.0
1797 */
1798 function wpp_textdomain() {
1799 load_plugin_textdomain( 'wordpress-popular-posts', false, dirname(plugin_basename( __FILE__ )) . '/lang/' );
1800 }
1801
1802 /**
1803 * Loads WPP stylesheet into wp_head()
1804 * Since 2.0.0
1805 */
1806 function wpp_print_stylesheet() {
1807
1808 $css_path = NULL;
1809
1810 if ( !is_admin() ) {
1811
1812 $theme_file = get_stylesheet_directory() . '/wpp.css';
1813 $plugin_file = plugin_dir_path(__FILE__) . 'style/wpp.css';
1814
1815 if ( @file_exists($theme_file) ) { // user stored a custom wpp.css on theme's directory, so use it
1816 $css_path = get_stylesheet_directory_uri() . "/wpp.css";
1817 } elseif ( @file_exists($plugin_file) ) { // no custom wpp.css, use plugin's instead
1818 $css_path = $this->pluginDir . 'style/wpp.css';
1819 }
1820
1821 if ( $css_path )
1822 wp_enqueue_style('wordpress-popular-posts', $css_path, false, $this->version);
1823
1824 }
1825 }
1826
1827 /**
1828 * WPP Admin page
1829 * Since 2.3.0
1830 */
1831 function wpp_admin() {
1832 require (dirname(__FILE__) . '/admin.php');
1833 }
1834 function add_wpp_admin() {
1835 add_options_page('Wordpress Popular Posts', 'Wordpress Popular Posts', 'manage_options', 'wpp_admin', array(&$this, 'wpp_admin'));
1836 }
1837 /**
1838 * Upload scripts for the admin section
1839 * Since 2.3.4
1840 */
1841 function wpp_admin_enqueue_scripts() {
1842
1843 wp_register_script( 'wpp-upload', $this->pluginDir . 'js/wpp-upload.js', array('jquery','media-upload','thickbox'), $this->version );
1844
1845 if ( get_current_screen()->id == 'settings_page_wpp_admin' ) {
1846
1847 wp_enqueue_script('jquery');
1848 wp_enqueue_script('thickbox');
1849 wp_enqueue_style('thickbox');
1850 wp_enqueue_script('media-upload');
1851 wp_enqueue_script('wpp-upload');
1852
1853 }
1854
1855 }
1856 function wpp_tb_setup() {
1857
1858 global $pagenow;
1859 if ( 'media-upload.php' == $pagenow || 'async-upload.php' == $pagenow ) {
1860 add_filter( 'gettext', array(&$this, 'replace_thickbox_text'), 1, 3 );
1861 }
1862
1863 }
1864 function replace_thickbox_text($translated_text, $text, $domain) {
1865
1866 if ('Insert into Post' == $text) {
1867 $referer = strpos( wp_get_referer(), 'wpp_admin' );
1868 if ( $referer != '' ) {
1869 return __('Upload', 'wordpress-popular-posts' );
1870 }
1871 }
1872
1873 return $translated_text;
1874 }
1875
1876 /**
1877 * WPP Update warning - lets the user know that the current WP version is too old
1878 * Since 2.0.0
1879 */
1880 function wpp_update_warning() {
1881 $msg = '<div id="wpp-message" class="error fade"><p>'.__('Your Wordpress version is too old. Wordpress Popular Posts Plugin requires at least version 3.3 to function correctly. Please update your blog via Tools &gt; Upgrade.', 'wordpress-popular-posts').'</p></div>';
1882 echo trim($msg);
1883 }
1884
1885 /**
1886 * PHP Update warning - lets the user know that the PHP version is too old
1887 * Since 2.3.3
1888 */
1889 function php_update_warning() {
1890 $msg = '<div id="wpp-php-message" class="error fade"><p>'.__('Your PHP installation is too old. Wordpress Popular Posts Plugin requires at least PHP v5.2.0 to function correctly. Please contact your hosting provider and ask them to upgrade PHP to 5.2.x or higher.', 'wordpress-popular-posts').'</p></div>';
1891 echo trim($msg);
1892 }
1893
1894 /**
1895 * WPP cache maintenance
1896 * Since 2.0.0
1897 */
1898 function wpp_cache_maintenance() {
1899 global $wpdb;
1900
1901 // delete posts that have not been seen in the past 30 days
1902 $wpdb->query( "DELETE FROM ".$wpdb->prefix."popularpostsdatacache WHERE day < DATE_SUB('".$this->curdate()."', INTERVAL 30 DAY);" );
1903
1904 // delete posts that have been deleted or trashed - added on ver 2.3.3
1905 $wpdb->query( "DELETE FROM {$wpdb->prefix}popularpostsdata WHERE postid IN (SELECT c.id FROM (SELECT id FROM {$wpdb->prefix}popularpostsdatacache GROUP BY id) c LEFT JOIN {$wpdb->posts} p ON c.id = p.ID WHERE p.ID IS NULL OR p.post_status = 'trash');" );
1906 $wpdb->query( "DELETE FROM {$wpdb->prefix}popularpostsdatacache WHERE id IN (SELECT c.id FROM (SELECT id FROM {$wpdb->prefix}popularpostsdatacache GROUP BY id) c LEFT JOIN {$wpdb->posts} p ON c.id = p.ID WHERE p.ID IS NULL OR p.post_status = 'trash');" );
1907
1908 }
1909
1910 /**
1911 * WPP plugin deactivation
1912 * Since 2.0.0
1913 */
1914 function wpp_deactivation() {
1915 wp_clear_scheduled_hook('wpp_cache_event');
1916 remove_shortcode('wpp');
1917 remove_shortcode('WPP');
1918 }
1919
1920 /**
1921 * WPP shortcode handler
1922 * Since 2.0.0
1923 */
1924 function wpp_shortcode($atts = NULL, $content = NULL) {
1925
1926 extract( shortcode_atts( array(
1927 'header' => '',
1928 'limit' => 10,
1929 'range' => 'daily',
1930 'order_by' => 'views',
1931 'post_type' => 'post,page',
1932 'pid' => '',
1933 'cat' => '',
1934 'author' => '',
1935 'title_length' => 0,
1936 'title_by_words' => 0,
1937 'excerpt_length' => 0,
1938 'excerpt_format' => 0,
1939 'excerpt_by_words' => 0,
1940 'thumbnail_width' => 0,
1941 'thumbnail_height' => 0,
1942 'thumbnail_selection' => 'wppgenerated',
1943 'rating' => false,
1944 'stats_comments' => true,
1945 'stats_views' => false,
1946 'stats_author' => false,
1947 'stats_date' => false,
1948 'stats_date_format' => 'F j, Y',
1949 'stats_category' => false,
1950 'wpp_start' => '<ul class="wpp-list">',
1951 'wpp_end' => '</ul>',
1952 'post_html' => '',
1953 'post_start' => '<li>',
1954 'post_end' => '</li>',
1955 'header_start' => '<h2>',
1956 'header_end' => '</h2>',
1957 'do_pattern' => false,
1958 'pattern_form' => '{thumb} {title}: {summary} {stats}'
1959 ), $atts ) );
1960
1961 // possible values for "Time Range" and "Order by"
1962 $range_values = array("yesterday", "daily", "weekly", "monthly", "all");
1963 $order_by_values = array("comments", "views", "avg");
1964 $thumbnail_selector = array("wppgenerated", "usergenerated");
1965
1966 $shortcode_ops = array(
1967 'title' => strip_tags($header),
1968 'limit' => empty($limit) ? 10 : (is_numeric($limit)) ? (($limit > 0) ? $limit : 10) : 10,
1969 'range' => (in_array($range, $range_values)) ? $range : 'daily',
1970 'order_by' => (in_array($order_by, $order_by_values)) ? $order_by : 'views',
1971 'post_type' => empty($post_type) ? 'post,page' : $post_type,
1972 'pid' => preg_replace( '|[^0-9,]|', '', $pid ),
1973 'cat' => preg_replace( '|[^0-9,-]|', '', $cat ),
1974 'author' => preg_replace( '|[^0-9,]|', '', $author ),
1975 'shorten_title' => array(
1976 'active' => empty($title_length) ? false : (is_numeric($title_length)) ? (($title_length > 0) ? true : false) : false,
1977 'length' => empty($title_length) ? 0 : (is_numeric($title_length)) ? $title_length : 0,
1978 'words' => empty($title_by_words) ? false : (is_numeric($title_by_words) && $title_by_words > 0) ? true : false
1979 ),
1980 'post-excerpt' => array(
1981 'active' => empty($excerpt_length) ? false : (is_numeric($excerpt_length)) ? (($excerpt_length > 0) ? true : false) : false,
1982 'length' => empty($excerpt_length) ? 0 : (is_numeric($excerpt_length)) ? $excerpt_length : 0,
1983 'keep_format' => empty($excerpt_format) ? false : (is_numeric($excerpt_format)) ? (($excerpt_format > 0) ? true : false) : false,
1984 'words' => empty($excerpt_by_words) ? false : (is_numeric($excerpt_by_words) && $excerpt_by_words > 0) ? true : false,
1985 ),
1986 'thumbnail' => array(
1987 'active' => empty($thumbnail_width) ? false : (is_numeric($thumbnail_width)) ? (($thumbnail_width > 0) ? true : false) : false,
1988 'width' => empty($thumbnail_width) ? 0 : (is_numeric($thumbnail_width)) ? $thumbnail_width : 0,
1989 'height' => empty($thumbnail_height) ? 0 : (is_numeric($thumbnail_height)) ? $thumbnail_height : 0
1990 ),
1991 'rating' => empty($rating) || $rating = "false" ? false : true,
1992 'stats_tag' => array(
1993 'comment_count' => empty($stats_comments) ? false : $stats_comments,
1994 'views' => empty($stats_views) ? false : $stats_views,
1995 'author' => empty($stats_author) ? false : $stats_author,
1996 'date' => array(
1997 'active' => empty($stats_date) ? false : $stats_date,
1998 'format' => empty($stats_date_format) ? 'F j, Y' : $stats_date_format
1999 ),
2000 'category' => empty($stats_category) ? false : $stats_category,
2001 ),
2002 'markup' => array(
2003 'custom_html' => true,
2004 'wpp-start' => empty($wpp_start) ? '&lt;ul class="wpp-list"&gt;' : $wpp_start,
2005 'wpp-end' => empty($wpp_end) ? '&lt;/ul&gt;' : $wpp_end,
2006 'post-html' => empty($post_html) ? '&lt;li&gt;{thumb} {title} {stats}&lt;/li&gt;' : $post_html,
2007 'post-start' => empty($post_start) ? '&lt;li&gt;' : $post_start,
2008 'post-end' => empty($post_end) ? '&lt;/li&gt;' : $post_end,
2009 'title-start' => empty($header_start) ? '' : $header_start,
2010 'title-end' => empty($header_end) ? '' : $header_end
2011 )
2012 );
2013
2014 /*echo "<pre>"; print_r( $shortcode_ops ); echo "</pre>";*/
2015
2016 $shortcode_content = "<!-- Wordpress Popular Posts Plugin v". $this->version ." [SC] [".$shortcode_ops['range']."] [".$shortcode_ops['order_by']."]". (($shortcode_ops['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
2017
2018 // is there a title defined by user?
2019 if (!empty($header) && !empty($header_start) && !empty($header_end)) {
2020 $shortcode_content .= $header_start . apply_filters('widget_title', $header) . $header_end;
2021 }
2022
2023 // print popular posts list
2024 $shortcode_content .= $this->get_popular_posts($shortcode_ops);
2025 $shortcode_content .= "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
2026
2027 return $shortcode_content;
2028 }
2029
2030 /**
2031 * WPP action links
2032 * Since 2.3.3
2033 */
2034 function wpp_action_links( $links, $file ){
2035 static $this_plugin;
2036
2037 if (!$this_plugin) {
2038 $this_plugin = plugin_basename(__FILE__);
2039 }
2040
2041 if ($file == $this_plugin) {
2042 $settings_link = '<a href="' . get_bloginfo('wpurl') . '/wp-admin/options-general.php?page=wpp_admin">Settings</a>';
2043 array_unshift($links, $settings_link);
2044 }
2045
2046 return $links;
2047 }
2048
2049 /**
2050 * Sorter
2051 * Since 2.3.0
2052 */
2053 function sorter($a, $b) {
2054 if ($a > 0 && $b > 0) {
2055 return $a - $b;
2056 } else {
2057 return $b - $a;
2058 }
2059 }
2060
2061 /**
2062 * Merges two associative arrays recursively
2063 * Source: http://www.php.net/manual/en/function.array-merge-recursive.php#92195
2064 * Since 2.3.4
2065 */
2066 function array_merge_recursive_distinct( array &$array1, array &$array2 ) {
2067 $merged = $array1;
2068
2069 foreach ( $array2 as $key => &$value ) {
2070 if ( is_array( $value ) && isset ( $merged[$key] ) && is_array( $merged[$key] ) ) {
2071 $merged[$key] = $this->array_merge_recursive_distinct ( $merged[$key], $value );
2072 } else {
2073 $merged[$key] = $value;
2074 }
2075 }
2076
2077 return $merged;
2078 }
2079
2080 }
2081
2082 // create tables
2083 register_activation_hook(__FILE__ , array('WordPressPopularPosts', 'wpp_install'));
2084 }
2085
2086 /**
2087 * Wordpress Popular Posts template tags for use in themes.
2088 */
2089
2090 /**
2091 * Template tag - gets views count
2092 * $id (int) - post / page ID
2093 * $range (string) - time frame
2094 * Since 2.0.3.
2095 */
2096 function wpp_get_views($id = NULL, $range = NULL) {
2097 // have we got an id?
2098 if ( empty($id) || is_null($id) || !is_numeric($id) ) {
2099 return "-1";
2100 } else {
2101 global $wpdb;
2102
2103 $table_name = $wpdb->prefix . "popularpostsdata";
2104 $query = "SELECT pageviews, last_viewed AS day FROM {$table_name} WHERE postid = '{$id}'";
2105
2106 if ( $range ) {
2107
2108 $interval = "";
2109
2110 switch( $range ){
2111 case "yesterday":
2112 $interval = "1 DAY";
2113 break;
2114
2115 case "daily":
2116 $interval = "1 DAY";
2117 break;
2118
2119 case "weekly":
2120 $interval = "1 WEEK";
2121 break;
2122
2123 case "monthly":
2124 $interval = "1 MONTH";
2125 break;
2126
2127 default:
2128 $interval = "1 DAY";
2129 break;
2130 }
2131
2132 $now = current_time('mysql');
2133
2134 $query = "SELECT SUM(pageviews) AS pageviews, MAX(day) AS day FROM {$table_name}cache WHERE id = '{$id}' AND day > DATE_SUB('{$now}', INTERVAL {$interval}) LIMIT 1;";
2135 }
2136
2137 $result = $wpdb->get_results($query, ARRAY_A);
2138
2139 if ( !is_array($result) || empty($result) || empty($result[0]['pageviews']) ) {
2140 return "0";
2141 } else {
2142 return number_format( $result[0]['pageviews'] );
2143 }
2144 }
2145 }
2146
2147 /**
2148 * Template tag - gets popular posts
2149 * Since 2.0.3.
2150 */
2151 function wpp_get_mostpopular($args = NULL) {
2152
2153 $shortcode = '[wpp';
2154
2155 if ( is_null( $args ) ) {
2156 $shortcode .= ']';
2157 } else {
2158 if( is_array( $args ) ){
2159 $atts = '';
2160 foreach( $args as $key => $arg ){
2161 $atts .= ' ' . $key . '="' . $arg . '"';
2162 }
2163 } else {
2164 $atts = trim( str_replace( "&", " ", $args ) );
2165 }
2166
2167 $shortcode .= ' ' . $atts . ']';
2168 }
2169
2170 echo do_shortcode( $shortcode );
2171 }
2172
2173 /**
2174 * Template tag - gets popular posts
2175 * Deprecated in 2.0.3.
2176 * Use wpp_get_mostpopular instead.
2177 */
2178 function get_mostpopular($args = NULL) {
2179 return wpp_get_mostpopular($args);
2180 }
2181
2182
2183 /**
2184 * Wordpress Popular Posts 2.3.6 Changelog.
2185 */
2186
2187 /*
2188 = 2.3.6 =
2189 * Added wpp_html filter to allow total control of the HTML output.
2190 * Added sanitization for external thumbnail filenames to avoid weird characters.
2191 * Updated thumbnail feature to handle external images.
2192 * Removed unnecesary wpp-thumbnail class from link tag, the image already has it.
2193 * Added wpp-list class to the UL tag, this should help style the popular list better.
2194 * Updated wpp.css with text floating next to thumbnails - this sets a predefined style for the plugin for the first time.
2195 * Added plugin version to wp_enqueue_* calls.
2196 * Fixed typo in wpp_update_warning. From v2.3.3, minimun Wordpress version required is 3.3.
2197 */