forked from cabrerahector/wordpress-popular-posts
/
wordpress-popular-posts.php
2207 lines (1755 loc) · 96.2 KB
/
wordpress-popular-posts.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: Wordpress Popular Posts
Plugin URI: http://wordpress.org/extend/plugins/wordpress-popular-posts
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><?php wpp_get_mostpopular(); ?></strong>
Version: 2.3.6
Author: Héctor Cabrera
Author URI: http://cabrerahector.com
License: GPL2
*/
if (basename($_SERVER['SCRIPT_NAME']) == basename(__FILE__)) exit('Please do not load this page directly');
/**
* Load Wordpress Popular Posts to widgets_init.
* @since 2.0
*/
add_action('widgets_init', 'load_wpp');
function load_wpp() {
register_widget('WordpressPopularPosts');
}
/**
* Wordpress Popular Posts class.
*/
if ( !class_exists('WordpressPopularPosts') ) {
class WordpressPopularPosts extends WP_Widget {
// plugin global variables
var $version = "2.3.5";
var $qTrans = false;
var $postRating = false;
var $thumb = false;
var $pluginDir = "";
var $charset = "UTF-8";
var $magicquotes = false;
var $default_thumbnail = "";
var $user_ops = array();
var $defaults = array(
'title' => '',
'limit' => 10,
'range' => 'daily',
'order_by' => 'views',
'post_type' => 'post,page',
'pid' => '',
'author' => '',
'cat' => '',
'shorten_title' => array(
'active' => false,
'length' => 25,
'words' => false
),
'post-excerpt' => array(
'active' => false,
'length' => 55,
'keep_format' => false,
'words' => false
),
'thumbnail' => array(
'active' => false,
'width' => 15,
'height' => 15
),
'rating' => false,
'stats_tag' => array(
'comment_count' => true,
'views' => false,
'author' => false,
'date' => array(
'active' => false,
'format' => 'F j, Y'
),
'category' => false
),
'markup' => array(
'custom_html' => false,
'wpp-start' => '<ul class="wpp-list">',
'wpp-end' => '</ul>',
'post-html' => '<li>{thumb} {title} {stats}</li>',
'post-start' => '<li>',
'post-end' => '</li>',
'title-start' => '<h2>',
'title-end' => '</h2>'
)
);
var $wpp_user_settings_def = array(
'stats' => array(
'order_by' => 'views',
'limit' => 10,
'post_type' => 'post,page'
),
'tools' => array(
'ajax' => false,
'css' => true,
'stylesheet' => true,
'thumbnail' => array(
'source' => 'featured',
'field' => '',
'resize' => false,
'default' => ''
),
'log_loggedin' => false,
'cache' => array(
'active' => false,
'interval' => array(
'time' => 'hour',
'value' => 1
)
)
)
);
/**
* WPP's Constructor
* Since 1.4.0
*/
function WordpressPopularPosts() {
global $wp_version;
// Set default title
$this->defaults['title'] = __('Popular Posts', 'wordpress-popular-posts');
// widget settings
$widget_ops = array( 'classname' => 'popular-posts', 'description' => __('The most Popular Posts on your blog.', 'wordpress-popular-posts') );
// widget control settings
$control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'wpp' );
// create the widget
$this->WP_Widget( 'wpp', 'Wordpress Popular Posts', $widget_ops, $control_ops );
// set plugin path
if (empty($this->pluginDir)) $this->pluginDir = plugin_dir_url(__FILE__);
// set charset
$this->charset = get_bloginfo('charset');
// detect PHP magic quotes
$this->magicquotes = get_magic_quotes_gpc();
// get user options
$this->user_ops = get_option('wpp_settings_config');
if ( !$this->user_ops ) {
add_option('wpp_settings_config', $this->wpp_user_settings_def);
$this->user_ops = $this->wpp_user_settings_def;
}
// set default thumbnail
$this->default_thumbnail = $this->pluginDir . "no_thumb.jpg";
$this->wpp_user_settings_def['tools']['thumbnail']['default'] = $this->default_thumbnail;
if ( !empty($this->user_ops['tools']['thumbnail']['default']) ) {
$this->default_thumbnail = $this->user_ops['tools']['thumbnail']['default'];
}
// set version and check for upgrades
$wpp_ver = get_option('wpp_ver');
if ( !$wpp_ver ) {
add_option('wpp_ver', $this->version);
} else if ( version_compare($wpp_ver, $this->version, '<') ) {
$this->wpp_upgrade();
}
// print stylesheet
if ($this->user_ops['tools']['css']) {
add_action('get_header', array(&$this, 'wpp_print_stylesheet'));
}
//wpp_ajax_get_popular
add_action('wp_ajax_wpp_ajax_get_popular', array(&$this, 'ajax_getpopular'));
add_action('wp_ajax_nopriv_wpp_ajax_get_popular', array(&$this, 'ajax_getpopular'));
if ($this->user_ops['tools']['ajax']) {
remove_action('the_content', array(&$this,'wpp_update') );
// add ajax update to wp_ajax_ hook
if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 1 ) {
add_action('wp_ajax_wpp_update', array(&$this, 'wpp_ajax_update'));
}
add_action('wp_ajax_nopriv_wpp_update', array(&$this, 'wpp_ajax_update'));
add_action('wp_head', array(&$this, 'wpp_print_ajax'));
} else {
// stop Wordpress from preloading next post and thus calling single.php twice!
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 1 ) {
remove_action('wp_ajax_wpp_update', array(&$this, 'wpp_ajax_update'));
}
remove_action('wp_ajax_nopriv_wpp_update', array(&$this, 'wpp_ajax_update'));
remove_action('wp_head', array(&$this, 'wpp_print_ajax'));
// add update action, no ajax
add_action('the_content', array(&$this,'wpp_update') );
}
// add ajax table truncation to wp_ajax_ hook
add_action('wp_ajax_wpp_clear_cache', array(&$this, 'wpp_clear_data'));
add_action('wp_ajax_wpp_clear_all', array(&$this, 'wpp_clear_data'));
// activate textdomain for translations
add_action('init', array(&$this, 'wpp_textdomain'));
// activate admin page
add_action('admin_menu', array(&$this, 'add_wpp_admin'));
// enqueue scripts
add_action('admin_enqueue_scripts', array(&$this, 'wpp_admin_enqueue_scripts'));
add_action('admin_init', array(&$this, 'wpp_tb_setup') );
// cache maintenance schedule
register_deactivation_hook(__FILE__, array(&$this, 'wpp_deactivation'));
add_action('wpp_cache_event', array(&$this, 'wpp_cache_maintenance'));
if (!wp_next_scheduled('wpp_cache_event')) {
$tomorrow = time() + 86400;
$midnight = mktime(0, 0, 0,
date("m", $tomorrow),
date("d", $tomorrow),
date("Y", $tomorrow));
wp_schedule_event( $midnight, 'daily', 'wpp_cache_event' );
}
// Wordpress version check
if (version_compare($wp_version, '3.3', '<')) add_action('admin_notices', array(&$this, 'wpp_update_warning'));
// PHP version check
if ( version_compare(phpversion(), '5.2.0', '<') ) add_action('admin_notices', array(&$this, 'php_update_warning'));
// qTrans plugin support
if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) $this->qTrans = true;
// WP-Post Ratings plugin support
if (function_exists('the_ratings_results')) $this->postRating = true;
// Can we create thumbnails?
if (extension_loaded('gd') && function_exists('gd_info') && version_compare(phpversion(), '5.2.0', '>=')) $this->thumb = true;
// shortcode
if( function_exists('add_shortcode') ){
add_shortcode('wpp', array(&$this, 'wpp_shortcode'));
add_shortcode('WPP', array(&$this, 'wpp_shortcode'));
}
// add plugin action link
add_filter('plugin_action_links', array(&$this, 'wpp_action_links'), 10, 2);
}
/**
* Builds WPP's widget
* Since 2.0.0
*/
function widget($args, $instance) {
extract($args);
//echo $widget_id;
echo "<!-- Wordpress Popular Posts Plugin v". $this->version ." [W] [".$instance['range']."] [".$instance['order_by']."]". (($instance['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
echo $before_widget . "\n";
// has user set a title?
if ($instance['title'] != '') {
$title = apply_filters( 'widget_title', $instance['title'] );
if ($instance['markup']['custom_html'] && $instance['markup']['title-start'] != "" && $instance['markup']['title-end'] != "" ) {
echo htmlspecialchars_decode($instance['markup']['title-start'], ENT_QUOTES) . $title . htmlspecialchars_decode($instance['markup']['title-end'], ENT_QUOTES);
} else {
echo $before_title . $title . $after_title;
}
}
if ( $this->user_ops['tools']['ajax'] ) {
?>
<script type="text/javascript">
/* <![CDATA[ */
jQuery(document).ready(function(){
jQuery.get('<?php echo admin_url('admin-ajax.php'); ?>', {action: 'wpp_ajax_get_popular', id: '<?php echo $this->number; ?>'}, function(data){
jQuery('#<?php echo $widget_id; ?>').append(data);
});
});
/* ]]> */
</script>
<?php
} else {
echo $this->get_popular_posts( $instance );
}
echo $after_widget . "\n";
echo "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
}
/**
* Updates each widget instance when user clicks the "save" button
* Since 2.0.0
*/
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = ($this->magicquotes) ? htmlspecialchars( stripslashes(strip_tags( $new_instance['title'] )), ENT_QUOTES ) : htmlspecialchars( strip_tags( $new_instance['title'] ), ENT_QUOTES );
$instance['limit'] = is_numeric($new_instance['limit']) ? $new_instance['limit'] : 10;
$instance['range'] = $new_instance['range'];
$instance['order_by'] = $new_instance['order_by'];
// FILTERS
if ($new_instance['post_type'] == "") { // user did not define the custom post type name, so we fall back to default
$instance['post_type'] = 'post,page';
} else {
$instance['post_type'] = $new_instance['post_type'];
}
$instance['pid'] = implode(",", array_filter(explode(",", preg_replace( '|[^0-9,]|', '', $new_instance['pid'] ))));
$instance['cat'] = implode(",", array_filter(explode(",", preg_replace( '|[^0-9,-]|', '', $new_instance['cat'] ))));
$instance['author'] = implode(",", array_filter(explode(",", preg_replace( '|[^0-9,]|', '', $new_instance['uid'] ))));
$instance['shorten_title']['active'] = (bool) $new_instance['shorten_title-active'];
$instance['shorten_title']['length'] = is_numeric($new_instance['shorten_title-length']) ? $new_instance['shorten_title-length'] : 25;
$instance['shorten_title']['words'] = $new_instance['shorten_title-words'];
$instance['post-excerpt']['active'] = (bool) $new_instance['post-excerpt-active'];
$instance['post-excerpt']['length'] = is_numeric($new_instance['post-excerpt-length']) ? $new_instance['post-excerpt-length'] : 55;
$instance['post-excerpt']['keep_format'] = $new_instance['post-excerpt-format'];
$instance['post-excerpt']['words'] = $new_instance['post-excerpt-words'];
if ($this->thumb) { // can create thumbnails
$instance['thumbnail']['active'] = (bool) $new_instance['thumbnail-active'];
if (is_numeric($new_instance['thumbnail-width']) && is_numeric($new_instance['thumbnail-height'])) {
$instance['thumbnail']['width'] = $new_instance['thumbnail-width'];
$instance['thumbnail']['height'] = $new_instance['thumbnail-height'];
} else {
$instance['thumbnail']['width'] = 15;
$instance['thumbnail']['height'] = 15;
}
} else { // cannot create thumbnails
$instance['thumbnail']['active'] = false;
$instance['thumbnail']['width'] = 15;
$instance['thumbnail']['height'] = 15;
}
if ( isset($instance['thumbnail']['thumb_selection']) )
unset( $instance['thumbnail']['thumb_selection'] );
$instance['rating'] = (bool) $new_instance['rating'];
$instance['stats_tag']['comment_count'] = (bool) $new_instance['comment_count'];
$instance['stats_tag']['views'] = (bool) $new_instance['views'];
$instance['stats_tag']['author'] = (bool) $new_instance['author'];
$instance['stats_tag']['date']['active'] = (bool) $new_instance['date'];
$instance['stats_tag']['date']['format'] = empty($new_instance['date_format']) ? 'F j, Y' : $new_instance['date_format'];
$instance['stats_tag']['category'] = (bool) $new_instance['category'];
$instance['markup']['custom_html'] = $new_instance['custom_html'];
$instance['markup']['wpp-start'] = empty($new_instance['wpp-start']) ? '<ul>' : htmlspecialchars( $new_instance['wpp-start'], ENT_QUOTES );
$instance['markup']['wpp-end'] = empty($new_instance['wpp-end']) ? '</ul>' : htmlspecialchars( $new_instance['wpp-end'], ENT_QUOTES );
$instance['markup']['post-html'] = empty ($new_instance['post-html']) ? '<li>{thumb} {title} {stats}</li>' : htmlspecialchars( $new_instance['post-html'], ENT_QUOTES );
$instance['markup']['post-start'] = empty ($new_instance['post-start']) ? '<li>' : htmlspecialchars( $new_instance['post-start'], ENT_QUOTES );
$instance['markup']['post-end'] = empty ($new_instance['post-end']) ? '</li>' : htmlspecialchars( $new_instance['post-end'], ENT_QUOTES );
$instance['markup']['title-start'] = empty($new_instance['title-start']) ? '' : htmlspecialchars( $new_instance['title-start'], ENT_QUOTES );
$instance['markup']['title-end'] = empty($new_instance['title-end']) ? '' : htmlspecialchars( $new_instance['title-end'], ENT_QUOTES );
return $instance;
}
/**
* WPP widget's form
* Since 2.0.0
*/
function form($instance) {
// update instance's settings
/*echo "<pre>"; print_r($instance); echo "</pre>";*/
$instance = $this->array_merge_recursive_distinct($this->defaults, $instance);
/*echo "<pre>"; print_r($instance); echo "</pre>";*/
// form
?>
<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 />
<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>
<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 />
<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>
<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 />
<select id="<?php echo $this->get_field_id( 'range' ); ?>" name="<?php echo $this->get_field_name( 'range' ); ?>" class="widefat">
<option value="daily" <?php if ( 'daily' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 24 hours', 'wordpress-popular-posts'); ?></option>
<option value="weekly" <?php if ( 'weekly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 7 days', 'wordpress-popular-posts'); ?></option>
<option value="monthly" <?php if ( 'monthly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 30 days', 'wordpress-popular-posts'); ?></option>
<option value="all" <?php if ( 'all' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('All-time', 'wordpress-popular-posts'); ?></option>
</select>
</p>
<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 />
<select id="<?php echo $this->get_field_id( 'order_by' ); ?>" name="<?php echo $this->get_field_name( 'order_by' ); ?>" class="widefat">
<option value="comments" <?php if ( 'comments' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Comments', 'wordpress-popular-posts'); ?></option>
<option value="views" <?php if ( 'views' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Total views', 'wordpress-popular-posts'); ?></option>
<option value="avg" <?php if ( 'avg' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Avg. daily views', 'wordpress-popular-posts'); ?></option>
</select>
</p>
<fieldset style="width:214px; padding:5px;" class="widefat">
<legend><?php _e('Posts settings', 'wordpress-popular-posts'); ?></legend>
<div style="display:<?php if ($this->postRating) : ?>block<?php else: ?>none<?php endif; ?>">
<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 />
</div>
<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 />
<div style="display:<?php if ($instance['shorten_title']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
<br />
<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 />
<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 />
<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 />
</div>
<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 />
<div style="display:<?php if ($instance['post-excerpt']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
<fieldset class="widefat">
<legend><?php _e('Excerpt Properties', 'wordpress-popular-posts'); ?></legend><br />
<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 />
<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 />
<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 />
<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 />
</fieldset>
<br />
</div>
</fieldset>
<br />
<fieldset class="widefat">
<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 />
<label for="<?php echo $this->get_field_id( 'post_type' ); ?>"><?php _e('Post type(s):', 'wordpress-popular-posts'); ?></label><br />
<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 />
<label for="<?php echo $this->get_field_id( 'pid' ); ?>"><?php _e('Post(s) ID(s) to exclude:', 'wordpress-popular-posts'); ?></label><br />
<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 />
<label for="<?php echo $this->get_field_id( 'cat' ); ?>"><?php _e('Category(ies) ID(s):', 'wordpress-popular-posts'); ?></label><br />
<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 />
<label for="<?php echo $this->get_field_id( 'uid' ); ?>"><?php _e('Author(s) ID(s):', 'wordpress-popular-posts'); ?></label><br />
<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 />
</fieldset>
<br />
<fieldset style="width:214px; padding:5px;" class="widefat">
<legend><?php _e('Thumbnail settings', 'wordpress-popular-posts'); ?></legend>
<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 />
<div style="display:<?php if ($instance['thumbnail']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
<label for="<?php echo $this->get_field_id( 'thumbnail-width' ); ?>"><?php _e('Width:', 'wordpress-popular-posts'); ?></label>
<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 />
<label for="<?php echo $this->get_field_id( 'thumbnail-height' ); ?>"><?php _e('Height:', 'wordpress-popular-posts'); ?></label>
<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 />
</div>
</fieldset>
<br />
<fieldset style="width:214px; padding:5px;" class="widefat">
<legend><?php _e('Stats Tag settings', 'wordpress-popular-posts'); ?></legend>
<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 />
<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 />
<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 />
<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>
<div style="display:<?php if ($instance['stats_tag']['date']['active']) : ?>block<?php else: ?>none<?php endif; ?>">
<fieldset class="widefat">
<legend><?php _e('Date Format', 'wordpress-popular-posts'); ?></legend>
<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 />
<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 />
<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 />
<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 />
</fieldset>
</div>
<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 />
</fieldset>
<br />
<fieldset style="width:214px; padding:5px;" class="widefat">
<legend><?php _e('HTML Markup settings', 'wordpress-popular-posts'); ?></legend>
<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 />
<div style="display:<?php if ($instance['markup']['custom_html']) : ?>block<?php else: ?>none<?php endif; ?>">
<br />
<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 />
<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>
<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 />
<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>
<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 />
<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>
</div>
</fieldset>
<?php
}
/**
* RRR Added to get local time as per WP settings
* Since 2.1.6
*/
function curdate() {
return gmdate( 'Y-m-d', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ));
}
function now() {
return current_time('mysql');
}
/**
* Calculates script execution time
* Since 2.3.0
*/
function microtime_float() {
list( $msec, $sec ) = explode( ' ', microtime() );
$microtime = (float) $msec + (float) $sec;
return $microtime;
}
/**
* Updates popular posts data table via AJAX on post/page view
* Since 2.0.0
*/
function wpp_ajax_update() {
$nonce = $_POST['token'];
// is this a valid request?
if ( !wp_verify_nonce($nonce, 'wpp-token') ) die("Invalid token");
if (is_numeric($_POST['id']) && (intval($_POST['id']) == floatval($_POST['id'])) && ($_POST['id'] != '')) {
$id = $_POST['id'];
} else {
die("Invalid ID");
}
// if we got an ID, let's update the data table
global $wpdb;
$wpdb->show_errors();
$table = $wpdb->prefix . 'popularpostsdata';
$exec_time = 0;
// update popularpostsdata table
$start = $this->microtime_float();
$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;");
$end = $this->microtime_float();
$exec_time += round($end - $start, 6);
// update popularpostsdatacache table
$start = $this->microtime_float();
$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()}';");
$exec_time += round($end - $start, 6);
if ($result && $result2) {
die( "OK. Execution time: " . $exec_time . " seconds" );
} else {
die( "Oops: " . $wpdb->print_error() );
}
}
/**
* Updates popular posts data table on post/page view
* Since 2.3.0
*/
function wpp_update($content) {
//if ( (is_single() || is_page()) && !is_user_logged_in() && !is_front_page() ) {
if ( (is_single() || is_page()) && !is_front_page() && !is_preview() ) {
if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 0 && is_user_logged_in() )
return $content;
global $wpdb, $post;
$table = $wpdb->prefix . 'popularpostsdata';
$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;");
$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()}';");
if (!$result || !$result2) {
print_r( $wpdb->print_error() );
}
}
return $content;
}
/**
* Builds list via AJAX
* Since 2.3.3
*/
function ajax_getpopular() {
if ( is_numeric($_GET['id']) && (intval($_GET['id']) == floatval($_GET['id'])) && ($_GET['id'] != '') ) {
$id = $_GET['id'];
} else {
die("Invalid ID");
}
$settings = $this->get_settings();
if ( isset($settings[$id]) ) {
$instance = $settings[$id];
echo $this->get_popular_posts( $instance );
} else {
echo "Invalid Widget ID";
}
die();
}
/**
* Clears WPP datacache table
* Since 2.0.0
*/
function wpp_clear_data() {
$token = $_POST['token'];
$clear = isset($_POST['clear']) ? $_POST['clear'] : '';
$key = get_option("wpp_rand");
if (current_user_can('manage_options') && ($token === $key) && !empty($clear)) {
global $wpdb;
// set table name
$table = $wpdb->prefix . "popularpostsdata";
$cache = $wpdb->prefix . "popularpostsdatacache";
if ($clear == 'cache') {
if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
$wpdb->query("TRUNCATE TABLE $cache;");
_e('Success! The cache table has been cleared!', 'wordpress-popular-posts');
} else {
_e('Error: cache table does not exist.', 'wordpress-popular-posts');
}
} else if ($clear == 'all') {
if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") == $table && $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
$wpdb->query("TRUNCATE TABLE $table;");
$wpdb->query("TRUNCATE TABLE $cache;");
_e('Success! All data have been cleared!', 'wordpress-popular-posts');
} else {
_e('Error: one or both data tables are missing.', 'wordpress-popular-posts');
}
} else {
_e('Invalid action.', 'wordpress-popular-posts');
}
} else {
_e('Sorry, you do not have enough permissions to do this. Please contact the site administrator for support.', 'wordpress-popular-posts');
}
die();
}
/**
* Installs WPP DB tables
* Since 2.0.0
*/
function wpp_install() {
global $wpdb;
$wpdb->show_errors();
$sql = "";
$charset_collate = "";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate";
// set table name
$table = $wpdb->prefix . "popularpostsdata";
// does popularpostsdata table exists?
if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") != $table ) { // fresh setup
$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;";
} else {
// check if cahe table is missing
$cache = $table . "cache";
if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") != $cache ) {
$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;";
} else { // check if any column is missing
// get table columns
$cacheFields = $wpdb->get_results("SHOW FIELDS FROM $cache", ARRAY_A);
$alter_day = true;
$add_daynotime = true;
foreach ($cacheFields as $column) {
// check if day column is type datetime
if ($column['Field'] == 'day') {
if ($column['Type'] == 'datetime') {
$alter_day = false;
}
}
// check if day_no_time field exists
if ($column['Field'] == 'day_no_time') {
$add_daynotime = false;
}
}
if ($alter_day) { // day column is not datimetime, so change it
$wpdb->query("ALTER TABLE $cache CHANGE day day datetime NOT NULL default '0000-00-00 00:00:00';");
}
if ($add_daynotime) { // day_no_time column is missing, add it
$wpdb->query("ALTER TABLE $cache ADD day_no_time date NOT NULL default '0000-00-00';");
$wpdb->query("UPDATE $cache SET day_no_time = day;");
}
$cacheIndex = $wpdb->get_results("SHOW INDEX FROM $cache", ARRAY_A);
if ($cacheIndex[0]['Key_name'] == "id") { // if index is id-day change to id-day_no_time
$wpdb->query("ALTER TABLE $cache DROP INDEX id, ADD UNIQUE KEY compositeID (id, day_no_time);");
}
}
}
dbDelta($sql);
}
/**
* Checks for stuff that needs updating on plugin upgrade
* Since 2.3.1
*/
function wpp_upgrade() {
update_option('wpp_ver', $this->version); // update wpp version in db
// update user options
$this->user_ops = $this->array_merge_recursive_distinct( $this->wpp_user_settings_def, $this->user_ops );
update_option('wpp_settings_config', $this->user_ops);
global $wpdb;
$wpdb->show_errors();
$sql = "";
$charset_collate = "";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate";
// set table name
$data = $wpdb->prefix . "popularpostsdata";
$cache = $data . "cache";
// if the cache table is missing, create it
if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") != $cache ) {
$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;";
} else { // check if any column is missing
// get table columns
$cacheFields = $wpdb->get_results("SHOW FIELDS FROM $cache", ARRAY_A);
$alter_day = true;
$add_daynotime = true;
foreach ($cacheFields as $column) {
// check if day column is type datetime
if ($column['Field'] == 'day') {
if ($column['Type'] == 'datetime') {
$alter_day = false;
}
}
// check if day_no_time field exists
if ($column['Field'] == 'day_no_time') {
$add_daynotime = false;
}
}
if ($alter_day) { // day column is not datimetime, so change it
$wpdb->query("ALTER TABLE $cache CHANGE day day datetime NOT NULL default '0000-00-00 00:00:00';");
}
if ($add_daynotime) { // day_no_time column is missing, add it
$wpdb->query("ALTER TABLE $cache ADD day_no_time date NOT NULL default '0000-00-00';");
$wpdb->query("UPDATE $cache SET day_no_time = day;");
}
$cacheIndex = $wpdb->get_results("SHOW INDEX FROM $cache", ARRAY_A);
if ($cacheIndex[0]['Key_name'] == "id") { // if index is id-day change to id-day_no_time
$wpdb->query("ALTER TABLE $cache DROP INDEX id, ADD UNIQUE KEY compositeID (id, day_no_time);");
}
}
dbDelta($sql);
}
/**
* Prints AJAX script to wp_head()
* Since 2.0.0
*/
function wpp_print_ajax() {
wp_print_scripts('jquery');
// if we're on a page or post, load the script
//if ( (is_single() || is_page()) && !is_user_logged_in() && !is_front_page() ) {
if ( (is_single() || is_page()) && !is_front_page() && !is_preview() ) {
if ( isset($this->user_ops['tools']['log_loggedin']) && $this->user_ops['tools']['log_loggedin'] == 0 && is_user_logged_in() )
return;
// let's add jQuery
//wp_print_scripts('jquery');
// create security token
$nonce = wp_create_nonce('wpp-token');
// get current post's ID
global $wp_query;
wp_reset_query();
$id = $wp_query->post->ID;
?>
<!-- Wordpress Popular Posts v<?php echo $this->version; ?> -->
<script type="text/javascript">
/* <![CDATA[ */
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {action: 'wpp_update', token: '<?php echo $nonce; ?>', id: <?php echo $id; ?>}, function(data){/*alert(data);*/});
/* ]]> */
</script>
<!-- End Wordpress Popular Posts v<?php echo $this->version; ?> -->
<?php
}
}
/**
* Builds popular posts list
* Since 1.4.0
*/
function get_popular_posts($instance, $return = false) {
// update instance's settings
/*echo "<pre>"; print_r($instance); echo "</pre>";*/
$instance = $this->array_merge_recursive_distinct($this->defaults, $instance);
/*echo "<pre>"; print_r($instance); echo "</pre>";*/
global $wpdb;
$table = $wpdb->prefix . "popularpostsdata";
$fields = "";
$from = "";
$where = "";
$post_types = "";
$pids = "";
$cats = "";
$authors = "";
$content = "";
// post filters
// * post types - based on code seen at https://github.com/williamsba/WordPress-Popular-Posts-with-Custom-Post-Type-Support
$types = explode(",", $instance['post_type']);
$i = 0;
$len = count($types);
$sql_post_types = "";
$join_cats = true;
if ($len > 1) { // we are getting posts from more that one ctp
foreach ( $types as $post_type ) {
$sql_post_types .= "'" .$post_type. "'";
if ($i != $len - 1) $sql_post_types .= ",";
$i++;
}
$post_types = " p.post_type IN({$sql_post_types}) ";
} else if ($len == 1) { // post from one ctp only
$post_types = " p.post_type = '".$instance['post_type']."' ";
// if we're getting just pages, why join the categories table?
if ( strtolower($instance['post_type']) == 'page' )
$join_cats = false;
}
// * posts exclusion
if ( !empty($instance['pid']) ) {
$ath = explode(",", $instance['pid']);
$len = count($ath);
if ($len > 1) { // we are excluding more than one post
$pids = " AND p.ID NOT IN(".$instance['pid'].") ";
} else if ($len == 1) { // exclude one post only
$pids = " AND p.ID <> '".$instance['pid']."' ";
}
}
// * categories
if ( !empty($instance['cat']) && $join_cats ) {
$cat_ids = explode(",", $instance['cat']);
$in = array();
$out = array();
$not_in = "";
usort($cat_ids, array(&$this, 'sorter'));
for ($i=0; $i < count($cat_ids); $i++) {
if ($cat_ids[$i] >= 0) $in[] = $cat_ids[$i];
if ($cat_ids[$i] < 0) $out[] = $cat_ids[$i];
}
$in_cats = implode(",", $in);
$out_cats = implode(",", $out);
$out_cats = preg_replace( '|[^0-9,]|', '', $out_cats );
if ($in_cats != "" && $out_cats == "") { // get posts from from given cats only
$cats = " AND p.ID IN (
SELECT object_id
FROM $wpdb->term_relationships AS r
JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
JOIN $wpdb->terms AS t ON t.term_id = x.term_id
WHERE x.taxonomy = 'category' AND t.term_id IN($in_cats)
) ";
} else if ($in_cats == "" && $out_cats != "") { // exclude posts from given cats only
$cats = " AND p.ID NOT IN (
SELECT object_id
FROM $wpdb->term_relationships AS r
JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
JOIN $wpdb->terms AS t ON t.term_id = x.term_id
WHERE x.taxonomy = 'category' AND t.term_id IN($out_cats)
) ";
} else { // mixed, and possibly a heavy load on the DB
$cats = " AND p.ID IN (
SELECT object_id
FROM $wpdb->term_relationships AS r
JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
JOIN $wpdb->terms AS t ON t.term_id = x.term_id
WHERE x.taxonomy = 'category' AND t.term_id IN($in_cats)
)) OR (p.post_type = 'post' AND p.ID NOT IN (
SELECT object_id
FROM $wpdb->term_relationships AS r
JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
JOIN $wpdb->terms AS t ON t.term_id = x.term_id
WHERE x.taxonomy = 'category' AND t.term_id IN($out_cats)
) ";
}
}
// * authors
if ( !empty($instance['author']) ) {
$ath = explode(",", $instance['author']);
$len = count($ath);
if ($len > 1) { // we are getting posts from more that one author
$authors = " AND p.post_author IN(".$instance['author'].") ";
} else if ($len == 1) { // post from one author only
$authors = " AND p.post_author = '".$instance['author']."' ";
}
}
$fields = "p.ID AS 'id', p.post_title AS 'title', p.post_date AS 'date', p.post_author AS 'uid' ";
if ($instance['range'] == "all") { // ALL TIME
$fields .= ", p.comment_count AS 'comment_count' ";
if ($instance['order_by'] == "comments") { // ordered by comments
if ($instance['stats_tag']['views']) { // get views, too
$fields .= ", IFNULL(v.pageviews, 0) AS 'pageviews' ";
$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']} ";
} else { // get data from wp_posts only
$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']} ";
}
} else { // ordered by views / avg
if ( $instance['order_by'] == "views" ) {
$fields .= ", v.pageviews AS 'pageviews' ";
$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']} ";
} else if ( $instance['order_by'] == "avg" ) {
$fields .= ", ( v.pageviews/(IF ( DATEDIFF('{$this->now()}', MIN(v.day)) > 0, DATEDIFF('{$this->now()}', MIN(v.day)), 1) ) ) AS 'avg_views' ";
$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']} ";
}
}
} else { // CUSTOM RANGE
$interval = "";
switch( $instance['range'] ){
case "yesterday":
$interval = "1 DAY";
break;
case "daily":
$interval = "1 DAY";
break;