/
disqus.php
1587 lines (1418 loc) · 55.1 KB
/
disqus.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: Disqus Comment System
Plugin URI: http://disqus.com/
Description: The Disqus comment system replaces your WordPress comment system with your comments hosted and powered by Disqus. Head over to the Comments admin page to set up your DISQUS Comment System.
Author: Disqus <team@disqus.com>
Version: 2.74
Author URI: http://disqus.com/
*/
/*.
require_module 'standard';
require_module 'pcre';
require_module 'mysql';
.*/
require_once(dirname(__FILE__) . '/lib/wp-api.php');
if (defined('DISQUS_LOCAL')) { // DISQUS defines this for local development purposes
define('DISQUS_DOMAIN', 'dev.disqus.org:8000');
define('DISQUS_IMPORTER_URL', 'http://dev.disqus.org:8001/');
} else {
define('DISQUS_DOMAIN', 'disqus.com');
define('DISQUS_IMPORTER_URL', 'http://import.disqus.com/');
}
define('DISQUS_URL', 'http://' . DISQUS_DOMAIN . '/');
define('DISQUS_MEDIA_URL', 'http://' . DISQUS_DOMAIN . '/media/');
define('DISQUS_API_URL', 'http://' . DISQUS_DOMAIN . '/api/');
define('DISQUS_RSS_PATH', '/latest.rss');
define('DISQUS_CAN_EXPORT', is_file(dirname(__FILE__) . '/export.php'));
if (!defined('DISQUS_DEBUG')) {
define('DISQUS_DEBUG', false);
}
define('DISQUS_VERSION', '2.74');
define('DISQUS_SYNC_TIMEOUT', 30);
/**
* Returns an array of all option identifiers used by DISQUS.
* @return array[int]string
*/
function dsq_options() {
return array(
'_disqus_sync_lock',
'_disqus_sync_post_ids',
# render disqus in the embed
'disqus_active',
'disqus_forum_url',
'disqus_api_key',
'disqus_user_api_key',
'disqus_replace',
'disqus_cc_fix',
# SSO features
'disqus_partner_key',
'disqus_public_key',
'disqus_secret_key',
'disqus_sso_button',
'disqus_sso_icon',
# disables automatic sync via cron
'disqus_manual_sync',
# disables server side rendering
'disqus_disable_ssr',
# the last sync comment id (from get_forum_posts)
'disqus_last_comment_id',
'disqus_version',
);
}
/**
* @param string $file
* @return string
*/
function dsq_plugin_basename($file) {
$file = dirname($file);
// From WP2.5 wp-includes/plugin.php:plugin_basename()
$file = str_replace('\\','/',$file); // sanitize for Win32 installs
$file = preg_replace('|/+|','/', $file); // remove any duplicate slash
$file = preg_replace('|^.*/' . PLUGINDIR . '/|','',$file); // get relative path from plugins dir
if ( strstr($file, '/') === false ) {
return $file;
}
$pieces = explode('/', $file);
return !empty($pieces[count($pieces)-1]) ? $pieces[count($pieces)-1] : $pieces[count($pieces)-2];
}
if ( !defined('WP_CONTENT_URL') ) {
define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content');
}
if ( !defined('PLUGINDIR') ) {
define('PLUGINDIR', 'wp-content/plugins'); // Relative to ABSPATH. For back compat.
}
define('DSQ_PLUGIN_URL', WP_CONTENT_URL . '/plugins/' . dsq_plugin_basename(__FILE__));
$mt_disqus_version = '2.01';
/**
* Response from Disqus get_thread API call for comments template.
*
* @global string $dsq_response
* @since 1.0
*/
$dsq_response = '';
/**
* Disqus API instance.
*
* @global string $dsq_api
* @since 1.0
*/
$dsq_api = new DisqusWordPressAPI(get_option('disqus_forum_url'), get_option('disqus_api_key'));
/**
* DISQUS currently unsupported dev toggle to output comments for this query.
*
* @global bool $DSQ_QUERY_COMMENTS
* @since ?
*/
$DSQ_QUERY_COMMENTS = false;
/**
* DISQUS array to store post_ids from WP_Query for comment JS output.
*
* @global array $DSQ_QUERY_POST_IDS
* @since 2.2
*/
$DSQ_QUERY_POST_IDS = array();
/**
* Helper functions.
*/
/**
* Tests if required options are configured to display the Disqus embed.
* @return bool
*/
function dsq_is_installed() {
return get_option('disqus_forum_url') && get_option('disqus_api_key');
}
/**
* @return bool
*/
function dsq_can_replace() {
global $id, $post;
if (get_option('disqus_active') === '0'){ return false; }
$replace = get_option('disqus_replace');
if ( is_feed() ) { return false; }
if ( 'draft' == $post->post_status ) { return false; }
if ( !get_option('disqus_forum_url') ) { return false; }
else if ( 'all' == $replace ) { return true; }
if ( !isset($post->comment_count) ) {
$num_comments = 0;
} else {
if ( 'empty' == $replace ) {
// Only get count of comments, not including pings.
// If there are comments, make sure there are comments (that are not track/pingbacks)
if ( $post->comment_count > 0 ) {
// Yuck, this causes a DB query for each post. This can be
// replaced with a lighter query, but this is still not optimal.
$comments = get_approved_comments($post->ID);
foreach ( $comments as $comment ) {
if ( $comment->comment_type != 'trackback' && $comment->comment_type != 'pingback' ) {
$num_comments++;
}
}
} else {
$num_comments = 0;
}
}
else {
$num_comments = $post->comment_count;
}
}
return ( ('empty' == $replace && 0 == $num_comments)
|| ('closed' == $replace && 'closed' == $post->comment_status) );
}
function dsq_manage_dialog($message, $error = false) {
global $wp_version;
echo '<div '
. ( $error ? 'id="disqus_warning" ' : '')
. 'class="updated fade'
. ( (version_compare($wp_version, '2.5', '<') && $error) ? '-ff0000' : '' )
. '"><p><strong>'
. $message
. '</strong></p></div>';
}
function dsq_sync_comments($comments) {
global $wpdb;
// user MUST be logged out during this process
wp_set_current_user(0);
// we need the thread_ids so we can map them to posts
$thread_map = array();
foreach ( $comments as $comment ) {
$thread_map[$comment->thread->id] = null;
}
$thread_ids = "'" . implode("', '", array_keys($thread_map)) . "'";
$results = $wpdb->get_results( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = 'dsq_thread_id' AND meta_value IN ({$thread_ids}) LIMIT 1");
foreach ( $results as $result ) {
$thread_map[$result->meta_value] = $result->post_id;
}
unset($result);
foreach ( $comments as $comment ) {
$ts = strtotime($comment->created_at);
if (!$thread_map[$comment->thread->id] && !empty($comment->thread->identifier)) {
// legacy threads dont already have their meta stored
foreach ( $comment->thread->identifier as $identifier ) {
// we know identifier starts with post_ID
if ($post_ID = (int)substr($identifier, 0, strpos($identifier, ' '))) {
$thread_map[$comment->thread->id] = $post_ID;
update_post_meta($post_ID, 'dsq_thread_id', $comment->thread->id);
if (DISQUS_DEBUG) {
echo "updated post {$post_ID}: dsq_thread_id set to {$comment->thread->id}\n";
}
}
}
unset($identifier);
}
if (!$thread_map[$comment->thread->id]) {
// shouldn't ever happen, but we can't be certain
if (DISQUS_DEBUG) {
if (!empty($comment->thread->identifier)) {
$idents = implode(', ', $comment->thread->identifier);
echo "skipped {$comment->id}: missing thread for identifiers ({$idents})\n";
} else {
echo "skipped {$comment->id}: missing thread (no identifier)\n";
}
}
continue;
}
$results = $wpdb->get_results($wpdb->prepare("SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = 'dsq_post_id' AND meta_value = %s LIMIT 1", $comment->id));
if (count($results)) {
// already exists
if (DISQUS_DEBUG) {
echo "skipped {$comment->id}: comment already exists\n";
}
if (count($results) > 1) {
// clean up duplicates -- fixes an issue where a race condition allowed comments to be synced multiple times
$results = array_slice($results, 1);
foreach ($results as $result) {
$wpdb->prepare("DELETE FROM $wpdb->commentmeta WHERE comment_id = %s LIMIT 1", $result);
}
}
continue;
}
$commentdata = false;
// first lets check by the id we have stored
if ($comment->meta) {
$meta = explode(';', $comment->meta);
foreach ($meta as $value) {
$value = explode('=', $value);
$meta[$value[0]] = $value[1];
}
unset($value);
if ($meta['wp_id']) {
$commentdata = $wpdb->get_row($wpdb->prepare( "SELECT comment_ID, comment_parent FROM $wpdb->comments WHERE comment_ID = %s LIMIT 1", $meta['wp_id']), ARRAY_A);
}
}
// skip comments that were imported but are missing meta information
if (!$commentdata && $comment->imported) {
if (DISQUS_DEBUG) {
echo "skipped {$comment->id}: comment not found and marked as imported\n";
}
continue;
}
// and follow up using legacy Disqus agent
if (!$commentdata) {
$commentdata = $wpdb->get_row($wpdb->prepare( "SELECT comment_ID, comment_parent FROM $wpdb->comments WHERE comment_agent = 'Disqus/1.0:{$comment->id}' LIMIT 1"), ARRAY_A);
}
if (!$commentdata) {
// Comment doesnt exist yet, lets insert it
if ($comment->status == 'approved') {
$approved = 1;
} elseif ($comment->status == 'spam') {
$approved = 'spam';
} else {
$approved = 0;
}
$commentdata = array(
'comment_post_ID' => $thread_map[$comment->thread->id],
'comment_date' => date('Y-m-d\TH:i:s', strtotime($comment->created_at) + (get_option('gmt_offset') * 3600)),
'comment_date_gmt' => $comment->created_at,
'comment_content' => apply_filters('pre_comment_content', $comment->message),
'comment_approved' => $approved,
'comment_agent' => 'Disqus/1.1('.DISQUS_VERSION.'):'.intval($comment->id),
'comment_type' => '',
);
if ($comment->is_anonymous) {
$commentdata['comment_author'] = $comment->anonymous_author->name;
$commentdata['comment_author_email'] = $comment->anonymous_author->email;
$commentdata['comment_author_url'] = $comment->anonymous_author->url;
$commentdata['comment_author_IP'] = $comment->ip_address;
} else {
if (!empty($comment->author->display_name)) {
$commentdata['comment_author'] = $comment->author->display_name;
} else {
$commentdata['comment_author'] = $comment->author->username;
}
$commentdata['comment_author_email'] = $comment->author->email;
$commentdata['comment_author_url'] = $comment->author->url;
$commentdata['comment_author_IP'] = $comment->ip_address;
}
$commentdata = wp_filter_comment($commentdata);
if ($comment->parent_post) {
$parent_id = $wpdb->get_var($wpdb->prepare( "SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = 'dsq_post_id' AND meta_value = %s LIMIT 1", $comment->parent_post));
if ($parent_id) {
$commentdata['comment_parent'] = $parent_id;
}
}
// due to a race condition we need to test again for coment existance
if ($wpdb->get_row($wpdb->prepare( "SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = 'dsq_post_id' AND meta_value = %s LIMIT 1", $comment->id))) {
// already exists
if (DISQUS_DEBUG) {
echo "skipped {$comment->id}: comment already exists (second check)\n";
}
continue;
}
$commentdata['comment_ID'] = wp_insert_comment($commentdata);
if (DISQUS_DEBUG) {
echo "inserted {$comment->id}: id is {$commentdata[comment_ID]}\n";
}
}
if (!$commentdata['comment_parent'] && $comment->parent_post) {
$parent_id = $wpdb->get_var($wpdb->prepare( "SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = 'dsq_post_id' AND meta_value = %s LIMIT 1", $comment->parent_post));
if ($parent_id) {
$wpdb->query($wpdb->prepare( "UPDATE $wpdb->comments SET comment_parent = %s WHERE comment_id = %s", $parent_id, $commentdata['comment_ID']));
if (DISQUS_DEBUG) {
echo "updated {$comment->id}: comment_parent changed to {$parent_id}\n";
}
}
}
$comment_id = $commentdata['comment_ID'];
update_comment_meta($comment_id, 'dsq_parent_post_id', $comment->parent_post);
update_comment_meta($comment_id, 'dsq_post_id', $comment->id);
}
unset($comment);
if( isset($_POST['dsq_api_key']) && $_POST['dsq_api_key'] == get_option('disqus_api_key') ) {
if( isset($_GET['dsq_sync_action']) && isset($_GET['dsq_sync_comment_id']) ) {
$comment_parts = explode('=', $_GET['dsq_sync_comment_id']);
if (!($comment_id = intval($comment_parts[1])) > 0) {
return;
}
if( 'wp_id' != $comment_parts[0] ) {
$comment_id = $wpdb->get_var($wpdb->prepare('SELECT comment_ID FROM ' . $wpdb->comments . ' WHERE comment_post_ID = %d AND comment_agent LIKE %s', intval($post->ID), 'Disqus/1.0:' . $comment_id));
}
switch( $_GET['dsq_sync_action'] ) {
case 'mark_spam':
wp_set_comment_status($comment_id, 'spam');
echo "<!-- dsq_sync: wp_set_comment_status($comment_id, 'spam') -->";
break;
case 'mark_approved':
wp_set_comment_status($comment_id, 'approve');
echo "<!-- dsq_sync: wp_set_comment_status($comment_id, 'approve') -->";
break;
case 'mark_killed':
wp_set_comment_status($comment_id, 'hold');
echo "<!-- dsq_sync: wp_set_comment_status($comment_id, 'hold') -->";
break;
}
}
}
}
function dsq_request_handler() {
global $dsq_response;
global $dsq_api;
global $post;
global $wpdb;
if (!empty($_GET['cf_action'])) {
switch ($_GET['cf_action']) {
case 'sync_comments':
if( !( $post_id = $_GET['post_id'] ) ) {
header("HTTP/1.0 400 Bad Request");
die();
}
// schedule the event for 5 minutes from now in case they
// happen to make a quick post
dsq_add_pending_post_id($post_id);
if (DISQUS_DEBUG) {
$response = dsq_sync_forum();
if (!$response) {
die('// error: '.$dsq_api->get_last_error());
} else {
list($last_comment_id, $comments) = $response;
die('// synced '.$comments.' comments');
}
} else {
$ts = time() + 300;
wp_schedule_single_event($ts, 'dsq_sync_forum');
die('// sync scheduled');
}
break;
case 'export_comments':
if (current_user_can('manage_options') && DISQUS_CAN_EXPORT) {
$timestamp = intval($_GET['timestamp']);
$post_id = intval($_GET['post_id']);
global $wpdb, $dsq_api;
$post = $wpdb->get_results($wpdb->prepare("
SELECT *
FROM $wpdb->posts
WHERE post_type != 'revision'
AND post_status = 'publish'
AND comment_count > 0
AND ID > %d
ORDER BY ID ASC
LIMIT 1
", $post_id));
$post = $post[0];
$post_id = $post->ID;
$max_post_id = $wpdb->get_var($wpdb->prepare("
SELECT MAX(ID)
FROM $wpdb->posts
WHERE post_type != 'revision'
AND post_status = 'publish'
AND comment_count > 0
", $post_id));
$eof = (int)($post_id == $max_post_id);
if ($eof) {
$status = 'complete';
$msg = dsq_i('Your comments have been sent to Disqus and queued for import!<br/><a href="'.DISQUS_IMPORTER_URL.'" target="_blank">See the status of your import at Disqus</a>');
}
else {
$status = 'partial';
$msg = dsq_i('Processed comments on post #%s…', $post_id);
}
$result = 'fail';
$response = null;
if ($post) {
require_once(dirname(__FILE__) . '/export.php');
$wxr = dsq_export_wp($post);
$response = $dsq_api->import_wordpress_comments($wxr, $timestamp, $eof);
if (!($response['group_id'] > 0)) {
$result = 'fail';
$msg = '<p class="status dsq-export-fail">'. dsq_i('Sorry, something unexpected happened with the export. Please <a href="#" id="dsq_export_retry">try again</a></p><p>If your API key has changed, you may need to reinstall Disqus (deactivate the plugin and then reactivate it). If you are still having issues, refer to the <a href="%s" onclick="window.open(this.href); return false">WordPress help page</a>.', 'http://disqus.com/help/wordpress'). '</p>';
$response = $dsq_api->get_last_error();
}
else {
if ($eof) {
$msg = dsq_i('Your comments have been sent to Disqus and queued for import!<br/><a href="%s" target="_blank">See the status of your import at Disqus</a>', $response['link']);
}
$result = 'success';
}
}
// send AJAX response
$response = compact('result', 'timestamp', 'status', 'post_id', 'msg', 'eof', 'response');
header('Content-type: text/javascript');
echo cf_json_encode($response);
die();
}
break;
case 'import_comments':
if (current_user_can('manage_options')) {
if (!isset($_GET['last_comment_id'])) $last_comment_id = false;
else $last_comment_id = $_GET['last_comment_id'];
if ($_GET['wipe'] == '1') {
$wpdb->query("DELETE FROM `".$wpdb->prefix."commentmeta` WHERE meta_key IN ('dsq_post_id', 'dsq_parent_post_id')");
$wpdb->query("DELETE FROM `".$wpdb->prefix."comments` WHERE comment_agent LIKE 'Disqus/%%'");
}
ob_start();
$response = dsq_sync_forum($last_comment_id, true);
$debug = ob_get_clean();
if (!$response) {
$status = 'error';
$result = 'fail';
$error = $dsq_api->get_last_error();
$msg = '<p class="status dsq-export-fail">'.dsq_i('There was an error downloading your comments from Disqus.').'<br/>'.htmlspecialchars($error).'</p>';
} else {
list($comments, $last_comment_id) = $response;
if (!$comments) {
$status = 'complete';
$msg = dsq_i('Your comments have been downloaded from Disqus and saved in your local database.');
} else {
$status = 'partial';
$msg = dsq_i('Import in progress (last post id: %s) …', $last_comment_id);
}
$result = 'success';
}
$debug = explode("\n", $debug);
$response = compact('result', 'status', 'comments', 'msg', 'last_comment_id', 'debug');
header('Content-type: text/javascript');
echo cf_json_encode($response);
die();
}
break;
}
}
}
add_action('init', 'dsq_request_handler');
/**
* @param string $option_name
*/
function dsq_image_upload_handler($option_name) {
// If the upload field has a file in it
if(isset($_FILES[$option_name]) && ($_FILES[$option_name]['size'] > 0)) {
// Get the type of the uploaded file. This is returned as "type/extension"
$arr_file_type = wp_check_filetype(basename($_FILES[$option_name]['name']));
$uploaded_file_type = $arr_file_type['type'];
// Set an array containing a list of acceptable formats
$allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png','image/x-icon');
// If the uploaded file is the right format
if(in_array($uploaded_file_type, $allowed_file_types)) {
// Options array for the wp_handle_upload function. 'test_upload' => false
$upload_overrides = array( 'test_form' => false );
// Handle the upload using WP's wp_handle_upload function. Takes the posted file and an options array
$uploaded_file = wp_handle_upload($_FILES[$option_name], $upload_overrides);
// If the wp_handle_upload call returned a local path for the image
if(isset($uploaded_file['url'])) {
update_option($option_name, $uploaded_file['url']);
}
}
}
}
function dsq_add_pending_post_id($post_id) {
update_post_meta($post_id, 'dsq_needs_sync', '1', $unique=true);
}
function dsq_get_pending_post_ids() {
global $wpdb;
$results = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'dsq_needs_sync'");
$post_ids = array();
foreach ($results as $result) {
$post_ids[] = $result->post_id;
}
return $post_ids;
}
function dsq_clear_pending_post_ids($post_ids) {
global $wpdb;
$post_ids_query = "'" . implode("', '", $post_ids) . "'";
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = 'dsq_needs_sync' AND post_id IN ({$post_ids_query})");
update_meta_cache('dsq_needs_sync', $post_ids);
}
function dsq_sync_post($post_id) {
global $dsq_api, $wpdb;
$post = get_post($post_id);
// Call update_thread to ensure our permalink is up to date
dsq_update_permalink($post);
}
function dsq_sync_forum($last_comment_id=false, $force=false) {
global $dsq_api, $wpdb;
set_time_limit(DISQUS_SYNC_TIMEOUT);
if ($force) {
$sync_time = null;
} else {
$sync_time = (int)get_option('_disqus_sync_lock');
}
// lock expires after 1 hour
if ($sync_time && $sync_time > time() - 60*60) {
$dsq_api->api->last_error = 'Sync already in progress (lock found)';
return false;
} else {
update_option('_disqus_sync_lock', time());
}
// sync all pending posts
$post_ids = dsq_get_pending_post_ids();
dsq_clear_pending_post_ids($post_ids);
foreach ($post_ids as $post_id) {
dsq_sync_post($post_id);
}
if ($last_comment_id === false) {
$last_comment_id = get_option('disqus_last_comment_id');
if (!$last_comment_id) {
$last_comment_id = 0;
}
}
if ($last_comment_id) {
$last_comment_id++;
}
//$last_comment_id = 0;
// Pull comments from API
$dsq_response = $dsq_api->get_forum_posts($last_comment_id);
if( $dsq_response < 0 || $dsq_response === false ) {
return false;
}
// Sync comments with database.
dsq_sync_comments($dsq_response);
$total = 0;
if ($dsq_response) {
foreach ($dsq_response as $comment) {
$total += 1;
if ($comment->id > $last_comment_id) $last_comment_id = $comment->id;
}
if ($last_comment_id > get_option('disqus_last_comment_id')) {
update_option('disqus_last_comment_id', $last_comment_id);
}
}
unset($comment);
delete_option('_disqus_sync_lock');
return array($total, $last_comment_id);
}
add_action('dsq_sync_forum', 'dsq_sync_forum');
function dsq_update_permalink($post) {
global $dsq_api;
if (DISQUS_DEBUG) {
echo "updating post on disqus: {$post->ID}\n";
}
$response = $dsq_api->api->update_thread(null, array(
'thread_identifier' => dsq_identifier_for_post($post),
'title' => dsq_title_for_post($post),
'url' => dsq_link_for_post($post)
));
update_post_meta($post->ID, 'dsq_thread_id', $response->id);
return $response;
}
/**
* Compatibility
*/
if (!function_exists ( '_wp_specialchars' ) ) {
function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
$string = (string) $string;
if ( 0 === strlen( $string ) ) {
return '';
}
// Don't bother if there are no specialchars - saves some processing
if ( !preg_match( '/[&<>"\']/', $string ) ) {
return $string;
}
// Account for the previous behaviour of the function when the $quote_style is not an accepted value
if ( empty( $quote_style ) ) {
$quote_style = ENT_NOQUOTES;
} elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
$quote_style = ENT_QUOTES;
}
// Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
if ( !$charset ) {
static $_charset;
if ( !isset( $_charset ) ) {
$alloptions = wp_load_alloptions();
$_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
}
$charset = $_charset;
}
if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
$charset = 'UTF-8';
}
$_quote_style = $quote_style;
if ( $quote_style === 'double' ) {
$quote_style = ENT_COMPAT;
$_quote_style = ENT_COMPAT;
} elseif ( $quote_style === 'single' ) {
$quote_style = ENT_NOQUOTES;
}
// Handle double encoding ourselves
if ( !$double_encode ) {
$string = wp_specialchars_decode( $string, $_quote_style );
$string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
}
$string = @htmlspecialchars( $string, $quote_style, $charset );
// Handle double encoding ourselves
if ( !$double_encode ) {
$string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
}
// Backwards compatibility
if ( 'single' === $_quote_style ) {
$string = str_replace( "'", ''', $string );
}
return $string;
}
}
if (!function_exists ( 'wp_check_invalid_utf8' ) ) {
function wp_check_invalid_utf8( $string, $strip = false ) {
$string = (string) $string;
if ( 0 === strlen( $string ) ) {
return '';
}
// Store the site charset as a static to avoid multiple calls to get_option()
static $is_utf8;
if ( !isset( $is_utf8 ) ) {
$is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
}
if ( !$is_utf8 ) {
return $string;
}
// Check for support for utf8 in the installed PCRE library once and store the result in a static
static $utf8_pcre;
if ( !isset( $utf8_pcre ) ) {
$utf8_pcre = @preg_match( '/^./u', 'a' );
}
// We can't demand utf8 in the PCRE installation, so just return the string in those cases
if ( !$utf8_pcre ) {
return $string;
}
// preg_match fails when it encounters invalid UTF8 in $string
if ( 1 === @preg_match( '/^./us', $string ) ) {
return $string;
}
// Attempt to strip the bad chars if requested (not recommended)
if ( $strip && function_exists( 'iconv' ) ) {
return iconv( 'utf-8', 'utf-8', $string );
}
return '';
}
}
if (!function_exists ( 'esc_html' ) ) {
function esc_html( $text ) {
$safe_text = wp_check_invalid_utf8( $text );
$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
return apply_filters( 'esc_html', $safe_text, $text );
}
}
if (!function_exists ( 'esc_attr' ) ) {
function esc_attr( $text ) {
$safe_text = wp_check_invalid_utf8( $text );
$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
return apply_filters( 'attribute_escape', $safe_text, $text );
}
}
/**
* Filters/Actions
*/
// ugly global hack for comments closing
$EMBED = false;
function dsq_comments_template($value) {
global $EMBED;
global $post;
global $comments;
if ( !( is_singular() && ( have_comments() || 'open' == $post->comment_status ) ) ) {
return;
}
if ( !dsq_is_installed() || !dsq_can_replace() ) {
return $value;
}
// TODO: If a disqus-comments.php is found in the current template's
// path, use that instead of the default bundled comments.php
//return TEMPLATEPATH . '/disqus-comments.php';
$EMBED = true;
return dirname(__FILE__) . '/comments.php';
}
function dsq_comment( $comment, $args, $depth ) {
$GLOBALS['comment'] = $comment;
switch ($comment->comment_type):
case '' :
?>
<li <?php comment_class(); ?> id="dsq-comment-<?php echo comment_ID(); ?>">
<div id="dsq-comment-header-<?php echo comment_ID(); ?>" class="dsq-comment-header">
<cite id="dsq-cite-<?php echo comment_ID(); ?>">
<?php if(comment_author_url()) : ?>
<a id="dsq-author-user-<?php echo comment_ID(); ?>" href="<?php echo comment_author_url(); ?>" target="_blank" rel="nofollow"><?php echo comment_author(); ?></a>
<?php else : ?>
<span id="dsq-author-user-<?php echo comment_ID(); ?>"><?php echo comment_author(); ?></span>
<?php endif; ?>
</cite>
</div>
<div id="dsq-comment-body-<?php echo comment_ID(); ?>" class="dsq-comment-body">
<div id="dsq-comment-message-<?php echo comment_ID(); ?>" class="dsq-comment-message"><?php echo wp_filter_kses(comment_text()); ?></div>
</div>
<?php
break;
case 'pingback' :
case 'trackback' :
?>
<li class="post pingback">
<p><?php echo dsq_i('Pingback:'); ?> <?php comment_author_link(); ?><?php edit_comment_link(dsq_i('(Edit)'), ' '); ?></p>
</li>
<?php
break;
endswitch;
}
// Mark entries in index to replace comments link.
// As of WordPress 3.1 this is required to return a numerical value
function dsq_comments_number($count) {
global $post;
return $count;
}
function dsq_comments_text($comment_text) {
global $post;
if ( dsq_can_replace() ) {
return '<span class="dsq-postid" rel="'.htmlspecialchars(dsq_identifier_for_post($post)).'">'.$comment_text.'</span>';
} else {
return $comment_text;
}
}
function dsq_bloginfo_url($url) {
if ( get_feed_link('comments_rss2') == $url && dsq_can_replace() ) {
return 'http://' . strtolower(get_option('disqus_forum_url')) . '.' . DISQUS_DOMAIN . DISQUS_RSS_PATH;
} else {
return $url;
}
}
function dsq_plugin_action_links($links, $file) {
$plugin_file = basename(__FILE__);
if (basename($file) == $plugin_file) {
if (!dsq_is_installed()) {
$settings_link = '<a href="edit-comments.php?page=disqus">'.dsq_i('Configure').'</a>';
} else {
$settings_link = '<a href="edit-comments.php?page=disqus#adv">'.dsq_i('Settings').'</a>';
}
array_unshift($links, $settings_link);
}
return $links;
}
add_filter('plugin_action_links', 'dsq_plugin_action_links', 10, 2);
/**
* Hide the default comment form to stop spammers by marking all comments
* as closed.
*/
function dsq_comments_open($open, $post_id=null) {
global $EMBED;
if ($EMBED) return false;
return $open;
}
add_filter('comments_open', 'dsq_comments_open');
// Always add Disqus management page to the admin menu
function dsq_add_pages() {
add_submenu_page(
'edit-comments.php',
'Disqus',
'Disqus',
'moderate_comments',
'disqus',
'dsq_manage'
);
}
add_action('admin_menu', 'dsq_add_pages', 10);
// a little jQuery goodness to get comments menu working as desired
function dsq_menu_admin_head() {
?>
<script type="text/javascript">
jQuery(function($) {
// fix menu
var mc = $('#menu-comments');
mc.find('a.wp-has-submenu').attr('href', 'edit-comments.php?page=disqus').end().find('.wp-submenu li:has(a[href="edit-comments.php?page=disqus"])').prependTo(mc.find('.wp-submenu ul'));
// fix admin bar
$('#wp-admin-bar-comments').find('a.ab-item').attr('href', 'edit-comments.php?page=disqus');
});
</script>
<?php
}
add_action('admin_head', 'dsq_menu_admin_head');
// only active on dashboard
function dsq_dash_comment_counts() {
global $wpdb;
// taken from wp-includes/comment.php - WP 2.8.5
$count = $wpdb->get_results("
SELECT comment_approved, COUNT( * ) AS num_comments
FROM {$wpdb->comments}
WHERE comment_type != 'trackback'
AND comment_type != 'pingback'
GROUP BY comment_approved
", ARRAY_A );
$total = 0;
$approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam');
$known_types = array_keys( $approved );
foreach( (array) $count as $row_num => $row ) {
$total += $row['num_comments'];
if ( in_array( $row['comment_approved'], $known_types ) && array_key_exists($row['comment_approved'], $approved) )
$stats[$approved[$row['comment_approved']]] = $row['num_comments'];
}
$stats['total_comments'] = $total;
foreach ( $approved as $key ) {
if ( empty($stats[$key]) )
$stats[$key] = 0;
}
$stats = (object) $stats;
?>
<script type="text/javascript">
jQuery(function($) {
$('#dashboard_right_now').find('.b-comments a').html('<?php echo number_format($stats->total_comments); ?>').end().find('.b_approved a').html('<?php echo number_format($stats->approved); ?>').end().find('.b-waiting a').html('<?php echo number_format($stats->moderated); ?>').end().find('.b-spam a').html('<?php echo number_format($stats->spam); ?>');
$('#dashboard_recent_comments div.trackback').remove();
$('#dashboard_right_now .inside table td.last a, #dashboard_recent_comments .inside .textright a.button').attr('href', 'edit-comments.php?page=disqus');
});
</script>
<?php
}
function dsq_wp_dashboard_setup() {
add_action('admin_head', 'dsq_dash_comment_counts');
}
add_action('wp_dashboard_setup', 'dsq_wp_dashboard_setup');
function dsq_manage() {
if (dsq_does_need_update() && isset($_POST['upgrade'])) {
dsq_install();
}
if (dsq_does_need_update() && isset($_POST['reset'])) {
include_once(dirname(__FILE__) . '/upgrade.php');
} else {
include_once(dirname(__FILE__) . '/manage.php');
}
}
function dsq_admin_head() {
if (isset($_GET['page']) && $_GET['page'] == 'disqus') {
?>
<link rel='stylesheet' href='<?php echo DSQ_PLUGIN_URL; ?>/media/styles/manage.css' type='text/css' />
<style type="text/css">
.dsq-importing, .dsq-imported, .dsq-import-fail, .dsq-exporting, .dsq-exported, .dsq-export-fail {
background: url(<?php echo admin_url('images/loading.gif'); ?>) left center no-repeat;
line-height: 16px;
padding-left: 20px;
}
p.status {
padding-top: 0;
padding-bottom: 0;
margin: 0;
}
.dsq-imported, .dsq-exported {
background: url(<?php echo admin_url('images/yes.png'); ?>) left center no-repeat;
}
.dsq-import-fail, .dsq-export-fail {
background: url(<?php echo admin_url('images/no.png'); ?>) left center no-repeat;
}
</style>
<script type="text/javascript">
jQuery(function($) {