PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/disqus-comment-system/disqus.php

https://bitbucket.org/mihteh/mihteh.com-wp
PHP | 1538 lines | 1324 code | 105 blank | 109 comment | 175 complexity | 1aa99d9e5a99c4d2e980214817f45707 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-2.0, GPL-3.0, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. Plugin Name: Disqus Comment System
  4. Plugin URI: http://disqus.com/
  5. 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.
  6. Author: Disqus <team@disqus.com>
  7. Version: 2.73
  8. Author URI: http://disqus.com/
  9. */
  10. /*.
  11. require_module 'standard';
  12. require_module 'pcre';
  13. require_module 'mysql';
  14. .*/
  15. require_once(dirname(__FILE__) . '/lib/wp-api.php');
  16. if (defined('DISQUS_LOCAL')) { // DISQUS defines this for local development purposes
  17. define('DISQUS_DOMAIN', 'dev.disqus.org:8000');
  18. define('DISQUS_IMPORTER_URL', 'http://dev.disqus.org:8001/');
  19. } else {
  20. define('DISQUS_DOMAIN', 'disqus.com');
  21. define('DISQUS_IMPORTER_URL', 'http://import.disqus.com/');
  22. }
  23. define('DISQUS_URL', 'http://' . DISQUS_DOMAIN . '/');
  24. define('DISQUS_MEDIA_URL', 'http://' . DISQUS_DOMAIN . '/media/');
  25. define('DISQUS_API_URL', 'http://' . DISQUS_DOMAIN . '/api/');
  26. define('DISQUS_RSS_PATH', '/latest.rss');
  27. define('DISQUS_CAN_EXPORT', is_file(dirname(__FILE__) . '/export.php'));
  28. if (!defined('DISQUS_DEBUG')) {
  29. define('DISQUS_DEBUG', false);
  30. }
  31. define('DISQUS_VERSION', '2.73');
  32. define('DISQUS_SYNC_TIMEOUT', 30);
  33. /**
  34. * Returns an array of all option identifiers used by DISQUS.
  35. * @return array[int]string
  36. */
  37. function dsq_options() {
  38. return array(
  39. '_disqus_sync_lock',
  40. '_disqus_sync_post_ids',
  41. # render disqus in the embed
  42. 'disqus_active',
  43. 'disqus_forum_url',
  44. 'disqus_api_key',
  45. 'disqus_user_api_key',
  46. 'disqus_replace',
  47. 'disqus_cc_fix',
  48. # SSO features
  49. 'disqus_partner_key',
  50. 'disqus_public_key',
  51. 'disqus_secret_key',
  52. 'disqus_sso_button',
  53. 'disqus_sso_icon',
  54. # disables automatic sync via cron
  55. 'disqus_manual_sync',
  56. # disables server side rendering
  57. 'disqus_disable_ssr',
  58. # the last sync comment id (from get_forum_posts)
  59. 'disqus_last_comment_id',
  60. 'disqus_version',
  61. );
  62. }
  63. /**
  64. * @param string $file
  65. * @return string
  66. */
  67. function dsq_plugin_basename($file) {
  68. $file = dirname($file);
  69. // From WP2.5 wp-includes/plugin.php:plugin_basename()
  70. $file = str_replace('\\','/',$file); // sanitize for Win32 installs
  71. $file = preg_replace('|/+|','/', $file); // remove any duplicate slash
  72. $file = preg_replace('|^.*/' . PLUGINDIR . '/|','',$file); // get relative path from plugins dir
  73. if ( strstr($file, '/') === false ) {
  74. return $file;
  75. }
  76. $pieces = explode('/', $file);
  77. return !empty($pieces[count($pieces)-1]) ? $pieces[count($pieces)-1] : $pieces[count($pieces)-2];
  78. }
  79. if ( !defined('WP_CONTENT_URL') ) {
  80. define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content');
  81. }
  82. if ( !defined('PLUGINDIR') ) {
  83. define('PLUGINDIR', 'wp-content/plugins'); // Relative to ABSPATH. For back compat.
  84. }
  85. define('DSQ_PLUGIN_URL', WP_CONTENT_URL . '/plugins/' . dsq_plugin_basename(__FILE__));
  86. $mt_disqus_version = '2.01';
  87. /**
  88. * Response from Disqus get_thread API call for comments template.
  89. *
  90. * @global string $dsq_response
  91. * @since 1.0
  92. */
  93. $dsq_response = '';
  94. /**
  95. * Disqus API instance.
  96. *
  97. * @global string $dsq_api
  98. * @since 1.0
  99. */
  100. $dsq_api = new DisqusWordPressAPI(get_option('disqus_forum_url'), get_option('disqus_api_key'));
  101. /**
  102. * DISQUS currently unsupported dev toggle to output comments for this query.
  103. *
  104. * @global bool $DSQ_QUERY_COMMENTS
  105. * @since ?
  106. */
  107. $DSQ_QUERY_COMMENTS = false;
  108. /**
  109. * DISQUS array to store post_ids from WP_Query for comment JS output.
  110. *
  111. * @global array $DSQ_QUERY_POST_IDS
  112. * @since 2.2
  113. */
  114. $DSQ_QUERY_POST_IDS = array();
  115. /**
  116. * Helper functions.
  117. */
  118. /**
  119. * Tests if required options are configured to display the Disqus embed.
  120. * @return bool
  121. */
  122. function dsq_is_installed() {
  123. return get_option('disqus_forum_url') && get_option('disqus_api_key');
  124. }
  125. /**
  126. * @return bool
  127. */
  128. function dsq_can_replace() {
  129. global $id, $post;
  130. if (get_option('disqus_active') === '0'){ return false; }
  131. $replace = get_option('disqus_replace');
  132. if ( is_feed() ) { return false; }
  133. if ( 'draft' == $post->post_status ) { return false; }
  134. if ( !get_option('disqus_forum_url') ) { return false; }
  135. else if ( 'all' == $replace ) { return true; }
  136. if ( !isset($post->comment_count) ) {
  137. $num_comments = 0;
  138. } else {
  139. if ( 'empty' == $replace ) {
  140. // Only get count of comments, not including pings.
  141. // If there are comments, make sure there are comments (that are not track/pingbacks)
  142. if ( $post->comment_count > 0 ) {
  143. // Yuck, this causes a DB query for each post. This can be
  144. // replaced with a lighter query, but this is still not optimal.
  145. $comments = get_approved_comments($post->ID);
  146. foreach ( $comments as $comment ) {
  147. if ( $comment->comment_type != 'trackback' && $comment->comment_type != 'pingback' ) {
  148. $num_comments++;
  149. }
  150. }
  151. } else {
  152. $num_comments = 0;
  153. }
  154. }
  155. else {
  156. $num_comments = $post->comment_count;
  157. }
  158. }
  159. return ( ('empty' == $replace && 0 == $num_comments)
  160. || ('closed' == $replace && 'closed' == $post->comment_status) );
  161. }
  162. function dsq_manage_dialog($message, $error = false) {
  163. global $wp_version;
  164. echo '<div '
  165. . ( $error ? 'id="disqus_warning" ' : '')
  166. . 'class="updated fade'
  167. . ( (version_compare($wp_version, '2.5', '<') && $error) ? '-ff0000' : '' )
  168. . '"><p><strong>'
  169. . $message
  170. . '</strong></p></div>';
  171. }
  172. function dsq_sync_comments($comments) {
  173. global $wpdb;
  174. // user MUST be logged out during this process
  175. wp_set_current_user(0);
  176. // we need the thread_ids so we can map them to posts
  177. $thread_map = array();
  178. foreach ( $comments as $comment ) {
  179. $thread_map[$comment->thread->id] = null;
  180. }
  181. $thread_ids = "'" . implode("', '", array_keys($thread_map)) . "'";
  182. $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");
  183. foreach ( $results as $result ) {
  184. $thread_map[$result->meta_value] = $result->post_id;
  185. }
  186. unset($result);
  187. foreach ( $comments as $comment ) {
  188. $ts = strtotime($comment->created_at);
  189. if (!$thread_map[$comment->thread->id] && !empty($comment->thread->identifier)) {
  190. // legacy threads dont already have their meta stored
  191. foreach ( $comment->thread->identifier as $identifier ) {
  192. // we know identifier starts with post_ID
  193. if ($post_ID = (int)substr($identifier, 0, strpos($identifier, ' '))) {
  194. $thread_map[$comment->thread->id] = $post_ID;
  195. update_post_meta($post_ID, 'dsq_thread_id', $comment->thread->id);
  196. if (DISQUS_DEBUG) {
  197. echo "updated post {$post_ID}: dsq_thread_id set to {$comment->thread->id}\n";
  198. }
  199. }
  200. }
  201. unset($identifier);
  202. }
  203. if (!$thread_map[$comment->thread->id]) {
  204. // shouldn't ever happen, but we can't be certain
  205. if (DISQUS_DEBUG) {
  206. if (!empty($comment->thread->identifier)) {
  207. $idents = implode(', ', $comment->thread->identifier);
  208. echo "skipped {$comment->id}: missing thread for identifiers ({$idents})\n";
  209. } else {
  210. echo "skipped {$comment->id}: missing thread (no identifier)\n";
  211. }
  212. }
  213. continue;
  214. }
  215. $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));
  216. if (count($results)) {
  217. // already exists
  218. if (DISQUS_DEBUG) {
  219. echo "skipped {$comment->id}: comment already exists\n";
  220. }
  221. if (count($results) > 1) {
  222. // clean up duplicates -- fixes an issue where a race condition allowed comments to be synced multiple times
  223. $results = array_slice($results, 1);
  224. foreach ($results as $result) {
  225. $wpdb->prepare("DELETE FROM $wpdb->commentmeta WHERE comment_id = %s LIMIT 1", $result);
  226. }
  227. }
  228. continue;
  229. }
  230. $commentdata = false;
  231. // first lets check by the id we have stored
  232. if ($comment->meta) {
  233. $meta = explode(';', $comment->meta);
  234. foreach ($meta as $value) {
  235. $value = explode('=', $value);
  236. $meta[$value[0]] = $value[1];
  237. }
  238. unset($value);
  239. if ($meta['wp_id']) {
  240. $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);
  241. }
  242. }
  243. // skip comments that were imported but are missing meta information
  244. if (!$commentdata && $comment->imported) {
  245. if (DISQUS_DEBUG) {
  246. echo "skipped {$comment->id}: comment not found and marked as imported\n";
  247. }
  248. continue;
  249. }
  250. // and follow up using legacy Disqus agent
  251. if (!$commentdata) {
  252. $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);
  253. }
  254. if (!$commentdata) {
  255. // Comment doesnt exist yet, lets insert it
  256. if ($comment->status == 'approved') {
  257. $approved = 1;
  258. } elseif ($comment->status == 'spam') {
  259. $approved = 'spam';
  260. } else {
  261. $approved = 0;
  262. }
  263. $commentdata = array(
  264. 'comment_post_ID' => $thread_map[$comment->thread->id],
  265. 'comment_date' => date('Y-m-d\TH:i:s', strtotime($comment->created_at) + (get_option('gmt_offset') * 3600)),
  266. 'comment_date_gmt' => $comment->created_at,
  267. 'comment_content' => apply_filters('pre_comment_content', $comment->message),
  268. 'comment_approved' => $approved,
  269. 'comment_agent' => 'Disqus/1.1('.DISQUS_VERSION.'):'.intval($comment->id),
  270. 'comment_type' => '',
  271. );
  272. if ($comment->is_anonymous) {
  273. $commentdata['comment_author'] = $comment->anonymous_author->name;
  274. $commentdata['comment_author_email'] = $comment->anonymous_author->email;
  275. $commentdata['comment_author_url'] = $comment->anonymous_author->url;
  276. $commentdata['comment_author_IP'] = $comment->ip_address;
  277. } else {
  278. if (!empty($comment->author->display_name)) {
  279. $commentdata['comment_author'] = $comment->author->display_name;
  280. } else {
  281. $commentdata['comment_author'] = $comment->author->username;
  282. }
  283. $commentdata['comment_author_email'] = $comment->author->email;
  284. $commentdata['comment_author_url'] = $comment->author->url;
  285. $commentdata['comment_author_IP'] = $comment->ip_address;
  286. }
  287. $commentdata = wp_filter_comment($commentdata);
  288. if ($comment->parent_post) {
  289. $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));
  290. if ($parent_id) {
  291. $commentdata['comment_parent'] = $parent_id;
  292. }
  293. }
  294. // due to a race condition we need to test again for coment existance
  295. 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))) {
  296. // already exists
  297. if (DISQUS_DEBUG) {
  298. echo "skipped {$comment->id}: comment already exists (second check)\n";
  299. }
  300. continue;
  301. }
  302. $commentdata['comment_ID'] = wp_insert_comment($commentdata);
  303. if (DISQUS_DEBUG) {
  304. echo "inserted {$comment->id}: id is {$commentdata[comment_ID]}\n";
  305. }
  306. }
  307. if (!$commentdata['comment_parent'] && $comment->parent_post) {
  308. $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));
  309. if ($parent_id) {
  310. $wpdb->query($wpdb->prepare( "UPDATE $wpdb->comments SET comment_parent = %s WHERE comment_id = %s", $parent_id, $commentdata['comment_ID']));
  311. if (DISQUS_DEBUG) {
  312. echo "updated {$comment->id}: comment_parent changed to {$parent_id}\n";
  313. }
  314. }
  315. }
  316. $comment_id = $commentdata['comment_ID'];
  317. update_comment_meta($comment_id, 'dsq_parent_post_id', $comment->parent_post);
  318. update_comment_meta($comment_id, 'dsq_post_id', $comment->id);
  319. }
  320. unset($comment);
  321. if( isset($_POST['dsq_api_key']) && $_POST['dsq_api_key'] == get_option('disqus_api_key') ) {
  322. if( isset($_GET['dsq_sync_action']) && isset($_GET['dsq_sync_comment_id']) ) {
  323. $comment_parts = explode('=', $_GET['dsq_sync_comment_id']);
  324. if (!($comment_id = intval($comment_parts[1])) > 0) {
  325. return;
  326. }
  327. if( 'wp_id' != $comment_parts[0] ) {
  328. $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));
  329. }
  330. switch( $_GET['dsq_sync_action'] ) {
  331. case 'mark_spam':
  332. wp_set_comment_status($comment_id, 'spam');
  333. echo "<!-- dsq_sync: wp_set_comment_status($comment_id, 'spam') -->";
  334. break;
  335. case 'mark_approved':
  336. wp_set_comment_status($comment_id, 'approve');
  337. echo "<!-- dsq_sync: wp_set_comment_status($comment_id, 'approve') -->";
  338. break;
  339. case 'mark_killed':
  340. wp_set_comment_status($comment_id, 'hold');
  341. echo "<!-- dsq_sync: wp_set_comment_status($comment_id, 'hold') -->";
  342. break;
  343. }
  344. }
  345. }
  346. }
  347. function dsq_request_handler() {
  348. global $dsq_response;
  349. global $dsq_api;
  350. global $post;
  351. global $wpdb;
  352. if (!empty($_GET['cf_action'])) {
  353. switch ($_GET['cf_action']) {
  354. case 'sync_comments':
  355. if( !( $post_id = $_GET['post_id'] ) ) {
  356. header("HTTP/1.0 400 Bad Request");
  357. die();
  358. }
  359. // schedule the event for 5 minutes from now in case they
  360. // happen to make a quick post
  361. dsq_add_pending_post_id($post_id);
  362. if (DISQUS_DEBUG) {
  363. $response = dsq_sync_forum();
  364. if (!$response) {
  365. die('// error: '.$dsq_api->get_last_error());
  366. } else {
  367. list($last_comment_id, $comments) = $response;
  368. die('// synced '.$comments.' comments');
  369. }
  370. } else {
  371. $ts = time() + 300;
  372. wp_schedule_single_event($ts, 'dsq_sync_forum');
  373. die('// sync scheduled');
  374. }
  375. break;
  376. case 'export_comments':
  377. if (current_user_can('manage_options') && DISQUS_CAN_EXPORT) {
  378. $timestamp = intval($_GET['timestamp']);
  379. $post_id = intval($_GET['post_id']);
  380. global $wpdb, $dsq_api;
  381. $post = $wpdb->get_results($wpdb->prepare("
  382. SELECT *
  383. FROM $wpdb->posts
  384. WHERE post_type != 'revision'
  385. AND post_status = 'publish'
  386. AND comment_count > 0
  387. AND ID > %d
  388. ORDER BY ID ASC
  389. LIMIT 1
  390. ", $post_id));
  391. $post = $post[0];
  392. $post_id = $post->ID;
  393. $max_post_id = $wpdb->get_var($wpdb->prepare("
  394. SELECT MAX(ID)
  395. FROM $wpdb->posts
  396. WHERE post_type != 'revision'
  397. AND post_status = 'publish'
  398. AND comment_count > 0
  399. ", $post_id));
  400. $eof = (int)($post_id == $max_post_id);
  401. if ($eof) {
  402. $status = 'complete';
  403. $msg = '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>';
  404. }
  405. else {
  406. $status = 'partial';
  407. $msg = dsq_i('Processed comments on post #%s&hellip;', $post_id);
  408. }
  409. $result = 'fail';
  410. $response = null;
  411. if ($post) {
  412. require_once(dirname(__FILE__) . '/export.php');
  413. $wxr = dsq_export_wp($post);
  414. $response = $dsq_api->import_wordpress_comments($wxr, $timestamp, $eof);
  415. if (!($response['group_id'] > 0)) {
  416. $result = 'fail';
  417. $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>';
  418. $response = $dsq_api->get_last_error();
  419. }
  420. else {
  421. if ($eof) {
  422. $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']);
  423. }
  424. $result = 'success';
  425. }
  426. }
  427. // send AJAX response
  428. $response = compact('result', 'timestamp', 'status', 'post_id', 'msg', 'eof', 'response');
  429. header('Content-type: text/javascript');
  430. echo cf_json_encode($response);
  431. die();
  432. }
  433. break;
  434. case 'import_comments':
  435. if (current_user_can('manage_options')) {
  436. if (!isset($_GET['last_comment_id'])) $last_comment_id = false;
  437. else $last_comment_id = $_GET['last_comment_id'];
  438. if ($_GET['wipe'] == '1') {
  439. $wpdb->query("DELETE FROM `".$wpdb->prefix."commentmeta` WHERE meta_key IN ('dsq_post_id', 'dsq_parent_post_id')");
  440. $wpdb->query("DELETE FROM `".$wpdb->prefix."comments` WHERE comment_agent LIKE 'Disqus/%%'");
  441. }
  442. ob_start();
  443. $response = dsq_sync_forum($last_comment_id, true);
  444. $debug = ob_get_clean();
  445. if (!$response) {
  446. $status = 'error';
  447. $result = 'fail';
  448. $error = $dsq_api->get_last_error();
  449. $msg = '<p class="status dsq-export-fail">'.dsq_i('There was an error downloading your comments from Disqus.').'<br/>'.htmlspecialchars($error).'</p>';
  450. } else {
  451. list($comments, $last_comment_id) = $response;
  452. if (!$comments) {
  453. $status = 'complete';
  454. $msg = dsq_i('Your comments have been downloaded from Disqus and saved in your local database.');
  455. } else {
  456. $status = 'partial';
  457. $msg = dsq_i('Import in progress (last post id: %s) &hellip;', $last_comment_id);
  458. }
  459. $result = 'success';
  460. }
  461. $debug = explode("\n", $debug);
  462. $response = compact('result', 'status', 'comments', 'msg', 'last_comment_id', 'debug');
  463. header('Content-type: text/javascript');
  464. echo cf_json_encode($response);
  465. die();
  466. }
  467. break;
  468. }
  469. }
  470. }
  471. add_action('init', 'dsq_request_handler');
  472. /**
  473. * @param string $option_name
  474. */
  475. function dsq_image_upload_handler($option_name) {
  476. // If the upload field has a file in it
  477. if(isset($_FILES[$option_name]) && ($_FILES[$option_name]['size'] > 0)) {
  478. // Get the type of the uploaded file. This is returned as "type/extension"
  479. $arr_file_type = wp_check_filetype(basename($_FILES[$option_name]['name']));
  480. $uploaded_file_type = $arr_file_type['type'];
  481. // Set an array containing a list of acceptable formats
  482. $allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png','image/x-icon');
  483. // If the uploaded file is the right format
  484. if(in_array($uploaded_file_type, $allowed_file_types)) {
  485. // Options array for the wp_handle_upload function. 'test_upload' => false
  486. $upload_overrides = array( 'test_form' => false );
  487. // Handle the upload using WP's wp_handle_upload function. Takes the posted file and an options array
  488. $uploaded_file = wp_handle_upload($_FILES[$option_name], $upload_overrides);
  489. // If the wp_handle_upload call returned a local path for the image
  490. if(isset($uploaded_file['url'])) {
  491. update_option($option_name, $uploaded_file['url']);
  492. }
  493. }
  494. }
  495. }
  496. function dsq_add_pending_post_id($post_id) {
  497. update_post_meta($post_id, 'dsq_needs_sync', '1', $unique=true);
  498. }
  499. function dsq_get_pending_post_ids() {
  500. global $wpdb;
  501. $results = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'dsq_needs_sync'");
  502. $post_ids = array();
  503. foreach ($results as $result) {
  504. $post_ids[] = $result->post_id;
  505. }
  506. return $post_ids;
  507. }
  508. function dsq_clear_pending_post_ids($post_ids) {
  509. global $wpdb;
  510. $post_ids_query = "'" . implode("', '", $post_ids) . "'";
  511. $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = 'dsq_needs_sync' AND post_id IN ({$post_ids_query})");
  512. update_meta_cache('dsq_needs_sync', $post_ids);
  513. }
  514. function dsq_sync_post($post_id) {
  515. global $dsq_api, $wpdb;
  516. $post = get_post($post_id);
  517. // Call update_thread to ensure our permalink is up to date
  518. dsq_update_permalink($post);
  519. }
  520. function dsq_sync_forum($last_comment_id=false, $force=false) {
  521. global $dsq_api, $wpdb;
  522. set_time_limit(DISQUS_SYNC_TIMEOUT);
  523. if ($force) {
  524. $sync_time = null;
  525. } else {
  526. $sync_time = (int)get_option('_disqus_sync_lock');
  527. }
  528. // lock expires after 1 hour
  529. if ($sync_time && $sync_time > time() - 60*60) {
  530. $dsq_api->api->last_error = 'Sync already in progress (lock found)';
  531. return false;
  532. } else {
  533. update_option('_disqus_sync_lock', time());
  534. }
  535. // sync all pending posts
  536. $post_ids = dsq_get_pending_post_ids();
  537. dsq_clear_pending_post_ids($post_ids);
  538. foreach ($post_ids as $post_id) {
  539. dsq_sync_post($post_id);
  540. }
  541. if ($last_comment_id === false) {
  542. $last_comment_id = get_option('disqus_last_comment_id');
  543. if (!$last_comment_id) {
  544. $last_comment_id = 0;
  545. }
  546. }
  547. if ($last_comment_id) {
  548. $last_comment_id++;
  549. }
  550. //$last_comment_id = 0;
  551. // Pull comments from API
  552. $dsq_response = $dsq_api->get_forum_posts($last_comment_id);
  553. if( $dsq_response < 0 || $dsq_response === false ) {
  554. return false;
  555. }
  556. // Sync comments with database.
  557. dsq_sync_comments($dsq_response);
  558. $total = 0;
  559. if ($dsq_response) {
  560. foreach ($dsq_response as $comment) {
  561. $total += 1;
  562. if ($comment->id > $last_comment_id) $last_comment_id = $comment->id;
  563. }
  564. if ($last_comment_id > get_option('disqus_last_comment_id')) {
  565. update_option('disqus_last_comment_id', $last_comment_id);
  566. }
  567. }
  568. unset($comment);
  569. delete_option('_disqus_sync_lock');
  570. return array($total, $last_comment_id);
  571. }
  572. add_action('dsq_sync_forum', 'dsq_sync_forum');
  573. function dsq_update_permalink($post) {
  574. global $dsq_api;
  575. if (DISQUS_DEBUG) {
  576. echo "updating post on disqus: {$post->ID}\n";
  577. }
  578. $response = $dsq_api->api->update_thread(null, array(
  579. 'thread_identifier' => dsq_identifier_for_post($post),
  580. 'title' => dsq_title_for_post($post),
  581. 'url' => dsq_link_for_post($post)
  582. ));
  583. update_post_meta($post->ID, 'dsq_thread_id', $response->id);
  584. return $response;
  585. }
  586. /**
  587. * Compatibility
  588. */
  589. if (!function_exists ( '_wp_specialchars' ) ) {
  590. function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
  591. $string = (string) $string;
  592. if ( 0 === strlen( $string ) ) {
  593. return '';
  594. }
  595. // Don't bother if there are no specialchars - saves some processing
  596. if ( !preg_match( '/[&<>"\']/', $string ) ) {
  597. return $string;
  598. }
  599. // Account for the previous behaviour of the function when the $quote_style is not an accepted value
  600. if ( empty( $quote_style ) ) {
  601. $quote_style = ENT_NOQUOTES;
  602. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  603. $quote_style = ENT_QUOTES;
  604. }
  605. // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
  606. if ( !$charset ) {
  607. static $_charset;
  608. if ( !isset( $_charset ) ) {
  609. $alloptions = wp_load_alloptions();
  610. $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
  611. }
  612. $charset = $_charset;
  613. }
  614. if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
  615. $charset = 'UTF-8';
  616. }
  617. $_quote_style = $quote_style;
  618. if ( $quote_style === 'double' ) {
  619. $quote_style = ENT_COMPAT;
  620. $_quote_style = ENT_COMPAT;
  621. } elseif ( $quote_style === 'single' ) {
  622. $quote_style = ENT_NOQUOTES;
  623. }
  624. // Handle double encoding ourselves
  625. if ( !$double_encode ) {
  626. $string = wp_specialchars_decode( $string, $_quote_style );
  627. $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
  628. }
  629. $string = @htmlspecialchars( $string, $quote_style, $charset );
  630. // Handle double encoding ourselves
  631. if ( !$double_encode ) {
  632. $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
  633. }
  634. // Backwards compatibility
  635. if ( 'single' === $_quote_style ) {
  636. $string = str_replace( "'", '&#039;', $string );
  637. }
  638. return $string;
  639. }
  640. }
  641. if (!function_exists ( 'wp_check_invalid_utf8' ) ) {
  642. function wp_check_invalid_utf8( $string, $strip = false ) {
  643. $string = (string) $string;
  644. if ( 0 === strlen( $string ) ) {
  645. return '';
  646. }
  647. // Store the site charset as a static to avoid multiple calls to get_option()
  648. static $is_utf8;
  649. if ( !isset( $is_utf8 ) ) {
  650. $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
  651. }
  652. if ( !$is_utf8 ) {
  653. return $string;
  654. }
  655. // Check for support for utf8 in the installed PCRE library once and store the result in a static
  656. static $utf8_pcre;
  657. if ( !isset( $utf8_pcre ) ) {
  658. $utf8_pcre = @preg_match( '/^./u', 'a' );
  659. }
  660. // We can't demand utf8 in the PCRE installation, so just return the string in those cases
  661. if ( !$utf8_pcre ) {
  662. return $string;
  663. }
  664. // preg_match fails when it encounters invalid UTF8 in $string
  665. if ( 1 === @preg_match( '/^./us', $string ) ) {
  666. return $string;
  667. }
  668. // Attempt to strip the bad chars if requested (not recommended)
  669. if ( $strip && function_exists( 'iconv' ) ) {
  670. return iconv( 'utf-8', 'utf-8', $string );
  671. }
  672. return '';
  673. }
  674. }
  675. if (!function_exists ( 'esc_html' ) ) {
  676. function esc_html( $text ) {
  677. $safe_text = wp_check_invalid_utf8( $text );
  678. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  679. return apply_filters( 'esc_html', $safe_text, $text );
  680. }
  681. }
  682. if (!function_exists ( 'esc_attr' ) ) {
  683. function esc_attr( $text ) {
  684. $safe_text = wp_check_invalid_utf8( $text );
  685. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  686. return apply_filters( 'attribute_escape', $safe_text, $text );
  687. }
  688. }
  689. /**
  690. * Filters/Actions
  691. */
  692. // ugly global hack for comments closing
  693. $EMBED = false;
  694. function dsq_comments_template($value) {
  695. global $EMBED;
  696. global $post;
  697. global $comments;
  698. if ( !( is_singular() && ( have_comments() || 'open' == $post->comment_status ) ) ) {
  699. return;
  700. }
  701. if ( !dsq_is_installed() || !dsq_can_replace() ) {
  702. return $value;
  703. }
  704. // TODO: If a disqus-comments.php is found in the current template's
  705. // path, use that instead of the default bundled comments.php
  706. //return TEMPLATEPATH . '/disqus-comments.php';
  707. $EMBED = true;
  708. return dirname(__FILE__) . '/comments.php';
  709. }
  710. function dsq_comment( $comment, $args, $depth ) {
  711. $GLOBALS['comment'] = $comment;
  712. switch ($comment->comment_type):
  713. case '' :
  714. ?>
  715. <li <?php comment_class(); ?> id="dsq-comment-<?php echo comment_ID(); ?>">
  716. <div id="dsq-comment-header-<?php echo comment_ID(); ?>" class="dsq-comment-header">
  717. <cite id="dsq-cite-<?php echo comment_ID(); ?>">
  718. <?php if(comment_author_url()) : ?>
  719. <a id="dsq-author-user-<?php echo comment_ID(); ?>" href="<?php echo comment_author_url(); ?>" target="_blank" rel="nofollow"><?php echo comment_author(); ?></a>
  720. <?php else : ?>
  721. <span id="dsq-author-user-<?php echo comment_ID(); ?>"><?php echo comment_author(); ?></span>
  722. <?php endif; ?>
  723. </cite>
  724. </div>
  725. <div id="dsq-comment-body-<?php echo comment_ID(); ?>" class="dsq-comment-body">
  726. <div id="dsq-comment-message-<?php echo comment_ID(); ?>" class="dsq-comment-message"><?php echo wp_filter_kses(comment_text()); ?></div>
  727. </div>
  728. </li>
  729. <?php
  730. break;
  731. case 'pingback' :
  732. case 'trackback' :
  733. ?>
  734. <li class="post pingback">
  735. <p><?php echo dsq_i('Pingback:'); ?> <?php comment_author_link(); ?><?php edit_comment_link(dsq_i('(Edit)'), ' '); ?></p>
  736. </li>
  737. <?php
  738. break;
  739. endswitch;
  740. }
  741. // Mark entries in index to replace comments link.
  742. // As of WordPress 3.1 this is required to return a numerical value
  743. function dsq_comments_number($count) {
  744. global $post;
  745. return $count;
  746. }
  747. function dsq_comments_text($comment_text) {
  748. global $post;
  749. if ( dsq_can_replace() ) {
  750. return '<span class="dsq-postid" rel="'.htmlspecialchars(dsq_identifier_for_post($post)).'">'.$comment_text.'</span>';
  751. } else {
  752. return $comment_text;
  753. }
  754. }
  755. function dsq_bloginfo_url($url) {
  756. if ( get_feed_link('comments_rss2') == $url && dsq_can_replace() ) {
  757. return 'http://' . strtolower(get_option('disqus_forum_url')) . '.' . DISQUS_DOMAIN . DISQUS_RSS_PATH;
  758. } else {
  759. return $url;
  760. }
  761. }
  762. function dsq_plugin_action_links($links, $file) {
  763. $plugin_file = basename(__FILE__);
  764. if (basename($file) == $plugin_file) {
  765. $settings_link = '<a href="edit-comments.php?page=disqus#adv">'.dsq_i('Settings').'</a>';
  766. array_unshift($links, $settings_link);
  767. }
  768. return $links;
  769. }
  770. add_filter('plugin_action_links', 'dsq_plugin_action_links', 10, 2);
  771. /**
  772. * Hide the default comment form to stop spammers by marking all comments
  773. * as closed.
  774. */
  775. function dsq_comments_open($open, $post_id=null) {
  776. global $EMBED;
  777. if ($EMBED) return false;
  778. return $open;
  779. }
  780. add_filter('comments_open', 'dsq_comments_open');
  781. // Always add Disqus management page to the admin menu
  782. function dsq_add_pages() {
  783. add_submenu_page(
  784. 'edit-comments.php',
  785. 'Disqus',
  786. 'Disqus',
  787. 'moderate_comments',
  788. 'disqus',
  789. 'dsq_manage'
  790. );
  791. }
  792. add_action('admin_menu', 'dsq_add_pages', 10);
  793. // a little jQuery goodness to get comments menu working as desired
  794. function dsq_menu_admin_head() {
  795. ?>
  796. <script type="text/javascript">
  797. jQuery(function($) {
  798. // fix menu
  799. var mc = $('#menu-comments');
  800. 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'));
  801. });
  802. </script>
  803. <?php
  804. }
  805. add_action('admin_head', 'dsq_menu_admin_head');
  806. // only active on dashboard
  807. function dsq_dash_comment_counts() {
  808. global $wpdb;
  809. // taken from wp-includes/comment.php - WP 2.8.5
  810. $count = $wpdb->get_results("
  811. SELECT comment_approved, COUNT( * ) AS num_comments
  812. FROM {$wpdb->comments}
  813. WHERE comment_type != 'trackback'
  814. AND comment_type != 'pingback'
  815. GROUP BY comment_approved
  816. ", ARRAY_A );
  817. $total = 0;
  818. $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam');
  819. $known_types = array_keys( $approved );
  820. foreach( (array) $count as $row_num => $row ) {
  821. $total += $row['num_comments'];
  822. if ( in_array( $row['comment_approved'], $known_types ) )
  823. $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
  824. }
  825. $stats['total_comments'] = $total;
  826. foreach ( $approved as $key ) {
  827. if ( empty($stats[$key]) )
  828. $stats[$key] = 0;
  829. }
  830. $stats = (object) $stats;
  831. ?>
  832. <style type="text/css">
  833. #dashboard_right_now .inside,
  834. #dashboard_recent_comments div.trackback {
  835. display: none;
  836. }
  837. </style>
  838. <script type="text/javascript">
  839. jQuery(function($) {
  840. $('#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); ?>').end().find('.inside').slideDown();
  841. $('#dashboard_recent_comments div.trackback').remove();
  842. $('#dashboard_right_now .inside table td.last a, #dashboard_recent_comments .inside .textright a.button').attr('href', 'edit-comments.php?page=disqus');
  843. });
  844. </script>
  845. <?php
  846. }
  847. function dsq_wp_dashboard_setup() {
  848. add_action('admin_head', 'dsq_dash_comment_counts');
  849. }
  850. add_action('wp_dashboard_setup', 'dsq_wp_dashboard_setup');
  851. function dsq_manage() {
  852. if (dsq_does_need_update() && isset($_POST['upgrade'])) {
  853. dsq_install();
  854. }
  855. if (dsq_does_need_update() && isset($_POST['uninstall'])) {
  856. include_once(dirname(__FILE__) . '/upgrade.php');
  857. } else {
  858. include_once(dirname(__FILE__) . '/manage.php');
  859. }
  860. }
  861. function dsq_admin_head() {
  862. if (isset($_GET['page']) && $_GET['page'] == 'disqus') {
  863. ?>
  864. <link rel='stylesheet' href='<?php echo DSQ_PLUGIN_URL; ?>/media/styles/manage.css' type='text/css' />
  865. <style type="text/css">
  866. .dsq-importing, .dsq-imported, .dsq-import-fail, .dsq-exporting, .dsq-exported, .dsq-export-fail {
  867. background: url(<?php echo admin_url('images/loading.gif'); ?>) left center no-repeat;
  868. line-height: 16px;
  869. padding-left: 20px;
  870. }
  871. p.status {
  872. padding-top: 0;
  873. padding-bottom: 0;
  874. margin: 0;
  875. }
  876. .dsq-imported, .dsq-exported {
  877. background: url(<?php echo admin_url('images/yes.png'); ?>) left center no-repeat;
  878. }
  879. .dsq-import-fail, .dsq-export-fail {
  880. background: url(<?php echo admin_url('images/no.png'); ?>) left center no-repeat;
  881. }
  882. </style>
  883. <script type="text/javascript">
  884. jQuery(function($) {
  885. $('#dsq-tabs li').click(function() {
  886. $('#dsq-tabs li.selected').removeClass('selected');
  887. $(this).addClass('selected');
  888. $('.dsq-main, .dsq-advanced').hide();
  889. $('.' + $(this).attr('rel')).show();
  890. });
  891. if (location.href.indexOf('#adv') != -1) {
  892. $('#dsq-tab-advanced').click();
  893. }
  894. dsq_fire_export();
  895. dsq_fire_import();
  896. });
  897. dsq_fire_export = function() {
  898. var $ = jQuery;
  899. $('#dsq_export a.button, #dsq_export_retry').unbind().click(function() {
  900. $('#dsq_export').html('<p class="status"></p>');
  901. $('#dsq_export .status').removeClass('dsq-export-fail').addClass('dsq-exporting').html('Processing...');
  902. dsq_export_comments();
  903. return false;
  904. });
  905. }
  906. dsq_export_comments = function() {
  907. var $ = jQuery;
  908. var status = $('#dsq_export .status');
  909. var export_info = (status.attr('rel') || '0|' + (new Date().getTime()/1000)).split('|');
  910. $.get(
  911. '<?php echo admin_url('index.php'); ?>',
  912. {
  913. cf_action: 'export_comments',
  914. post_id: export_info[0],
  915. timestamp: export_info[1]
  916. },
  917. function(response) {
  918. switch (response.result) {
  919. case 'success':
  920. status.html(response.msg).attr('rel', response.post_id + '|' + response.timestamp);
  921. switch (response.status) {
  922. case 'partial':
  923. dsq_export_comments();
  924. break;
  925. case 'complete':
  926. status.removeClass('dsq-exporting').addClass('dsq-exported');
  927. break;
  928. }
  929. break;
  930. case 'fail':
  931. status.parent().html(response.msg);
  932. dsq_fire_export();
  933. break;
  934. }
  935. },
  936. 'json'
  937. );
  938. }
  939. dsq_fire_import = function() {
  940. var $ = jQuery;
  941. $('#dsq_import a.button, #dsq_import_retry').unbind().click(function() {
  942. var wipe = $('#dsq_import_wipe').is(':checked');
  943. $('#dsq_import').html('<p class="status"></p>');
  944. $('#dsq_import .status').removeClass('dsq-import-fail').addClass('dsq-importing').html('Processing...');
  945. dsq_import_comments(wipe);
  946. return false;
  947. });
  948. }
  949. dsq_import_comments = function(wipe) {
  950. var $ = jQuery;
  951. var status = $('#dsq_import .status');
  952. var last_comment_id = status.attr('rel') || '0';
  953. $.get(
  954. '<?php echo admin_url('index.php'); ?>',
  955. {
  956. cf_action: 'import_comments',
  957. last_comment_id: last_comment_id,
  958. wipe: (wipe ? 1 : 0)
  959. },
  960. function(response) {
  961. switch (response.result) {
  962. case 'success':
  963. status.html(response.msg).attr('rel', response.last_comment_id);
  964. switch (response.status) {
  965. case 'partial':
  966. dsq_import_comments(false);
  967. break;
  968. case 'complete':
  969. status.removeClass('dsq-importing').addClass('dsq-imported');
  970. break;
  971. }
  972. break;
  973. case 'fail':
  974. status.parent().html(response.msg);
  975. dsq_fire_import();
  976. break;
  977. }
  978. },
  979. 'json'
  980. );
  981. }
  982. </script>
  983. <?php
  984. // HACK: Our own styles for older versions of WordPress.
  985. global $wp_version;
  986. if ( version_compare($wp_version, '2.5', '<') ) {
  987. echo "<link rel='stylesheet' href='" . DSQ_PLUGIN_URL . "/media/styles/manage-pre25.css' type='text/css' />";
  988. }
  989. }
  990. }
  991. add_action('admin_head', 'dsq_admin_head');
  992. function dsq_warning() {
  993. $page = (isset($_GET['page']) ? $_GET['page'] : null);
  994. if ( !get_option('disqus_forum_url') && !isset($_POST['forum_url']) && $page != 'disqus' ) {
  995. dsq_manage_dialog('You must <a href="edit-comments.php?page=disqus">configure the plugin</a> to enable Disqus Comments.', true);
  996. }
  997. if ( !dsq_is_installed() && $page != 'disqus' && !empty($_GET['step']) && !isset($_POST['uninstall']) ) {
  998. dsq_manage_dialog('Disqus Comments has not yet been configured. (<a href="edit-comments.php?page=disqus">Click here to configure</a>)');
  999. }
  1000. }
  1001. /**
  1002. * Wrapper for built-in __() which pulls all text from
  1003. * the disqus domain and supports variable interpolation.
  1004. */
  1005. function dsq_i($text, $params=null) {
  1006. if (!is_array($params))
  1007. {
  1008. $params = func_get_args();
  1009. $params = array_slice($params, 1);
  1010. }
  1011. return vsprintf(__($text, 'disqus'), $params);
  1012. }
  1013. // catch original query
  1014. function dsq_parse_query($query) {
  1015. add_action('the_posts', 'dsq_add_request_post_ids', 999);
  1016. }
  1017. add_action('parse_request', 'dsq_parse_query');
  1018. // track the original request post_ids, only run once
  1019. function dsq_add_request_post_ids($posts) {
  1020. dsq_add_query_posts($posts);
  1021. remove_action('the_posts', 'dsq_log_request_post_ids', 999);
  1022. return $posts;
  1023. }
  1024. function dsq_maybe_add_post_ids($posts) {
  1025. global $DSQ_QUERY_COMMENTS;
  1026. if ($DSQ_QUERY_COMMENTS) {
  1027. dsq_add_query_posts($posts);
  1028. }
  1029. return $posts;
  1030. }
  1031. add_action('the_posts', 'dsq_maybe_add_post_ids');
  1032. function dsq_add_query_posts($posts) {
  1033. global $DSQ_QUERY_POST_IDS;
  1034. if (count($posts)) {
  1035. foreach ($posts as $post) {
  1036. $post_ids[] = intval($post->ID);
  1037. }
  1038. $DSQ_QUERY_POST_IDS[md5(serialize($post_ids))] = $post_ids;
  1039. }
  1040. }
  1041. // check to see if the posts in the loop match the original request or an explicit request, if so output the JS
  1042. function dsq_loop_end($query) {
  1043. if ( get_option('disqus_cc_fix') == '1' || !count($query->posts) || is_single() || is_page() || is_feed() || !dsq_can_replace() ) {
  1044. return;
  1045. }
  1046. global $DSQ_QUERY_POST_IDS;
  1047. foreach ($query->posts as $post) {
  1048. $loop_ids[] = intval($post->ID);
  1049. }
  1050. $posts_key = md5(serialize($loop_ids));
  1051. if (isset($DSQ_QUERY_POST_IDS[$posts_key])) {
  1052. dsq_output_loop_comment_js($DSQ_QUERY_POST_IDS[$posts_key]);
  1053. }
  1054. }
  1055. add_action('loop_end', 'dsq_loop_end');
  1056. // if someone has a better hack, let me know
  1057. // prevents duplicate calls to count.js
  1058. $_HAS_COUNTS = false;
  1059. function dsq_output_loop_comment_js($post_ids = null) {
  1060. global $_HAS_COUNTS;
  1061. if ($_HAS_COUNTS) return;
  1062. $_HAS_COUNTS = true;
  1063. if (count($post_ids)) {
  1064. ?>
  1065. <script type="text/javascript">
  1066. // <![CDATA[
  1067. var disqus_shortname = '<?php echo strtolower(get_option('disqus_forum_url')); ?>';
  1068. (function () {
  1069. var nodes = document.getElementsByTagName('span');
  1070. for (var i = 0, url; i < nodes.length; i++) {
  1071. if (nodes[i].className.indexOf('dsq-postid') != -1) {
  1072. nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
  1073. url = nodes[i].parentNode.href.split('#', 1);
  1074. if (url.length == 1) { url = url[0]; }
  1075. else { url = url[1]; }
  1076. nodes[i].parentNode.href = url + '#disqus_thread';
  1077. }
  1078. }
  1079. var s = document.createElement('script'); s.async = true;
  1080. s.type = 'text/javascript';
  1081. <?php
  1082. if (is_ssl()) {
  1083. $connection_type = "https";
  1084. } else {
  1085. $connection_type = "http";
  1086. }
  1087. ?>
  1088. s.src = '<?php echo $connection_type; ?>' + '://' + '<?php echo DISQUS_DOMAIN; ?>/forums/' + disqus_shortname + '/count.js';
  1089. (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
  1090. }());
  1091. //]]>
  1092. </script>
  1093. <?php
  1094. }
  1095. }
  1096. function dsq_output_footer_comment_js() {
  1097. if (!dsq_can_replace()) return;
  1098. if (get_option('disqus_cc_fix') != '1') return;
  1099. ?>
  1100. <script type="text/javascript">
  1101. // <![CDATA[
  1102. var disqus_shortname = '<?php echo strtolower(get_option('disqus_forum_url')); ?>';
  1103. (function () {
  1104. var nodes = document.getElementsByTagName('span');
  1105. for (var i = 0, url; i < nodes.length; i++) {
  1106. if (nodes[i].className.indexOf('dsq-postid') != -1) {
  1107. nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
  1108. url = nodes[i].parentNode.href.split('#', 1);
  1109. if (url.length == 1) url = url[0];
  1110. else url = url[1]
  1111. nodes[i].parentNode.href = url + '#disqus_thread';
  1112. }
  1113. }
  1114. var s = document.createElement('script'); s.async = true;
  1115. s.type = 'text/javascript';
  1116. <?php
  1117. if (is_ssl()) {
  1118. $connection_type = "https";
  1119. } else {
  1120. $connection_type = "http";
  1121. }
  1122. ?>
  1123. s.src = '<?php echo $connection_type; ?>' + '://' + '<?php echo DISQUS_DOMAIN; ?>/forums/' + disqus_shortname + '/count.js';
  1124. (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
  1125. }());
  1126. //]]>
  1127. </script>
  1128. <?php
  1129. }
  1130. add_action('wp_footer', 'dsq_output_footer_comment_js');
  1131. // UPDATE DSQ when a permalink changes
  1132. $dsq_prev_permalinks = array();
  1133. function dsq_prev_permalink($post_id) {
  1134. // if post not published, return
  1135. $post = &get_post($post_id);
  1136. if ($post->post_status != 'publish') {
  1137. return;
  1138. }
  1139. global $dsq_prev_permalinks;
  1140. $dsq_prev_permalinks['post_'.$post_id] = get_permalink($post_id);
  1141. }
  1142. add_action('pre_post_update', 'dsq_prev_permalink');
  1143. function dsq_check_permalink($post_id) {
  1144. global $dsq_prev_permalinks;
  1145. if (!empty($dsq_prev_permalinks['post_'.$post_id]) && $dsq_prev_permalinks['post_'.$post_id] != get_permalink($post_id)) {
  1146. $post = get_post($post_id);
  1147. dsq_update_permalink($post);
  1148. }
  1149. }
  1150. add_action('edit_post', 'dsq_check_permalink');
  1151. add_action('admin_notices', 'dsq_warning');
  1152. // Only replace comments if the disqus_forum_url option is set.
  1153. add_filter('comments_template', 'dsq_comments_template');
  1154. add_filter('comments_number', 'dsq_comments_text');
  1155. add_filter('get_comments_number', 'dsq_comments_number');
  1156. add_filter('bloginfo_url', 'dsq_bloginfo_url');
  1157. /**
  1158. * JSON ENCODE for PHP < 5.2.0
  1159. * Checks if json_encode is not available and defines json_encode
  1160. * to use php_json_encode in its stead
  1161. * Works on iteratable objects as well - stdClass is iteratable, so all WP objects are gonna be iteratable
  1162. */
  1163. if(!function_exists('cf_json_encode')) {
  1164. function cf_json_encode($data) {
  1165. // json_encode is sending an application/x-javascript header on Joyent servers
  1166. // for some unknown reason.
  1167. // if(function_exists('json_encode')) { return json_encode($data); }
  1168. // else { return cfjson_encode($data); }
  1169. return cfjson_encode($data);
  1170. }
  1171. function cfjson_encode_string($str) {
  1172. if(is_bool($str)) {
  1173. return $str ? 'true' : 'false';
  1174. }
  1175. return str_replace(
  1176. array(
  1177. '"'
  1178. , '/'
  1179. , "\n"
  1180. , "\r"
  1181. )
  1182. , array(
  1183. '\"'
  1184. , '\/'
  1185. , '\n'
  1186. , '\r'
  1187. )
  1188. , $str
  1189. );
  1190. }
  1191. function cfjson_encode($arr) {
  1192. $json_str = '';
  1193. if (is_array($arr)) {
  1194. $pure_array = true;
  1195. $array_length = count($arr);
  1196. for ( $i = 0; $i < $array_length ; $i++) {
  1197. if (!isset($arr[$i])) {
  1198. $pure_array = false;
  1199. break;
  1200. }
  1201. }
  1202. if ($pure_array) {
  1203. $json_str = '[';
  1204. $temp = array();
  1205. for ($i=0; $i < $array_length; $i++) {
  1206. $temp[] = sprintf("%s", cfjson_encode($arr[$i]));
  1207. }
  1208. $json_str .= implode(',', $temp);
  1209. $json_str .="]";
  1210. }
  1211. else {
  1212. $json_str = '{';
  1213. $temp = array();
  1214. foreach ($arr as $key => $value) {
  1215. $temp[] = sprintf("\"%s\":%s", $key, cfjson_encode($value));
  1216. }
  1217. $json_str .= implode(',', $temp);
  1218. $json_str .= '}';
  1219. }
  1220. }
  1221. else if (is_object($arr)) {
  1222. $json_str = '{';
  1223. $temp = array();
  1224. foreach ($arr as $k => $v) {
  1225. $temp[] = '"'.$k.'":'.cfjson_encode($v);
  1226. }
  1227. $json_str .= implode(',', $temp);

Large files files are truncated, but you can click here to view the full file