-
Notifications
You must be signed in to change notification settings - Fork 2
/
wp_veracity.php
executable file
·3192 lines (2928 loc) · 95.8 KB
/
wp_veracity.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 Veracity
Plugin URI: http://appfrica.org
Description: This will enable ranking of your posts by popularity based on Bayesian algorithm; using the behavior of your visitors to determine each post's popularity. You set a value (or use the default value) for every post view, comment, etc. and the popularity of your posts is calculated based on those values. Once you have activated the plugin, you can configure the Popularity Values and View Reports. You can also use the included Widgets and Template Tags to display post popularity and lists of popular posts on your blog. This plug-in borrows code from and is a mashup of Popularity Contest from Crowd Favorite (http://crowdfavorite.com/wordpress/plugins/popularity-contest/) and Bayesian Top Title Learner (http://wordpress.org/extend/plugins/bayesian-top-title-learner/).
Version: 1.0
Author: Ivan Kavuma, Jon Gosier
Author URI: http://appfrica.org
*/
$interest = 'interest';//meta data tags for wp
$scen = 'scenario';
$processdelayinsec=2;//TODO ADD option
$processnow = TRUE;//FALSE;
function bttl_widget()
{
// Check for the required plugin functions.
if (!function_exists('register_sidebar_widget') ){return;}
//Display defaultnum posts picked randomly, weighted based on interest.
//Records which ones were displayed in the SQL database
//Checks if we need to process our data based on time interval or user request
function bttl_display($args)
{
global $processdelayinsec, $processnow;
global $interest, $scen;
global $wpdb;
extract($args);
$wpdb->bttl_data = $wpdb->prefix.'bttl_data';
$options=get_option('bttl_control');
$defaultnum = (isset($options['count'])) ? $options['count'] : 4;
$title = ($options['title']) ? $options['title'] : "Featured" ;
$testmode = ($options['showscore']) ? TRUE : FALSE;
$items = pickrandomweighted($defaultnum);
$timestamp = rand(1000000,2000000);
$plugindirarr = explode('wp-content',dirname(__FILE__));
$plugindir = (count($plugindirarr)==2) ? '/wp-content'.$plugindirarr[1] : '/wp-content/plugins';
//microtime(get_as_float);
//microtime seemed like a good unique identifier, but its implementation
//is not standard on all systems
//rand may collide, but not often and the effect on stats would be negligible
echo $before_widget;
echo "$before_title $title $after_title <ul>";
foreach ($items as $item)
{
$ab=get_post_meta($item->ID,$interest,TRUE);
$score = ($testmode) ? round(expect($ab),2)." <a href='http://www.srcf.ucam.org/~sea31/what_multi.cgi?plot=plot+%5B0%3A1%5D+x**$ab[0]+*%281-x%29**$ab[1]&button=plot'>plot</a>" : "";
echo '<li><a href="' . get_bloginfo('wpurl') . $plugindir.'/bttl.php?guid='.rawurlencode(get_permalink($item->ID)).'&items='.$item->ID.'&stamp='.$timestamp.'">'.$item->post_title." $score".'</a>'.'</li>';
}
if ($testmode) echo "<li>".round(expect($ab=get_option($scen)),2)." <a href='http://www.srcf.ucam.org/~sea31/what_multi.cgi?plot=plot+%5B0%3A1%5D+x**$ab[0]+*%281-x%29**$ab[1]&button=plot'>plot</a> </li>";
echo '</ul> '.$after_widget;
$table_name=$wpdb->bttl_data;
if ($wpdb->get_var("show tables like '$table_name'") != $table_name)
{
$sql = "CREATE TABLE " . $table_name . " (
timestamp char(20),
items BIGINT(20),
clicked int(8) NOT NULL DEFAULT 0,
key timestamp(timestamp)
);
";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
//Commented statement is safer, but unnecessary because users can't affect these values. The subsequent statement is more compatible
//foreach ($items as $item) $wpdb->insert($table_name,array('timestamp'=>$timestamp,'items'=>$item->ID));
foreach ($items as $item) {$id = $item->ID;$wpdb->query("INSERT INTO $table_name (timestamp, items) VALUES ('$timestamp','$id')");}
$oldest = $wpdb->get_var('SELECT timestamp FROM '.$table_name.' ORDER BY timestamp ASC LIMIT 1');
$newest = $wpdb->get_var('SELECT timestamp FROM '.$table_name.' ORDER BY timestamp DESC LIMIT 1');
$oldtime=get_option('lastupdatetime');
$newtime=time();
if (($newtime - $oldtime > $processdelayinsec) or($processnow==true))
{
updateinterest();
update_option('lastupdatetime',$newtime);
}
}
//Make sure all the posts have a prior interest setting
function checkforblanks()
{
$defaultprior = array(0, 0);//initializes or resets for interest/scenario tags
$defaultscen = array(0, 3);
global $interest;
global $scen;
$all_posts = get_posts('numberposts=-1');
//RESET
$options=get_option('bttl_control');
$resetparams = ($options['reset']==1)? TRUE: FALSE;
if ($resetparams)
{
foreach ($all_posts as $post)
{
update_option($scen, $defaultscen);
delete_post_meta($post->ID, $interest);
}
//DROP TABLE ADD
$options['reset']= 0;
update_option('bttl_control',$options);
}
foreach($all_posts as $post) {
if (get_post_meta($post->ID, $interest, TRUE)==FALSE)
add_post_meta($post->ID, $interest, $defaultprior);
}
}
//Pick $number posts at random weighted based on interest
function pickrandomweighted($number)
{
global $interest;
global $wpdb;
checkforblanks();
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
$number = floor($number);
if ($number < 0)
$number = 0;
if ($number > $numposts)
$number = $numposts;
$all_posts = get_posts('numberposts=-1');
$maxinterest = 0;
foreach ($all_posts as $post)
$maxinterest+=expect(get_post_meta($post->ID, $interest, TRUE));
for ($i=0; $i < $number ; $i++)
{
$pick=rand(0, 10000*$maxinterest)/10000;
$temp=0;
foreach ($all_posts as $key=>$post)
{
$pickpostkey = $key;
$temp+=expect(get_post_meta($post->ID, $interest, true));
if ($temp > $pick)
break;
}
$maxinterest -= expect(get_post_meta($all_posts[$pickpostkey]->ID, $interest, TRUE));
$pickpost[$i]=$all_posts[$pickpostkey];
unset($all_posts[$pickpostkey]);
}
return $pickpost;
}
function expect($beta)
{
//Another nice property of Beta distributions: easy expectation values
return((1+$beta[0])/(2+$beta[0]+$beta[1]));
}
//Input an array of weights, output the key of a choice made randomly based on the weights
function randwgt($weightarray)
{
$pick = rand(0, 10000*array_sum($weightarray))/10000;
$temp=0;
foreach ($weightarray as $key=>$i)
{
$item=$key;
$temp+=$i;
if ($temp>$pick)
break;
}
return $item;
}
//Process raw data into a form that can be used in our updating algorithm
function processrawdata()
{
global $interest;
global $wpdb;
$options=get_option('bttl_control');
$defaultnum = ($options['count']) ? $options['count'] : 4;
$all_posts=get_posts('numberposts=-1');
$table_name=$wpdb->prefix.'bttl_data';
$timestamp = $wpdb->get_col("select timestamp,items,clicked from $table_name order by timestamp desc limit $defaultnum");
$items = $wpdb->get_col("", 1);
$clicked = $wpdb->get_col("", 2);
$result = array('posts'=>$items, 'clicked'=>$clicked);
if ($items)
{
$wpdb->query("delete from $table_name where timestamp = '$timestamp[0]'");
}
return $result;
}
//Update interest based on recent data
function updateinterest()
{
global $interest;
global $scen;
$datum = processrawdata();
while($datum['posts']){
//update interest
$somethingclicked = array_sum($datum['clicked'])>0 ? 1 : 0;
$probnoneinteresting = 1;
foreach ($datum['posts'] as $postid)
{
$probnoneinteresting *= (1-expect(get_post_meta($postid, $interest, true)));
}
$j=0;
foreach($datum['posts'] as $postid)
{
$probthisnotinteresting = (1-expect(get_post_meta($postid, $interest, true)));
$nothingterm = 1/(1+((1/expect(get_option($scen))-1)/($probnoneinteresting/$probthisnotinteresting)));
$oldinterest=get_post_meta($postid, $interest, true);
$adda = ($datum['clicked'][$j]);
$addb = (1-$datum['clicked'][$j])*($somethingclicked+(1-$somethingclicked)*$nothingterm);
update_post_meta($postid, $interest, array($oldinterest[0]+$adda, $oldinterest[1]+$addb));
//update the popularity score ########### Ivan #####################
$j++;
}
//update scenario
$oldscen = get_option($scen);
update_option($scen, array($oldscen[0]+$somethingclicked, $oldscen[1]+(1-$somethingclicked)*$probnoneinteresting));
$datum = processrawdata();
}
}
function bttl_control()
{
$options = get_option('bttl_control');
$newoptions = $options;
if (!is_array($options) )
{
add_option('bttl_control', array('title'=>'Featured', 'reset'=>'0', 'count'=>'4', 'showscore'=>'0'));
$options = get_option('bttl_control');
$newoptions = $options;
}
if ($_POST['bttl-submit'] )
{
$newoptions['title'] = strip_tags(stripslashes($_POST['bttl-title']));
$newoptions['reset'] = (int) $_POST['bttl-reset'];
$newoptions['count'] = (int) $_POST['bttl-count'];
$newoptions['showscore'] = (int) $_POST['bttl-showscore'];
}
if ($options != $newoptions )
{
$options = $newoptions;
update_option('bttl_control', $options);
}
?><div style="text-align:right"> <label for="bttl-title" style="line-height:35px;display:block;"><?php
_e('Widget title:', 'widgets');
?><input type="text" id="bttl-title" name="bttl-title" value="<?php
echo wp_specialchars($options['title'], true);
?>" /></label> <label for="bttl-count" style="line-height:35px;display:block;"><?php
_e('Number of links:', 'widgets');
?><input type="text" id="bttl-count" name="bttl-count" value="<?php
echo $options['count'];
?>" /></label> <input type="hidden" name="bttl-submit" id="bttl-submit" value="1" /> <label for="bttl-reset" style="line-height:35px;display:block;"><?php
_e('Reset, 0 or 1:', 'widgets');
?><input type="text" id="bttl-reset" name="bttl-reset" value="<?php
echo $options['reset'];
?>" /></label> <label for="bttl-showscore" style="line-height:35px;display:block;"><?php
_e('Show scores, 0 or 1:', 'widgets');
?><input type="text" id="bttl-showscore" name="bttl-showscore" value="<?php
echo $options['showscore'];
?>" /></label> <input type="hidden" name="bttl-submit" id="bttl-submit" value="1" /> </div><?php
}
function init_bttl()
{
//register_sidebar_widget(array('Bayesian Top Title Learner', 'widgets'), 'bttl_display');
}
// This registers our widget so it appears with the other available
//register_sidebar_widget(array('Bayesian Top Title Learner', 'widgets'), 'bttl_display');
//register_widget_control(array('Bayesian Top Title Learner', 'widgets'), 'bttl_control', 300, 100);
}
//First check how we got here, either record a link, or put up your hooks
if (isset($_GET['stamp']))
{
//RECORD LINKS
$timestamp = $_GET['stamp'];
$items = $_GET['items'];
$clicked = $_GET['clicked'];
$dir_tries = 0;
$dir = dirname( __FILE__ );
while ( !file_exists( "$dir/wp-load.php" ) && $dir_tries < 5 ) {
$dir = dirname( $dir );
$dir_tries++;
}
require_once( "$dir/wp-load.php" );
$table_name=$wpdb->prefix.'bttl_data';
$bob=$wpdb->update($table_name, array('clicked'=>1), array('timestamp'=>$timestamp, 'items'=>$items) ) ;
header('Location: '.rawurldecode($_GET['guid']));
}
else{
add_action('widgets_init', 'bttl_widget');
}
/* popularity section. */
if (!defined('AKPC_LOADED')) : // LOADED CHECK
@define('AKPC_LOADED', true);
/* -- INSTALLATION --------------------- */
// To hide the popularity score on a per post/page basis, add a custom field to the post/page as follows:
// name: hide_popularity
// value: 1
// When this is set to 1, WPMU will auto-install popularity contest for each installed blog when installed in the mu-plugins folder
@define('AKPC_MU_AUTOINSTALL', 1);
// Change this to 1 if you want popularity contest to pull its config from this file instead of the database
// This option hides most of the Popularity Contest admin page
@define('AKPC_CONFIG_FILE', 0);
// By default the view is recorded via an Ajax call from the page. If you want Popularity Contest to do this on the
// back end set this to 0. Setting this to 0 will cause popularity contest results to improperly tally when caching is
// turned on. It is recommended to use the API.
@define('AKPC_USE_API', 1);
// if pulling settings from this file, set weight values below
$akpc_settings['show_pop'] = 1; // clickthrough from feed
$akpc_settings['show_help'] = 1; // clickthrough from feed
$akpc_settings['ignore_authors'] = 1; // clickthrough from feed
$akpc_settings['feed_value'] = 1; // clickthrough from feed
$akpc_settings['home_value'] = 2; // clickthrough from home
$akpc_settings['archive_value'] = 4; // clickthrough from archive page
$akpc_settings['category_value'] = 6; // clickthrough from category page
$akpc_settings['single_value'] = 10; // full article page view
$akpc_settings['comment_value'] = 20; // comment on article
$akpc_settings['pingback_value'] = 50; // pingback on article
$akpc_settings['trackback_value'] = 80; // trackback on article
$akpc_settings['searcher_names'] = 'google.com yahoo.com bing.com'; // serach engine bot names, space separated
// If you would like to show lists of popular posts in the sidebar,
// take a look at how it is implemented in the included sidebar.php.
/* ------------------------------------- */
load_plugin_textdomain('popularity-contest');
if (is_file(trailingslashit(ABSPATH.PLUGINDIR).'popularity-contest.php')) {
define('AKPC_FILE', trailingslashit(ABSPATH.PLUGINDIR).'popularity-contest.php');
}
else if (is_file(trailingslashit(ABSPATH.PLUGINDIR).'popularity-contest/popularity-contest.php')) {
define('AKPC_FILE', trailingslashit(ABSPATH.PLUGINDIR).'popularity-contest/popularity-contest.php');
}
register_activation_hook(AKPC_FILE, 'akpc_install');
function akpc_install() {
global $akpc;
if (!is_a($akpc, 'ak_popularity_contest')) {
$akpc = new ak_popularity_contest();
}
$akpc->install();
$akpc->upgrade();
$akpc->mine_gap_data();
}
// -- MAIN FUNCTIONALITY
class ak_popularity_contest {
var $feed_value;
var $home_value;
var $archive_value;
var $category_value;
var $single_value;
var $comment_value;
var $pingback_value;
var $trackback_value;
var $searcher_names;
var $logged;
var $options;
var $top_ranked;
var $current_posts;
var $show_pop;
var $show_help;
var $ignore_authors;
var $report_types;
function ak_popularity_contest() {
$this->options = array(
'feed_value'
,'home_value'
,'archive_value'
,'category_value'
,'tag_value'
,'single_value'
,'searcher_value'
,'comment_value'
,'pingback_value'
,'trackback_value'
,'searcher_names'
,'show_pop'
,'show_help'
,'ignore_authors'
);
$this->feed_value = 1;
$this->home_value = 2;
$this->archive_value = 4;
$this->category_value = 6;
$this->tag_value = 6;
$this->single_value = 10;
$this->searcher_value = 2;
$this->comment_value = 20;
$this->pingback_value = 50;
$this->trackback_value = 80;
$this->searcher_names = 'google.com yahoo.com bing.com';
$this->logged = 0;
$this->show_pop = 1;
$this->show_help = 1;
$this->ignore_authors = 1;
$this->top_ranked = array();
$this->current_posts = array();
}
function get_settings() {
global $wpdb;
if (AKPC_CONFIG_FILE == 1) { // use hard coded settings
global $akpc_settings;
foreach($akpc_settings as $key => $value) {
if (in_array($key, $this->options)) {
$this->$key = $value;
}
}
}
else { // pull settings from db
// This checks to see if the tables are in the DB for this blog
$settings = $this->query_settings();
// If the DB tables are not in place, lets check to see if we can install
if (!count($settings)) {
// This checks to see if we need to install, then checks if we can install
// For the can install to work in MU the AKPC_MU_AUTOINSTALL variable must be set to 1
if (!$this->check_install() && $this->can_autoinstall()) {
$this->install();
}
if (!$this->check_install()) {
$error = __('
<h2>Popularity Contest Installation Failed</h2>
<p>Sorry, Popularity Contest was not successfully installed. Please try again, or try one of the following options for support:</p>
<ul>
<li><a href="http://wphelpcenter.com">WordPress HelpCenter</a> (the official support provider for Popularity Contest)</li>
<li><a href="http://wordpress.org">WordPress Forums</a> (community support forums)</li>
</ul>
<p>If you are having trouble and need to disable Popularity Contest immediately, simply delete the popularity-contest.php file from within your wp-content/plugins directory.</p>
', 'popularity-contest');
wp_die($error);
}
else {
$settings = $this->query_settings();
}
}
if (count($settings)) {
foreach ($settings as $setting) {
if (in_array($setting->option_name, $this->options)) {
$this->{$setting->option_name} = $setting->option_value;
}
}
}
}
return true;
}
function query_settings() {
global $wpdb;
return @$wpdb->get_results("
SELECT *
FROM $wpdb->ak_popularity_options
");
}
/**
* check_install - This function checks to see if the proper tables have been added to the DB for the blog the plugin is being activated for
*
* @return void
*/
function check_install() {
global $wpdb;
$result = mysql_query("SHOW TABLES LIKE '{$wpdb->prefix}ak_popularity%'", $wpdb->dbh);
return mysql_num_rows($result) == 2;
}
/**
* can_autoinstall - This function checks to see whether the tables can be installed
*
* @return void - Checks to see if the blog is MU, if not returns true
* - Checks to see if the blog is MU, if it is also checks to see if the function can install and returns true if it can
* - (For the second condition to work: ie. if the plugin is installed in MU: AKPC_MU_AUTOINSTALL must be set to 1)
*/
function can_autoinstall() {
global $wpmu_version;
return (is_null($wpmu_version) || (!is_null($wpmu_version) && AKPC_MU_AUTOINSTALL == 1));
}
/**
* install - This function installs the proper tables in the DB for handling popularity contest items
*
* @return void - Returns whether the table creation was successful
*/
function install() {
global $wpdb;
if ($this->check_install()) {
return;
}
$result = mysql_query("
CREATE TABLE `$wpdb->ak_popularity_options` (
`option_name` VARCHAR( 50 ) NOT NULL,
`option_value` VARCHAR( 50 ) NOT NULL
)
", $wpdb->dbh) or die(mysql_error().' on line: '.__LINE__);
if (!$result) {
return false;
}
$this->default_values();
$result = mysql_query("
CREATE TABLE `$wpdb->ak_popularity` (
`post_id` INT( 11 ) NOT NULL ,
`total` INT( 11 ) NOT NULL ,
`feed_views` INT( 11 ) NOT NULL ,
`home_views` INT( 11 ) NOT NULL ,
`archive_views` INT( 11 ) NOT NULL ,
`category_views` INT( 11 ) NOT NULL ,
`tag_views` INT( 11 ) NOT NULL ,
`single_views` INT( 11 ) NOT NULL ,
`searcher_views` INT( 11 ) NOT NULL ,
`comments` INT( 11 ) NOT NULL ,
`pingbacks` INT( 11 ) NOT NULL ,
`trackbacks` INT( 11 ) NOT NULL ,
`last_modified` DATETIME NOT NULL ,
KEY `post_id` ( `post_id` )
)
", $wpdb->dbh) or die(mysql_error().' on line: '.__LINE__);
if (!$result) {
return false;
}
$this->mine_data();
return true;
}
function upgrade() {
$this->upgrade_20();
}
function upgrade_20() {
global $wpdb;
$cols = $wpdb->get_col("
SHOW COLUMNS FROM $wpdb->ak_popularity
");
//2.0 Schema
if (!in_array('tag_views', $cols)) {
$wpdb->query("
ALTER TABLE `$wpdb->ak_popularity`
ADD `tag_views` INT( 11 ) NOT NULL
AFTER `category_views`
");
}
if (!in_array('searcher_views', $cols)) {
$wpdb->query("
ALTER TABLE `$wpdb->ak_popularity`
ADD `searcher_views` INT( 11 ) NOT NULL
AFTER `single_views`
");
}
$temp = new ak_popularity_contest;
$cols = $wpdb->get_col("
SELECT `option_name`
FROM `$wpdb->ak_popularity_options`
");
if (!in_array('searcher_names', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'searcher_names',
'$temp->searcher_names'
)
");
}
if (!in_array('show_pop', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'show_pop',
'$temp->show_pop'
)
");
}
if (!in_array('show_help', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'show_help',
'$temp->show_help'
)
");
}
if (!in_array('ignore_authors', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'ignore_authors',
'$temp->ignore_authors'
)
");
}
}
function default_values() {
global $wpdb;
foreach ($this->options as $option) {
$result = $wpdb->query("
INSERT
INTO $wpdb->ak_popularity_options
VALUES (
'$option',
'{$this->$option}'
)
");
if (!$result) {
return false;
}
}
return true;
}
function update_settings() {
if (!current_user_can('manage_options')) { wp_die('Unauthorized.'); }
global $wpdb;
$this->upgrade();
foreach ($this->options as $option) {
if (isset($_POST[$option])) {
$option != 'searcher_names' ? $this->$option = intval($_POST[$option]) : $this->$option = stripslashes($_POST[$option]);
$wpdb->query("
UPDATE $wpdb->ak_popularity_options
SET option_value = '{$this->$option}'
WHERE option_name = '".$wpdb->escape($option)."'
");
}
}
$this->recalculate_popularity();
$this->mine_gap_data();
header('Location: '.get_bloginfo('wpurl').'/wp-admin/options-general.php?page='.basename(__FILE__).'&updated=true');
die();
}
function recalculate_popularity() {
global $wpdb;
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET total = (home_views * $this->home_value)
+ (feed_views * $this->feed_value)
+ (archive_views * $this->archive_value)
+ (category_views * $this->category_value)
+ (tag_views * $this->tag_value)
+ (single_views * $this->single_value)
+ (searcher_views * $this->searcher_value)
+ (comments * $this->comment_value)
+ (pingbacks * $this->pingback_value)
+ (trackbacks * $this->trackback_value)
");
}
function reset_data() {
global $wpdb;
$result = $wpdb->query("
TRUNCATE $wpdb->ak_popularity
");
if (!$result) {
return false;
}
$result = $wpdb->query("
TRUNCATE $wpdb->ak_popularity_options
");
if (!$result) {
return false;
}
$this->default_values();
return true;
}
function create_post_record($post_id = -1) {
global $wpdb;
if ($post_id == -1) {
global $post_id;
}
$post_id = intval($post_id);
$count = $wpdb->get_var("
SELECT COUNT(post_id)
FROM $wpdb->ak_popularity
WHERE post_id = '$post_id'
");
if (!intval($count)) {
$result = $wpdb->query("
INSERT
INTO $wpdb->ak_popularity (
`post_id`,
`last_modified`
)
VALUES (
'$post_id',
'".date('Y-m-d H:i:s')."'
)
");
}
}
function delete_post_record($post_id = -1) {
global $wpdb;
if ($post_id == -1) {
global $post_id;
}
$result = $wpdb->query("
DELETE
FROM $wpdb->ak_popularity
WHERE post_id = '$post_id'
");
}
function mine_data() {
global $wpdb;
$posts = $wpdb->get_results("
SELECT ID
FROM $wpdb->posts
WHERE post_status = 'publish'
");
if ($posts && count($posts) > 0) {
foreach ($posts as $post) {
$this->create_post_record($post->ID);
$this->populate_post_data($post->ID);
}
}
return true;
}
function mine_gap_data() {
global $wpdb;
$posts = $wpdb->get_results("
SELECT p.ID
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE pop.post_id IS NULL
AND (
p.post_type = 'post'
OR p.post_type = 'page'
)
AND p.post_status = 'publish'
");
if ($posts && count($posts) > 0) {
foreach ($posts as $post) {
$this->create_post_record($post->ID);
$this->populate_post_data($post->ID);
}
}
}
function populate_post_data($post_id) {
global $wpdb;
// grab existing comments
$count = intval($wpdb->get_var("
SELECT COUNT(*)
FROM $wpdb->comments
WHERE comment_post_ID = '$post_id'
AND comment_type = ''
AND comment_approved = '1'
"));
if ($count > 0) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET comments = comments + $count
, total = total + ".($this->comment_value * $count)."
WHERE post_id = '$post_id'
");
if (!$result) {
return false;
}
}
// grab existing trackbacks
$count = intval($wpdb->get_var("
SELECT COUNT(*)
FROM $wpdb->comments
WHERE comment_post_ID = '$post_id'
AND comment_type = 'trackback'
AND comment_approved = '1'
"));
if ($count > 0) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET trackbacks = trackbacks + $count
, total = total + ".($this->trackback_value * $count)."
WHERE post_id = '$post_id'
");
if (!$result) {
return false;
}
}
// grab existing pingbacks
$count = intval($wpdb->get_var("
SELECT COUNT(*)
FROM $wpdb->comments
WHERE comment_post_ID = '$post_id'
AND comment_type = 'pingback'
AND comment_approved = '1'
"));
if ($count > 0) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET pingbacks = pingbacks + $count
, total = total + ".($this->pingback_value * $count)."
WHERE post_id = '$post_id'
");
if (!$result) {
return false;
}
}
}
function record_view($api = false, $ids = false, $type = false) {
if ($this->logged > 0 || ($this->ignore_authors && current_user_can('publish_posts'))) {
return true;
}
global $wpdb;
if ($api == false) {
global $posts;
if (!isset($posts) || !is_array($posts) || count($posts) == 0 || is_admin()) {
return;
}
$ids = array();
$ak_posts = $posts;
foreach ($ak_posts as $post) {
$ids[] = $post->ID;
}
}
if (!$ids || !count($ids)) {
return;
}
if (($api && $type == 'feed') || is_feed()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET feed_views = feed_views + 1
, total = total + $this->feed_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && $type == 'archive') || (is_archive() && !is_category())) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET archive_views = archive_views + 1
, total = total + $this->archive_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && $type == 'category') || is_category()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET category_views = category_views + 1
, total = total + $this->category_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && $type == 'tag') || is_tag()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET tag_views = tag_views + 1
, total = total + $this->tag_views
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && in_array($type, array('single', 'page'))) || is_single() || is_singular() || is_page()) {
if (($api && $type == 'searcher') || akpc_is_searcher()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET searcher_views = searcher_views + 1
, total = total + $this->searcher_value
WHERE post_id = '".$ids[0]."'
");
if (!$result) {
return false;
}
}
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET single_views = single_views + 1
, total = total + $this->single_value
WHERE post_id = '".$ids[0]."'
");
if (!$result) {
return false;
}
}
else {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET home_views = home_views + 1
, total = total + $this->home_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
$this->logged++;
return true;
}
function record_feedback($type, $action = '+', $comment_id = null) {
global $wpdb, $comment_post_ID;
if ($comment_id) {
$comment_post_ID = $comment_id;
}
switch ($type) {
case 'trackback':