Yet Another Related Posts Plugin (YARPP) - Version 5.24.0

Version Description

(17-June-2021) = * Enhancement: Option to automatically generate missing thumbnail sizes on the fly when using Custom YARPP Templates * New: Control YARPP Automatic Display programatically with filter support for noyarpp. For example: add_filter( 'noyarpp', 'custom_function' ); * Enhancement: Use the faster and less memory intensive function strpos() instead of stristr()

Download this release

Release Info

Developer jeffparker
Plugin Icon 128x128 Yet Another Related Posts Plugin (YARPP)
Version 5.24.0
Comparing to
See all releases

Code changes from version 5.23.0 to 5.24.0

Files changed (48) hide show
  1. classes/YARPP_Admin.php +885 -834
  2. classes/YARPP_Block.php +4 -2
  3. classes/YARPP_Cache.php +573 -528
  4. classes/YARPP_Cache_Bypass.php +191 -187
  5. classes/YARPP_Cache_Postmeta.php +120 -99
  6. classes/YARPP_Cache_Tables.php +136 -112
  7. classes/YARPP_Core.php +1352 -1096
  8. classes/YARPP_DB_Options.php +8 -6
  9. classes/YARPP_DB_Schema.php +18 -12
  10. classes/YARPP_Meta_Box.php +99 -99
  11. classes/YARPP_Meta_Box_Contact.php +26 -26
  12. classes/YARPP_Meta_Box_Display_Feed.php +62 -59
  13. classes/YARPP_Meta_Box_Display_Rest_Api.php +2 -2
  14. classes/YARPP_Meta_Box_Display_Web.php +114 -105
  15. classes/YARPP_Meta_Box_Optin.php +23 -24
  16. classes/YARPP_Meta_Box_Pool.php +25 -25
  17. classes/YARPP_Meta_Box_Relatedness.php +13 -13
  18. classes/YARPP_Rest_Api.php +79 -75
  19. classes/YARPP_Shortcode.php +23 -22
  20. classes/YARPP_Widget.php +64 -54
  21. includes/init_functions.php +8 -8
  22. includes/optin_notice.js.php +21 -21
  23. includes/related_functions.php +77 -74
  24. includes/template_builtin.php +42 -42
  25. includes/template_functions.php +1 -1
  26. includes/template_metabox.php +16 -16
  27. includes/template_thumbnails.php +16 -12
  28. includes/template_widget.php +5 -5
  29. includes/yarpp_meta_boxes_hooks.php +62 -61
  30. includes/yarpp_myisam_notice.php +16 -15
  31. includes/yarpp_options.php +162 -147
  32. includes/yarpp_pro_options.php +13 -13
  33. includes/yarpp_pro_set_display_types.php +9 -7
  34. js/options_basic.min.js +1 -1
  35. lib/plugin-deactivation-survey/deactivate-feedback-form.php +4 -4
  36. readme.txt +301 -130
  37. src/js/block.js +116 -112
  38. src/js/metabox.js +69 -69
  39. src/js/options_basic.js +488 -471
  40. src/js/options_switch.js +68 -68
  41. uninstall.php +21 -20
  42. yarpp-templates/yarpp-template-example.php +3 -4
  43. yarpp-templates/yarpp-template-list.php +1 -1
  44. yarpp-templates/yarpp-template-multilingual.php +2 -2
  45. yarpp-templates/yarpp-template-random.php +3 -3
  46. yarpp-templates/yarpp-template-simple.php +3 -3
  47. yarpp-templates/yarpp-template-thumbnail.php +2 -2
  48. yarpp.php +51 -45
classes/YARPP_Admin.php CHANGED
@@ -5,173 +5,177 @@ class YARPP_Admin {
5
  /**
6
  * @var YARPP
7
  */
8
- public $core;
9
- public $hook;
10
-
11
- const ACTIVATE_TIMESTAMP_OPTION = 'yarpp_activate_timestamp';
12
- const REVIEW_DISMISS_OPTION = 'yarpp_review_notice';
13
- const REVIEW_FIRST_PERIOD = 518400; // 6 days in seconds
14
- const REVIEW_LATER_PERIOD = 5184000; // 60 days in seconds
15
- const REVIEW_FOREVER_PERIOD = 63113904; // 2 years in seconds
16
-
17
- function __construct(&$core) {
18
- $this->core = &$core;
19
-
20
- /* If action = flush and the nonce is correct, reset the cache */
21
- if (isset($_GET['action']) && $_GET['action'] === 'flush' && check_ajax_referer('yarpp_cache_flush', false, false) !== false) {
22
- $this->core->cache->flush();
23
- wp_safe_redirect(admin_url('/options-general.php?page=yarpp'));
24
- exit;
25
- }
26
-
27
- /* If action = copy_templates and the nonce is correct, copy templates */
28
- if (isset($_GET['action']) && $_GET['action'] === 'copy_templates' && check_ajax_referer('yarpp_copy_templates', false, false) !== false) {
29
- $this->copy_templates();
30
- wp_safe_redirect(admin_url('/options-general.php?page=yarpp'));
31
- exit;
32
- }
33
-
34
- add_action('admin_init', array($this, 'ajax_register'));
35
- add_action('admin_init', array($this, 'review_register'));
36
- add_action('admin_menu', array($this, 'ui_register'));
37
- add_action( 'save_post', array($this, 'yarpp_save_meta_box' ) );
38
-
39
- add_filter('current_screen', array($this, 'settings_screen'));
40
- add_filter('screen_settings', array($this, 'render_screen_settings'), 10, 2);
41
- add_filter('default_hidden_meta_boxes', array($this, 'default_hidden_meta_boxes'), 10, 2);
42
- add_filter('shareaholic_deactivate_feedback_form_plugins', array($this,'deactivation_survey_data'));
43
- }
44
-
45
- /**
46
- * @since 4.0.3 Moved method to Core.
47
- */
48
- public function get_templates() {
49
- return $this->core->get_templates();
50
- }
51
-
52
- /**
53
- * Register Review notice
54
- */
55
- function review_register() {
56
- self::check_review_dismissal();
57
- self::check_plugin_review();
58
- }
59
-
60
- /**
61
- * Register AJAX services
62
- */
63
- function ajax_register() {
64
- if (defined('DOING_AJAX') && DOING_AJAX) {
65
- add_action('wp_ajax_yarpp_display_exclude_terms', array($this, 'ajax_display_exclude_terms'));
66
- add_action('wp_ajax_yarpp_display_demo', array($this, 'ajax_display_demo'));
67
- add_action('wp_ajax_yarpp_display', array($this, 'ajax_display'));
68
- add_action('wp_ajax_yarpp_optin_data', array($this, 'ajax_optin_data'));
69
- add_action('wp_ajax_yarpp_optin_enable', array($this, 'ajax_optin_enable'));
70
- add_action('wp_ajax_yarpp_optin_disable', array($this, 'ajax_optin_disable'));
71
- add_action('wp_ajax_yarpp_set_display_code', array($this, 'ajax_set_display_code'));
72
- add_action('wp_ajax_yarpp_switch', array($this, 'ajax_switch'));
73
- add_action('wp_ajax_yarpp_clear_cache', array($this, 'ajax_clear_cache'));
74
- }
75
- }
76
- /**
77
- * Ajax callback for clearing the YARPP cache
78
- *
79
- * @since 5.13.0
80
- */
81
- public function ajax_clear_cache() {
82
- if( false === check_ajax_referer( 'clear_cache_yarpp', false, false ) ) {
83
- echo 'nonce_fail';
84
- } else if ( current_user_can( 'manage_options' ) ) {
85
- $this->core->cache->flush();
86
- echo 'success';
87
- } else {
88
- echo 'forbidden';
89
- }
90
- wp_die();
91
- }
92
- /**
93
- * Check review notice status for current user
94
- *
95
- * @since 5.1.0
96
- */
97
- public static function check_review_dismissal() {
98
-
99
- global $current_user;
100
- $user_id = $current_user->ID;
101
-
102
- if (!is_admin() ||
103
- !isset($_GET['_wpnonce']) ||
104
- !wp_verify_nonce($_GET['_wpnonce'], 'review-nonce') ||
105
- !isset($_GET['yarpp_defer_t']) ||
106
- !isset($_GET[self::REVIEW_DISMISS_OPTION])) {
107
- return;
108
- }
109
-
110
- $the_meta_array = array (
111
- 'dismiss_defer_period' => $_GET["yarpp_defer_t"],
112
- 'dismiss_timestamp' => time()
113
- );
114
-
115
- update_user_meta($user_id, self::REVIEW_DISMISS_OPTION, $the_meta_array);
116
- }
117
-
118
- /**
119
- * Check if we should display the review notice
120
- *
121
- * @since 5.1.0
122
- */
123
- public static function check_plugin_review() {
124
-
125
- global $current_user;
126
- $user_id = $current_user->ID;
127
-
128
- if (!current_user_can('publish_posts')) {
129
  return;
130
  }
131
 
132
- $show_review_notice = false;
133
- $activation_timestamp = get_site_option(self::ACTIVATE_TIMESTAMP_OPTION);
134
- $review_dismissal_array = get_user_meta($user_id, self::REVIEW_DISMISS_OPTION, true);
135
- $dismiss_defer_period = isset($review_dismissal_array['dismiss_defer_period']) ? $review_dismissal_array['dismiss_defer_period'] : 0;
136
- $dismiss_timestamp = isset($review_dismissal_array['dismiss_timestamp']) ? $review_dismissal_array['dismiss_timestamp'] : time();
137
-
138
- if ($dismiss_timestamp + $dismiss_defer_period <= time()) {
139
- $show_review_notice = true;
140
- }
141
-
142
- if (!$activation_timestamp) {
143
- $activation_timestamp = time();
144
- add_site_option(self::ACTIVATE_TIMESTAMP_OPTION, $activation_timestamp);
145
- }
146
-
147
- // display review message after a certain period of time after activation
148
- if ((time() - $activation_timestamp > self::REVIEW_FIRST_PERIOD) && $show_review_notice == true) {
149
- add_action('admin_notices', array('YARPP_Admin', 'display_review_notice'));
150
- }
151
- }
152
-
153
- /**
154
- * @since 5.1.0
155
- */
156
- public static function display_review_notice() {
157
-
158
- $dismiss_forever = add_query_arg( array(
159
- self::REVIEW_DISMISS_OPTION => true,
160
- 'yarpp_defer_t' => self::REVIEW_FOREVER_PERIOD
161
- ));
162
-
163
- $dismiss_forlater = add_query_arg( array(
164
- self::REVIEW_DISMISS_OPTION => true,
165
- 'yarpp_defer_t' => self::REVIEW_LATER_PERIOD
166
- ));
167
-
168
- $dismiss_forever_url = wp_nonce_url($dismiss_forever, 'review-nonce');
169
- $dismiss_forlater_url = wp_nonce_url($dismiss_forlater, 'review-nonce');
170
-
171
- echo '
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  <style>
173
  .yarpp-review-notice {
174
- background-size: contain; background-position: right bottom; background-repeat: no-repeat; background-image: url(' . plugins_url('../images/icon-256x256.png', __FILE__) . ');
175
  }
176
  .yarpp-review-notice-text {
177
  background: rgba(255, 255, 255, 0.9); text-shadow: white 0px 0px 10px; margin-right: 8em !important;
@@ -200,649 +204,688 @@ class YARPP_Admin {
200
  </script>
201
 
202
  <div class="notice notice-info is-dismissible yarpp-review-notice">
203
- <p class="yarpp-review-notice-text">' . __('Hey there! We noticed that you have had success using ', 'yarpp') . '<a href="' . admin_url('options-general.php?page=yarpp') . '">YARPP - Related Posts</a>! ' . __('Could you please do us a BIG favor and give us a quick 5-star rating on WordPress? It will boost our motivation and spread the word. We would really appreciate it 🤗 — Team YARPP', 'yarpp') . '
204
  <br />
205
  <br />
206
- <a onClick="' . "yarpp_openWindowReload('https://wordpress.org/support/plugin/yet-another-related-posts-plugin/reviews/?rate=5#new-post', '$dismiss_forever_url')" . '" class="button button-primary">' . __('Ok, you deserve it', 'shareaholic') . '</a> &nbsp;
207
- <a href="' . $dismiss_forlater_url . '">' . __('No, not good enough', 'yarpp') . '</a> &nbsp;
208
- <a href="' . $dismiss_forever_url . '">' . __('I already did', 'yarpp') . '</a> &nbsp;
209
- <a href="' . $dismiss_forever_url . '">' . __('Dismiss', 'yarpp') . '</a>
210
  </p>
211
  </div>';
212
- }
213
-
214
- function ui_register() {
215
- global $wp_version;
216
-
217
- if ($this->core->db_options->after_activation()) {
218
-
219
- $this->core->db_options->delete_activation_flag();
220
- $this->core->db_options->delete_upgrade_flag();
221
-
222
- /* Optin/Pro message */
223
- add_action('admin_notices', array($this, 'install_notice'));
224
-
225
- } elseif ( $this->core->db_options->after_upgrade() && current_user_can('manage_options') && $this->core->get_option('optin')) {
226
- add_action('admin_notices', array($this, 'upgrade_notice'));
227
- }
228
-
229
- if ($this->core->get_option('optin')) $this->core->db_options->delete_upgrade_flag();
230
-
231
- /*
232
- * Setup Admin
233
- */
234
- $titleName = 'YARPP';
235
- $this->hook = add_options_page($titleName, $titleName, 'manage_options', 'yarpp', array($this, 'options_page'));
236
-
237
- /**
238
- * @since 3.0.12 Add settings link to the plugins page.
239
- */
240
- add_filter('plugin_action_links', array($this, 'settings_link'), 10, 2);
241
-
242
- $metabox_post_types = $this->core->get_option('auto_display_post_types');
243
- if (!in_array('post', $metabox_post_types)) $metabox_post_types[] = 'post';
244
-
245
- /**
246
- * @since 3.0 Add meta box in Editor
247
- */
248
- if(!$this->core->yarppPro['active']){
249
- foreach ($metabox_post_types as $post_type) {
250
- $title = __('YARPP: Related Posts' , 'yarpp');
251
- add_meta_box('yarpp_relatedposts',$title, array($this, 'metabox'), $post_type, 'normal');
252
- }
253
- }
254
-
255
- /**
256
- * @since 3.3: properly enqueue scripts for admin.
257
- */
258
- add_action('admin_enqueue_scripts', array($this, 'enqueue'));
259
- }
260
-
261
- /**
262
- * @since 3.5.4 Only load metabox code if we're going to be on the settings page.
263
- */
264
- function settings_screen($current_screen) {
265
- if ($current_screen->id !== 'settings_page_yarpp') return $current_screen;
266
-
267
- /**
268
- * @since 3.3: Load options page sections as meta-boxes.
269
- */
270
- include_once(YARPP_DIR.'/includes/yarpp_meta_boxes_hooks.php');
271
-
272
- /**
273
- * @since 3.5.5 Check that add_help_tab method callable (WP >= 3.3).
274
- */
275
- if (is_callable(array($current_screen, 'add_help_tab'))) {
276
- $current_screen->add_help_tab(array(
277
- 'id' => 'faq',
278
- 'title' => __('Frequently Asked Questions', 'yarpp'),
279
- 'callback' => array(&$this, 'help_faq')
280
- ));
281
-
282
- $current_screen->add_help_tab(array(
283
- 'id' => 'dev',
284
- 'title' => __('Developing with YARPP', 'yarpp'),
285
- 'callback' => array(&$this, 'help_dev')
286
- ));
287
-
288
- $current_screen->add_help_tab(array(
289
- 'id' => 'optin',
290
- 'title' => __('Optional Data Collection', 'yarpp'),
291
- 'callback' => array(&$this, 'help_optin')
292
- ));
293
- }
294
-
295
- return $current_screen;
296
- }
297
-
298
- private $readme = null;
299
-
300
- public function help_faq() {
301
- if (is_null($this->readme)) $this->readme = file_get_contents(YARPP_DIR.'/readme.txt');
302
-
303
- if (preg_match('!== Frequently Asked Questions ==(.*?)^==!sm', $this->readme, $matches)) {
304
- echo $this->markdown($matches[1]);
305
- } else {
306
- echo(
307
- '<a href="https://wordpress.org/plugins/yet-another-related-posts-plugin/#faq">'.
308
- __('Frequently Asked Questions', 'yarpp').
309
- '</a>'
310
- );
311
- }
312
- }
313
-
314
- public function help_dev() {
315
- if (is_null($this->readme)) $this->readme = file_get_contents(YARPP_DIR.'/readme.txt');
316
-
317
- if (preg_match('!== Developing with YARPP ==(.*?)^==!sm', $this->readme, $matches)) {
318
- echo $this->markdown( $matches[1] );
319
- } else {
320
- echo(
321
- '<a href="https://wordpress.org/plugins/yet-another-related-posts-plugin/#faq" target="_blank">'.
322
- __('Developing with YARPP', 'yarpp').
323
- '</a>'
324
- );
325
- }
326
- }
327
-
328
- public function help_optin() {
329
- echo(
330
- '<p>'.
331
- __("With your permission, YARPP will send information about YARPP's settings, usage, and environment
332
- back to a central server at ", 'yarpp').'<code>yarpp.org</code>'.'.&nbsp;'.
333
- '</p>'.
334
- '<p>'.
335
- 'We would really appreciate your input to help us continue to improve the product. We are primarily looking '.
336
- 'for country, domain, and date installed information.'.
337
- '</p>'.
338
- '<p>'.
339
- __("This information will be used to improve YARPP in the future and help decide future development
340
- decisions for YARPP.",
341
- 'yarpp'
342
- ).' '.
343
- '</p>'.
344
- '<p>'.
345
- '<strong>'.
346
- __("Contributing this data will help make YARPP better for you and for other YARPP users.",
347
- 'yarpp' ).'</strong>'.
348
- '</p>'
349
- );
350
-
351
- echo(
352
- '<p>'.
353
- __("The following information is sent back to YARPP:", 'yarpp').
354
- '</p>'.
355
- '<div id="optin_data_frame"></div>'.
356
- '<p>'.
357
- __("In addition, YARPP also loads an invisible pixel image with your YARPP results to know how often YARPP is being used.", 'yarpp').
358
- '</p>'
359
- );
360
- }
361
-
362
- function the_optin_button($action, $echo = false) {
363
- $status = ($this->core->yarppPro['active']) ? 'disabled' : null;
364
-
365
- if ($action === 'disable'){
366
- $out =
367
- '<a id="yarpp-optin-button'.$status.'" class="button" '.$status.'>'.
368
- 'No, Thanks. Please <strong>'.$action.'</strong> sending usage data'.
369
- '</a>';
370
- } else {
371
- $out =
372
- '<a id="yarpp-optin-button'.$status.'" class="button" '.$status.'>'.
373
- 'Yes, <strong>'.$action.'</strong> sending usage data back to help improve YARPP'.
374
- '</a>';
375
- }
376
-
377
- if ($echo){
378
- echo $out;
379
- return null;
380
- } else {
381
- return $out;
382
- }
383
- }
384
-
385
- function the_donothing_button($msg, $echo = false) {
386
- $out ='<a href="options-general.php?page=yarpp" class="button">'.$msg.'</a>';
387
- if ($echo){
388
- echo $out;
389
- return null;
390
- } else {
391
- return $out;
392
- }
393
- }
394
-
395
- function optin_button_script($optinAction, $echo=false) {
396
- wp_nonce_field('yarpp_optin_'.$optinAction, 'yarpp_optin-nonce', false);
397
-
398
- ob_start();
399
- include(YARPP_DIR.'/includes/optin_notice.js.php');
400
- $out = ob_get_contents();
401
- ob_end_clean();
402
-
403
- if($echo){
404
- echo $out;
405
- return null;
406
- } else {
407
- return $out;
408
- }
409
- }
410
-
411
- function upgrade_notice() {
412
- $optinAction = ($this->core->get_option('optin')) ? 'disable' : 'enable';
413
- $this->optin_notice('upgrade', $optinAction);
414
- }
415
-
416
- public function install_notice(){
417
- $optinAction = ($this->core->get_option('optin')) ? 'disable' : 'enable';
418
- $this->optin_notice('install', $optinAction);
419
- }
420
-
421
- public function optin_notice($type=false, $optinAction='disable') {
422
- $screen = get_current_screen();
423
- if(is_null($screen) || $screen->id == 'settings_page_yarpp') return;
424
-
425
- switch($type) {
426
- case 'upgrade':
427
- $this->core->db_options->delete_upgrade_flag();
428
- break;
429
- case 'install':
430
- default:
431
- $user = get_current_user_id();
432
- update_user_option($user, 'yarpp_saw_optin', true);
433
- }
434
-
435
- $out = '<div class="updated fade"><p>';
436
-
437
- if($type === 'upgrade'){
438
- $out .= '<strong>'.sprintf(__('%1$s updated successfully.'), 'Yet Another Related Posts Plugin').'</strong>';
439
- }
440
 
441
- if ($type === 'install'){
442
- $tmp = __('Thank you for installing <span>Yet Another Related Posts Plugin</span>!', 'yarpp');
443
- $out .= '<strong>'.str_replace('<span>','<span style="font-style:italic; font-weight: inherit;">', $tmp).'</strong>';
444
- }
445
 
446
- if($this->core->yarppPro['active']){
447
 
448
- $out .=
449
- '<p>'.
450
- 'You currently have <strong>YARPP Basic</strong> and <strong>YARPP Pro</strong> enabled.<br/><br/>'.
451
- '<a href="options-general.php?page=yarpp" class="button">Take me to the settings page</a>'.
452
- '</p>';
453
 
454
- } else {
 
455
 
456
- $out .= '</p><p>';
457
- if($optinAction !== 'disable'){
458
- $out .= $this->the_donothing_button('No, thanks').'&nbsp;&nbsp;';
459
- } else {
460
- $out .= $this->the_donothing_button('Yes, keep sending usage data').'&nbsp;&nbsp;';
461
- }
462
- $out .= $this->the_optin_button($optinAction);
463
- $out .= $this->optin_button_script($optinAction);
464
 
465
- }
 
 
466
 
467
- echo $out.'</div>';
468
- }
469
-
470
- // faux-markdown, required for the help text rendering
471
- protected function markdown( $text ) {
472
- $replacements = array(
473
- // strip each line
474
- '!\s*[\r\n] *!' => "\n",
475
-
476
- // headers
477
- '!^=(.*?)=\s*$!m' => '<h3>\1</h3>',
478
-
479
- // bullets
480
- '!^(\* .*([\r\n]\* .*)*)$!m' => "<ul>\n\\1\n</ul>",
481
- '!^\* (.*?)$!m' => '<li>\1</li>',
482
- '!^(\d+\. .*([\r\n]\d+\. .*)*)$!m' => "<ol>\n\\1\n</ol>",
483
- '!^\d+\. (.*?)$!m' => '<li>\1</li>',
484
-
485
- // code block
486
- '!^(\t.*([\r\n]\t.*)*)$!m' => "<pre>\n\\1\n</pre>",
487
-
488
- // wrap p
489
- '!^([^<\t].*[^>])$!m' => '<p>\1</p>',
490
- // bold
491
- '!\*([^*]*?)\*!' => '<strong>\1</strong>',
492
- // code
493
- '!`([^`]*?)`!' => '<code>\1</code>',
494
- // links
495
- '!\[([^]]+)\]\(([^)]+)\)!' => '<a href="\2" target="_new">\1</a>',
496
- );
497
- $text = preg_replace(array_keys($replacements), array_values($replacements), $text);
498
-
499
- return $text;
500
- }
501
-
502
- public function render_screen_settings ($output, $current_screen) {
503
- if ( $current_screen->id != 'settings_page_yarpp' )
504
- return $output;
505
-
506
- $output .= "<div id='yarpp_extra_screen_settings'><label for='yarpp_display_code'><input type='checkbox' name='yarpp_display_code' id='yarpp_display_code'";
507
- $output .= checked($this->core->get_option('display_code'), true, false);
508
- $output .= " />";
509
- $output .= __('Show example code output', 'yarpp');
510
- $output .= '</label></div>';
511
-
512
- return $output;
513
- }
514
-
515
- // since 3.3
516
- public function enqueue() {
517
- $version = defined('WP_DEBUG') && WP_DEBUG ? time() : YARPP_VERSION;
518
- $screen = get_current_screen();
519
- if (!is_null($screen) && $screen->id === 'settings_page_yarpp') {
520
- wp_enqueue_style('yarpp_switch_options', plugins_url('style/options_switch.css', dirname(__FILE__)), array(), $version );
521
- wp_enqueue_script('yarpp_switch_options', yarpp_get_file_url_for_environment('js/options_switch.min.js', 'src/js/options_switch.js'), array('jquery'), $version );
522
-
523
- wp_enqueue_style('wp-pointer');
524
- wp_enqueue_style('yarpp_options', plugins_url('style/options_basic.css', dirname(__FILE__)), array(), $version );
525
- wp_enqueue_style('yarpp_remodal', plugins_url('lib/plugin-deactivation-survey/remodal.css', dirname(__FILE__)), array(), $version );
526
- wp_enqueue_style('yarpp_deactivate', plugins_url('lib/plugin-deactivation-survey/deactivate-feedback-form.css', dirname(__FILE__)), array(), $version );
527
- wp_enqueue_style('yarpp_default_theme', plugins_url('lib/plugin-deactivation-survey/remodal-default-theme.css', dirname(__FILE__)), array(), $version );
528
-
529
- wp_enqueue_script('postbox');
530
- wp_enqueue_script('wp-pointer');
531
- wp_enqueue_script('yarpp_remodal', plugins_url('lib/plugin-deactivation-survey/remodal.min.js', dirname(__FILE__)), array(), $version );
532
- wp_enqueue_script('yarpp_options', yarpp_get_file_url_for_environment('js/options_basic.min.js', 'src/js/options_basic.js'), array('jquery'), $version );
533
- // Localize the script with messages
534
- $translation_strings = array(
535
- 'alert_message' => __( 'This will clear all of YARPP’s cached related results.<br> Are you sure?', 'yarpp' ),
536
- 'model_title' => __( 'YARPP Cache', 'yarpp' ),
537
- 'success' => __( 'Cache cleared successfully!', 'yarpp' ),
538
- 'logo' => plugins_url('/images/icon-256x256.png', YARPP_MAIN_FILE),
539
- 'bgcolor'=> '#fff',
540
- 'forbidden' => __( 'You are not allowed to do this!', 'yarpp' ),
541
- 'nonce_fail' => __( 'You left this page open for too long. Please refresh the page and try again!', 'yarpp' ),
542
- 'error' => __( 'There is some error. Please refresh the page and try again!', 'yarpp' ),
543
- );
544
- wp_localize_script( 'yarpp_options', 'yarpp_messages', $translation_strings );
545
- }
546
-
547
- $metabox_post_types = $this->core->get_option('auto_display_post_types');
548
- if (!is_null($screen) && ($screen->id == 'post' || in_array( $screen->id, $metabox_post_types))) {
549
- wp_enqueue_script('yarpp_metabox', yarpp_get_file_url_for_environment('js/metabox.min.js', 'src/js/metabox.js'), array('jquery'), $version );
550
- }
551
- }
552
-
553
- public function settings_link($links, $file) {
554
- $this_plugin = dirname(plugin_basename(dirname(__FILE__))).'/yarpp.php';
555
- if($file == $this_plugin) {
556
- $links[] = '<a href="options-general.php?page=yarpp">'.__('Settings').'</a>';
557
- }
558
- return $links;
559
- }
560
-
561
- public function options_page() {
562
- $mode = (isset($_GET['mode'])) ? htmlentities(strtolower($_GET['mode'])) : null;
563
- if ($mode !== 'basic' && ($mode === 'pro' || $this->core->yarppPro['active'])){
564
- include_once(YARPP_DIR.'/includes/yarpp_pro_options.php');
565
- } else {
566
- include_once(YARPP_DIR . '/includes/yarpp_options.php');
567
- }
568
- }
569
- /**
570
- * Function to save the meta box.
571
- *
572
- * @param mixed $post_id Post ID.
573
- */
574
- public function yarpp_save_meta_box( $post_id ) {
575
- $yarpp_meta = array();
576
- // Return if we're doing an autosave.
577
- if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
578
- return;
579
- }
580
- // Verify our nonce here.
581
- if ( ! isset( $_POST['yarpp_display-nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['yarpp_display-nonce'] ), 'yarpp_display' ) ) {
582
- return;
583
- }
584
- if ( isset( $_POST['yarpp_display_for_this_post'] ) ) {
585
- $yarpp_meta['yarpp_display_for_this_post'] = 1;
586
- } else {
587
- $yarpp_meta['yarpp_display_for_this_post'] = 0;
588
- }
589
- update_post_meta( $post_id, 'yarpp_meta', $yarpp_meta );
590
- }
591
-
592
- // @since 3.4: don't actually compute results here, but use ajax instead
593
- public function metabox() {
594
- global $post;
595
- $metabox_post_types = $this->core->get_option('auto_display_post_types');
596
- $yarpp_meta = get_post_meta( $post->ID, 'yarpp_meta', true );
597
- if ( isset( $yarpp_meta['yarpp_display_for_this_post'] ) && 0 === $yarpp_meta['yarpp_display_for_this_post'] ) {
598
- $yarpp_disable_here = 0;
599
- } else {
600
- $yarpp_disable_here = 1;
601
- }
602
- ?>
603
- <style>
604
- .yarpp-metabox-options {
605
- margin: 10px 0;
606
- }
607
- #yarpp-related-posts .spinner {
608
- float: none; visibility: hidden; opacity: 1; margin: 5px 7px 0 7px;
609
- }
610
- </style>
611
- <?php if ( in_array( get_post_type(), $metabox_post_types ) ) { ?>
612
- <p>
613
- <input type="checkbox" id="yarpp_display_for_this_post" name="yarpp_display_for_this_post" <?php checked( 1, $yarpp_disable_here, true ); ?> />
614
- <label for="yarpp_display_for_this_post"><strong><?php esc_html_e( 'Automatically display related content on this post', 'yarpp' ); ?></strong></label>
615
- <br />
616
- <em><?php esc_html_e( 'If this is unchecked, then YARPP will not automatically insert the related posts at the end of this post.', 'yarpp' ); ?></em>
617
- </p>
618
- <?php } ?>
619
- <?php
620
- if ( !get_the_ID() ) {
621
- echo "<div><p>".__("Related posts will be displayed once you save this post",'yarpp').".</p></div>";
622
- } else {
623
- echo '<div id="yarpp-related-posts"><img height="20px" width="20px" src="' . esc_url( admin_url( 'images/spinner-2x.gif' ) ) . '" alt="loading..." /></div>';
624
- }
625
- wp_nonce_field( 'yarpp_display', 'yarpp_display-nonce', false );
626
- }
627
-
628
- // @since 3.3: default metaboxes to show:
629
- public function default_hidden_meta_boxes($hidden, $screen) {
630
- if ($screen->id === 'settings_page_yarpp') {
631
- $hidden = $this->core->default_hidden_metaboxes;
632
- }
633
- return $hidden;
634
- }
635
-
636
- // @since 4: UI to copy templates
637
- public function can_copy_templates() {
638
- $theme_dir = get_stylesheet_directory();
639
- // If we can't write to the theme, return false
640
- if (!is_dir($theme_dir) || !is_writable($theme_dir)) return false;
641
-
642
- require_once(ABSPATH.'wp-admin/includes/file.php');
643
- WP_Filesystem(false, get_stylesheet_directory());
644
- global $wp_filesystem;
645
- // direct method is the only method that I've tested so far
646
- return $wp_filesystem->method === 'direct';
647
- }
648
-
649
- public function copy_templates() {
650
- $templates_dir = trailingslashit(trailingslashit(YARPP_DIR).'yarpp-templates');
651
-
652
- require_once(ABSPATH.'wp-admin/includes/file.php');
653
- WP_Filesystem(false, get_stylesheet_directory());
654
- global $wp_filesystem;
655
- if ( $wp_filesystem->method !== 'direct') return false;
656
-
657
- return copy_dir($templates_dir, get_stylesheet_directory(), array('.svn'));
658
- }
659
-
660
- /*
661
- * AJAX SERVICES
662
- */
663
-
664
- public function ajax_display_exclude_terms() {
665
- check_ajax_referer('yarpp_display_exclude_terms');
666
-
667
- if (!isset($_REQUEST['taxonomy'])) return;
668
-
669
- $taxonomy = (string) $_REQUEST['taxonomy'];
670
-
671
- header("HTTP/1.1 200");
672
- header("Content-Type: text/html; charset=UTF-8");
673
-
674
- $exclude_tt_ids = wp_parse_id_list($this->core->get_option('exclude'));
675
- $exclude_term_ids = $this->get_term_ids_from_tt_ids( $taxonomy, $exclude_tt_ids );
676
- // if ('category' === $taxonomy) $exclude .= ','.get_option('default_category');
677
-
678
- $terms = get_terms($taxonomy, array(
679
- 'exclude' => $exclude_term_ids,
680
- 'hide_empty' => false,
681
- 'hierarchical' => false,
682
- 'number' => 100,
683
- 'offset' => $_REQUEST['offset']
684
- ));
685
-
686
- if ( !count($terms) ) {
687
- echo ':('; // no more :(
688
- exit;
689
- }
690
-
691
- foreach ($terms as $term) {
692
- echo "<span><input type='checkbox' name='exclude[{$term->term_taxonomy_id}]' id='exclude_{$term->term_taxonomy_id}' value='true' /> <label for='exclude_{$term->term_taxonomy_id}'>" . esc_html($term->name) . "</label></span> ";
693
- }
694
- exit;
695
- }
696
-
697
- public function get_term_ids_from_tt_ids( $taxonomy, $tt_ids ) {
698
- global $wpdb;
699
- $tt_ids = wp_parse_id_list($tt_ids);
700
- if ( empty($tt_ids) )
701
- return array();
702
- return $wpdb->get_col("select term_id from $wpdb->term_taxonomy where taxonomy = '{$taxonomy}' and term_taxonomy_id in (" . join(',', $tt_ids) . ")");
703
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
704
 
705
  /**
706
  * Handles populating the YARPP related metabox. When the page is initially loaded, this is called to populate it
707
- * but $_REQUEST['refresh'] isn't set because we're happy using the cached results. But when the user clicks the
708
- * "Refresh" button, $_REQUEST['refresh'] is set so we try to clear the cache and re-calculate the related content.
709
  */
710
- public function ajax_display() {
711
- check_ajax_referer('yarpp_display');
712
-
713
- if (!isset($_REQUEST['ID'])) return;
714
-
715
- $args = array(
716
- 'domain' => isset($_REQUEST['domain']) ? $_REQUEST['domain'] : 'website'
717
- );
718
- if(isset($_REQUEST['refresh']) && $this->core->cache instanceof YARPP_Cache){
719
- $this->core->cache->clear($_REQUEST['ID']);
720
- }
721
- $return = $this->core->display_related(absint($_REQUEST['ID']), $args, false);
722
-
723
- header("HTTP/1.1 200");
724
- header("Content-Type: text/html; charset=UTF-8");
725
- echo $return;
726
-
727
- die();
728
- }
729
-
730
- public function ajax_display_demo() {
731
- check_ajax_referer('yarpp_display_demo');
732
-
733
- header("HTTP/1.1 200");
734
- header("Content-Type: text/html; charset=UTF-8");
735
-
736
- $args = array(
737
- 'post_type' => array('post'),
738
- 'domain' => (isset($_REQUEST['domain'])) ? $_REQUEST['domain'] : 'website'
739
- );
740
-
741
- $return = $this->core->display_demo_related($args, false);
742
- echo preg_replace("/[\n\r]/",'',nl2br(htmlspecialchars($return)));
743
- exit;
744
- }
745
-
746
- /**
747
- * Display optin data in a human readable format on the help tab.
748
- */
749
- public function ajax_optin_data() {
750
- check_ajax_referer('yarpp_optin_data');
751
-
752
- header("HTTP/1.1 200");
753
- header("Content-Type: text/html; charset=UTF-8");
754
-
755
- $data = $this->core->optin_data();
756
- $this->core->pretty_echo($data);
757
- die();
758
- }
759
-
760
- public function ajax_optin_disable() {
761
- check_ajax_referer('yarpp_optin_disable');
762
-
763
- $this->core->set_option('optin', false);
764
-
765
- header("HTTP/1.1 200");
766
- header("Content-Type: text; charset=UTF-8");
767
- echo 'ok';
768
-
769
- die();
770
- }
771
-
772
- public function ajax_optin_enable() {
773
- check_ajax_referer('yarpp_optin_enable');
774
-
775
- $this->core->set_option('optin', true);
776
- $this->core->optin_ping();
777
-
778
- header("HTTP/1.1 200");
779
- header("Content-Type: text; charset=UTF-8");
780
- echo 'ok';
781
-
782
- die();
783
- }
784
-
785
- /**
786
- * Handles switching between Pro and Basic versions
787
- *
788
- * For example:
789
- * ../wp-admin/admin-ajax.php?action=yarpp_switch&go=pro
790
- * ../wp-admin/admin-ajax.php?action=yarpp_switch&go=basic
791
- *
792
- * @since 5.1.0
793
- */
794
- public function ajax_switch() {
795
- check_ajax_referer('yarpp_switch');
796
-
797
- if (!is_admin() ||
798
- !current_user_can('manage_options')) {
799
- return;
800
- }
801
-
802
- if (!isset($_GET['go']) || trim($_GET['go']) === '') die();
803
-
804
- $switch = htmlentities($_GET['go']);
805
-
806
- function switchYarppPro($status){
807
- $yarppPro = get_option('yarpp_pro');
808
- $yarpp = get_option('yarpp');
809
-
810
- if($status){
811
- $yarppPro['optin'] = (bool) $yarpp['optin'];
812
- $yarpp['optin'] = false;
813
- } else {
814
- $yarpp['optin'] = (bool) $yarppPro['optin'];
815
- }
816
 
817
- $yarppPro['active'] = $status;
818
- update_option('yarpp',$yarpp);
819
- update_option('yarpp_pro',$yarppPro);
820
-
821
- header("HTTP/1.1 200");
822
- header("Content-Type: text/plain; charset=UTF-8");
823
- die('ok');
824
- }
825
-
826
- switch ($switch){
827
- case 'basic':
828
- switchYarppPro(0);
829
- break;
830
- case 'pro':
831
- switchYarppPro(1);
832
- break;
833
- }
834
- }
835
-
836
- public function ajax_set_display_code() {
837
- check_ajax_referer( 'yarpp_set_display_code' );
838
-
839
- header("HTTP/1.1 200");
840
- header("Content-Type: text; charset=UTF-8");
841
-
842
- $data = $this->core->set_option( 'display_code', isset($_REQUEST['checked']) );
843
- echo 'ok';
844
- die();
845
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
846
 
847
  /**
848
  * Registers YARPP plugin for the deactivation survey library code.
@@ -864,15 +907,15 @@ class YARPP_Admin {
864
  $api_key = '';
865
  $verification_key = '';
866
  }
867
- $plugin_data = get_plugin_data(YARPP_MAIN_FILE, false, false);
868
- $plugins[] = (object) array(
869
- 'title_slugged' => sanitize_title($plugin_data['Name']),
870
- 'basename' => plugin_basename(YARPP_MAIN_FILE),
871
- 'logo' => plugins_url('/images/icon-256x256.png', YARPP_MAIN_FILE),
872
- 'api_server' => 'yarpp.com',
873
- 'script_cache_ver' => YARPP_VERSION,
874
- 'bgcolor' => '#fff',
875
- 'send' => array(
876
  'plugin_name' => 'yarpp',
877
  'plugin_version' => YARPP_VERSION,
878
  'api_key' => $api_key,
@@ -881,42 +924,50 @@ class YARPP_Admin {
881
  'domain' => site_url(),
882
  'language' => strtolower( get_bloginfo( 'language' ) ),
883
  ),
884
- 'reasons' => array(
885
- 'error' => esc_html__( 'I think I found a bug', 'yarpp' ),
886
- 'feature-missing' => esc_html__( 'It\'s missing a feature I need', 'yarpp' ),
887
- 'too-hard' => esc_html__( 'I couldn\'t figure out how to do something', 'yarpp' ),
888
- 'inefficient' => esc_html__( 'It\'s too slow or inefficient', 'yarpp' ),
889
- 'no-signup' => esc_html__( 'I don\'t want to signup', 'yarpp' ),
890
- 'temporary-deactivation' => esc_html__( 'Temporarily deactivating or troubleshooting', 'yarpp' ),
891
- 'other' => esc_html__( 'Other', 'yarpp' )
892
- ),
893
- 'reasons_needing_comment' => array(
894
- 'error',
895
- 'feature-missing',
896
- 'too-hard',
897
- 'other'
898
- ),
899
- 'translations' => array(
900
- 'quick_feedback' => esc_html__( 'Quick Feedback', 'yarpp' ),
901
- 'foreword' => esc_html__( 'If you would be kind enough, please tell us why you are deactivating the plugin:',
902
- 'yarpp' ),
903
- 'please_tell_us' => esc_html__( 'Please share anything you think might be helpful. The more we know about your problem, the faster we\'ll be able to fix it.',
904
- 'yarpp' ),
905
- 'cancel' => esc_html__( 'Cancel', 'yarpp' ),
906
- 'skip_and_deactivate' => esc_html__( 'Skip &amp; Deactivate', 'yarpp' ),
907
- 'submit_and_deactivate' => esc_html__( 'Submit &amp; Deactivate', 'yarpp' ),
908
- 'please_wait' => esc_html__( 'Please wait...', 'yarpp' ),
909
- 'thank_you' => esc_html__( 'Thank you!', 'yarpp' ),
910
- 'ask_for_support' => sprintf(
911
- esc_html__( 'Have you visited %1$sthe support forum%2$s and %3$sread the FAQs%2$s for help?',
912
- 'yarpp' ),
913
- '<a href="https://wordpress.org/support/plugin/yet-another-related-posts-plugin/" target="_blank" >',
914
- '</a>',
915
- '<a href="https://wordpress.org/plugins/yet-another-related-posts-plugin/#faq" target="_blank" >'
916
- ),
917
- 'email_request' => esc_html__( 'If you would like to tell us more, please leave your email here. We will be in touch (only for product feedback, nothing else).',
918
- 'yarpp' ),
919
- )
 
 
 
 
 
 
 
 
920
 
921
  );
922
 
5
  /**
6
  * @var YARPP
7
  */
8
+ public $core;
9
+ public $hook;
10
+
11
+ const ACTIVATE_TIMESTAMP_OPTION = 'yarpp_activate_timestamp';
12
+ const REVIEW_DISMISS_OPTION = 'yarpp_review_notice';
13
+ const REVIEW_FIRST_PERIOD = 518400; // 6 days in seconds
14
+ const REVIEW_LATER_PERIOD = 5184000; // 60 days in seconds
15
+ const REVIEW_FOREVER_PERIOD = 63113904; // 2 years in seconds
16
+
17
+ function __construct( &$core ) {
18
+ $this->core = &$core;
19
+
20
+ /* If action = flush and the nonce is correct, reset the cache */
21
+ if ( isset( $_GET['action'] ) && $_GET['action'] === 'flush' && check_ajax_referer( 'yarpp_cache_flush', false, false ) !== false ) {
22
+ $this->core->cache->flush();
23
+ wp_safe_redirect( admin_url( '/options-general.php?page=yarpp' ) );
24
+ exit;
25
+ }
26
+
27
+ /* If action = copy_templates and the nonce is correct, copy templates */
28
+ if ( isset( $_GET['action'] ) && $_GET['action'] === 'copy_templates' && check_ajax_referer( 'yarpp_copy_templates', false, false ) !== false ) {
29
+ $this->copy_templates();
30
+ wp_safe_redirect( admin_url( '/options-general.php?page=yarpp' ) );
31
+ exit;
32
+ }
33
+
34
+ add_action( 'admin_init', array( $this, 'ajax_register' ) );
35
+ add_action( 'admin_init', array( $this, 'review_register' ) );
36
+ add_action( 'admin_menu', array( $this, 'ui_register' ) );
37
+ add_action( 'save_post', array( $this, 'yarpp_save_meta_box' ) );
38
+
39
+ add_filter( 'current_screen', array( $this, 'settings_screen' ) );
40
+ add_filter( 'screen_settings', array( $this, 'render_screen_settings' ), 10, 2 );
41
+ add_filter( 'default_hidden_meta_boxes', array( $this, 'default_hidden_meta_boxes' ), 10, 2 );
42
+ add_filter( 'shareaholic_deactivate_feedback_form_plugins', array( $this, 'deactivation_survey_data' ) );
43
+ }
44
+
45
+ /**
46
+ * @since 4.0.3 Moved method to Core.
47
+ */
48
+ public function get_templates() {
49
+ return $this->core->get_templates();
50
+ }
51
+
52
+ /**
53
+ * Register Review notice
54
+ */
55
+ function review_register() {
56
+ self::check_review_dismissal();
57
+ self::check_plugin_review();
58
+ }
59
+
60
+ /**
61
+ * Register AJAX services
62
+ */
63
+ function ajax_register() {
64
+ if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
65
+ add_action( 'wp_ajax_yarpp_display_exclude_terms', array( $this, 'ajax_display_exclude_terms' ) );
66
+ add_action( 'wp_ajax_yarpp_display_demo', array( $this, 'ajax_display_demo' ) );
67
+ add_action( 'wp_ajax_yarpp_display', array( $this, 'ajax_display' ) );
68
+ add_action( 'wp_ajax_yarpp_optin_data', array( $this, 'ajax_optin_data' ) );
69
+ add_action( 'wp_ajax_yarpp_optin_enable', array( $this, 'ajax_optin_enable' ) );
70
+ add_action( 'wp_ajax_yarpp_optin_disable', array( $this, 'ajax_optin_disable' ) );
71
+ add_action( 'wp_ajax_yarpp_set_display_code', array( $this, 'ajax_set_display_code' ) );
72
+ add_action( 'wp_ajax_yarpp_switch', array( $this, 'ajax_switch' ) );
73
+ add_action( 'wp_ajax_yarpp_clear_cache', array( $this, 'ajax_clear_cache' ) );
74
+ }
75
+ }
76
+ /**
77
+ * Ajax callback for clearing the YARPP cache
78
+ *
79
+ * @since 5.13.0
80
+ */
81
+ public function ajax_clear_cache() {
82
+ if ( false === check_ajax_referer( 'clear_cache_yarpp', false, false ) ) {
83
+ echo 'nonce_fail';
84
+ } elseif ( current_user_can( 'manage_options' ) ) {
85
+ $this->core->cache->flush();
86
+ echo 'success';
87
+ } else {
88
+ echo 'forbidden';
89
+ }
90
+ wp_die();
91
+ }
92
+ /**
93
+ * Check review notice status for current user
94
+ *
95
+ * @since 5.1.0
96
+ */
97
+ public static function check_review_dismissal() {
98
+
99
+ global $current_user;
100
+ $user_id = $current_user->ID;
101
+
102
+ if ( ! is_admin() ||
103
+ ! isset( $_GET['_wpnonce'] ) ||
104
+ ! wp_verify_nonce( $_GET['_wpnonce'], 'review-nonce' ) ||
105
+ ! isset( $_GET['yarpp_defer_t'] ) ||
106
+ ! isset( $_GET[ self::REVIEW_DISMISS_OPTION ] ) ) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  return;
108
  }
109
 
110
+ $the_meta_array = array(
111
+ 'dismiss_defer_period' => $_GET['yarpp_defer_t'],
112
+ 'dismiss_timestamp' => time(),
113
+ );
114
+
115
+ update_user_meta( $user_id, self::REVIEW_DISMISS_OPTION, $the_meta_array );
116
+ }
117
+
118
+ /**
119
+ * Check if we should display the review notice
120
+ *
121
+ * @since 5.1.0
122
+ */
123
+ public static function check_plugin_review() {
124
+
125
+ global $current_user;
126
+ $user_id = $current_user->ID;
127
+
128
+ if ( ! current_user_can( 'publish_posts' ) ) {
129
+ return;
130
+ }
131
+
132
+ $show_review_notice = false;
133
+ $activation_timestamp = get_site_option( self::ACTIVATE_TIMESTAMP_OPTION );
134
+ $review_dismissal_array = get_user_meta( $user_id, self::REVIEW_DISMISS_OPTION, true );
135
+ $dismiss_defer_period = isset( $review_dismissal_array['dismiss_defer_period'] ) ? $review_dismissal_array['dismiss_defer_period'] : 0;
136
+ $dismiss_timestamp = isset( $review_dismissal_array['dismiss_timestamp'] ) ? $review_dismissal_array['dismiss_timestamp'] : time();
137
+
138
+ if ( $dismiss_timestamp + $dismiss_defer_period <= time() ) {
139
+ $show_review_notice = true;
140
+ }
141
+
142
+ if ( ! $activation_timestamp ) {
143
+ $activation_timestamp = time();
144
+ add_site_option( self::ACTIVATE_TIMESTAMP_OPTION, $activation_timestamp );
145
+ }
146
+
147
+ // display review message after a certain period of time after activation
148
+ if ( ( time() - $activation_timestamp > self::REVIEW_FIRST_PERIOD ) && $show_review_notice == true ) {
149
+ add_action( 'admin_notices', array( 'YARPP_Admin', 'display_review_notice' ) );
150
+ }
151
+ }
152
+
153
+ /**
154
+ * @since 5.1.0
155
+ */
156
+ public static function display_review_notice() {
157
+
158
+ $dismiss_forever = add_query_arg(
159
+ array(
160
+ self::REVIEW_DISMISS_OPTION => true,
161
+ 'yarpp_defer_t' => self::REVIEW_FOREVER_PERIOD,
162
+ )
163
+ );
164
+
165
+ $dismiss_forlater = add_query_arg(
166
+ array(
167
+ self::REVIEW_DISMISS_OPTION => true,
168
+ 'yarpp_defer_t' => self::REVIEW_LATER_PERIOD,
169
+ )
170
+ );
171
+
172
+ $dismiss_forever_url = wp_nonce_url( $dismiss_forever, 'review-nonce' );
173
+ $dismiss_forlater_url = wp_nonce_url( $dismiss_forlater, 'review-nonce' );
174
+
175
+ echo '
176
  <style>
177
  .yarpp-review-notice {
178
+ background-size: contain; background-position: right bottom; background-repeat: no-repeat; background-image: url(' . plugins_url( '../images/icon-256x256.png', __FILE__ ) . ');
179
  }
180
  .yarpp-review-notice-text {
181
  background: rgba(255, 255, 255, 0.9); text-shadow: white 0px 0px 10px; margin-right: 8em !important;
204
  </script>
205
 
206
  <div class="notice notice-info is-dismissible yarpp-review-notice">
207
+ <p class="yarpp-review-notice-text">' . __( 'Hey there! We noticed that you have had success using ', 'yarpp' ) . '<a href="' . admin_url( 'options-general.php?page=yarpp' ) . '">YARPP - Related Posts</a>! ' . __( 'Could you please do us a BIG favor and give us a quick 5-star rating on WordPress? It will boost our motivation and spread the word. We would really appreciate it 🤗 — Team YARPP', 'yarpp' ) . '
208
  <br />
209
  <br />
210
+ <a onClick="' . "yarpp_openWindowReload('https://wordpress.org/support/plugin/yet-another-related-posts-plugin/reviews/?rate=5#new-post', '$dismiss_forever_url')" . '" class="button button-primary">' . __( 'Ok, you deserve it', 'shareaholic' ) . '</a> &nbsp;
211
+ <a href="' . $dismiss_forlater_url . '">' . __( 'No, not good enough', 'yarpp' ) . '</a> &nbsp;
212
+ <a href="' . $dismiss_forever_url . '">' . __( 'I already did', 'yarpp' ) . '</a> &nbsp;
213
+ <a href="' . $dismiss_forever_url . '">' . __( 'Dismiss', 'yarpp' ) . '</a>
214
  </p>
215
  </div>';
216
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
+ function ui_register() {
219
+ global $wp_version;
 
 
220
 
221
+ if ( $this->core->db_options->after_activation() ) {
222
 
223
+ $this->core->db_options->delete_activation_flag();
224
+ $this->core->db_options->delete_upgrade_flag();
 
 
 
225
 
226
+ /* Optin/Pro message */
227
+ add_action( 'admin_notices', array( $this, 'install_notice' ) );
228
 
229
+ } elseif ( $this->core->db_options->after_upgrade() && current_user_can( 'manage_options' ) && $this->core->get_option( 'optin' ) ) {
230
+ add_action( 'admin_notices', array( $this, 'upgrade_notice' ) );
231
+ }
 
 
 
 
 
232
 
233
+ if ( $this->core->get_option( 'optin' ) ) {
234
+ $this->core->db_options->delete_upgrade_flag();
235
+ }
236
 
237
+ /*
238
+ * Setup Admin
239
+ */
240
+ $titleName = 'YARPP';
241
+ $this->hook = add_options_page( $titleName, $titleName, 'manage_options', 'yarpp', array( $this, 'options_page' ) );
242
+
243
+ /**
244
+ * @since 3.0.12 Add settings link to the plugins page.
245
+ */
246
+ add_filter( 'plugin_action_links', array( $this, 'settings_link' ), 10, 2 );
247
+
248
+ $metabox_post_types = $this->core->get_option( 'auto_display_post_types' );
249
+ if ( ! in_array( 'post', $metabox_post_types ) ) {
250
+ $metabox_post_types[] = 'post';
251
+ }
252
+
253
+ /**
254
+ * @since 3.0 Add meta box in Editor
255
+ */
256
+ if ( ! $this->core->yarppPro['active'] ) {
257
+ foreach ( $metabox_post_types as $post_type ) {
258
+ $title = __( 'YARPP: Related Posts', 'yarpp' );
259
+ add_meta_box( 'yarpp_relatedposts', $title, array( $this, 'metabox' ), $post_type, 'normal' );
260
+ }
261
+ }
262
+
263
+ /**
264
+ * @since 3.3: properly enqueue scripts for admin.
265
+ */
266
+ add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
267
+ }
268
+
269
+ /**
270
+ * @since 3.5.4 Only load metabox code if we're going to be on the settings page.
271
+ */
272
+ function settings_screen( $current_screen ) {
273
+ if ( $current_screen->id !== 'settings_page_yarpp' ) {
274
+ return $current_screen;
275
+ }
276
+
277
+ /**
278
+ * @since 3.3: Load options page sections as meta-boxes.
279
+ */
280
+ include_once YARPP_DIR . '/includes/yarpp_meta_boxes_hooks.php';
281
+
282
+ /**
283
+ * @since 3.5.5 Check that add_help_tab method callable (WP >= 3.3).
284
+ */
285
+ if ( is_callable( array( $current_screen, 'add_help_tab' ) ) ) {
286
+ $current_screen->add_help_tab(
287
+ array(
288
+ 'id' => 'faq',
289
+ 'title' => __( 'Frequently Asked Questions', 'yarpp' ),
290
+ 'callback' => array( &$this, 'help_faq' ),
291
+ )
292
+ );
293
+
294
+ $current_screen->add_help_tab(
295
+ array(
296
+ 'id' => 'dev',
297
+ 'title' => __( 'Developing with YARPP', 'yarpp' ),
298
+ 'callback' => array( &$this, 'help_dev' ),
299
+ )
300
+ );
301
+
302
+ $current_screen->add_help_tab(
303
+ array(
304
+ 'id' => 'optin',
305
+ 'title' => __( 'Optional Data Collection', 'yarpp' ),
306
+ 'callback' => array( &$this, 'help_optin' ),
307
+ )
308
+ );
309
+ }
310
+
311
+ return $current_screen;
312
+ }
313
+
314
+ private $readme = null;
315
+
316
+ public function help_faq() {
317
+ if ( is_null( $this->readme ) ) {
318
+ $this->readme = file_get_contents( YARPP_DIR . '/readme.txt' );
319
+ }
320
+
321
+ if ( preg_match( '!== Frequently Asked Questions ==(.*?)^==!sm', $this->readme, $matches ) ) {
322
+ echo $this->markdown( $matches[1] );
323
+ } else {
324
+ echo(
325
+ '<a href="https://wordpress.org/plugins/yet-another-related-posts-plugin/#faq">' .
326
+ __( 'Frequently Asked Questions', 'yarpp' ) .
327
+ '</a>'
328
+ );
329
+ }
330
+ }
331
+
332
+ public function help_dev() {
333
+ if ( is_null( $this->readme ) ) {
334
+ $this->readme = file_get_contents( YARPP_DIR . '/readme.txt' );
335
+ }
336
+
337
+ if ( preg_match( '!== Developing with YARPP ==(.*?)^==!sm', $this->readme, $matches ) ) {
338
+ echo $this->markdown( $matches[1] );
339
+ } else {
340
+ echo(
341
+ '<a href="https://wordpress.org/plugins/yet-another-related-posts-plugin/#faq" target="_blank">' .
342
+ __( 'Developing with YARPP', 'yarpp' ) .
343
+ '</a>'
344
+ );
345
+ }
346
+ }
347
+
348
+ public function help_optin() {
349
+ echo(
350
+ '<p>' .
351
+ __(
352
+ "With your permission, YARPP will send information about YARPP's settings, usage, and environment
353
+ back to a central server at ",
354
+ 'yarpp'
355
+ ) . '<code>yarpp.org</code>' . '.&nbsp;' .
356
+ '</p>' .
357
+ '<p>' .
358
+ 'We would really appreciate your input to help us continue to improve the product. We are primarily looking ' .
359
+ 'for country, domain, and date installed information.' .
360
+ '</p>' .
361
+ '<p>' .
362
+ __(
363
+ 'This information will be used to improve YARPP in the future and help decide future development
364
+ decisions for YARPP.',
365
+ 'yarpp'
366
+ ) . ' ' .
367
+ '</p>' .
368
+ '<p>' .
369
+ '<strong>' .
370
+ __(
371
+ 'Contributing this data will help make YARPP better for you and for other YARPP users.',
372
+ 'yarpp'
373
+ ) . '</strong>' .
374
+ '</p>'
375
+ );
376
+
377
+ echo(
378
+ '<p>' .
379
+ __( 'The following information is sent back to YARPP:', 'yarpp' ) .
380
+ '</p>' .
381
+ '<div id="optin_data_frame"></div>' .
382
+ '<p>' .
383
+ __( 'In addition, YARPP also loads an invisible pixel image with your YARPP results to know how often YARPP is being used.', 'yarpp' ) .
384
+ '</p>'
385
+ );
386
+ }
387
+
388
+ function the_optin_button( $action, $echo = false ) {
389
+ $status = ( $this->core->yarppPro['active'] ) ? 'disabled' : null;
390
+
391
+ if ( $action === 'disable' ) {
392
+ $out =
393
+ '<a id="yarpp-optin-button' . $status . '" class="button" ' . $status . '>' .
394
+ 'No, Thanks. Please <strong>' . $action . '</strong> sending usage data' .
395
+ '</a>';
396
+ } else {
397
+ $out =
398
+ '<a id="yarpp-optin-button' . $status . '" class="button" ' . $status . '>' .
399
+ 'Yes, <strong>' . $action . '</strong> sending usage data back to help improve YARPP' .
400
+ '</a>';
401
+ }
402
+
403
+ if ( $echo ) {
404
+ echo $out;
405
+ return null;
406
+ } else {
407
+ return $out;
408
+ }
409
+ }
410
+
411
+ function the_donothing_button( $msg, $echo = false ) {
412
+ $out = '<a href="options-general.php?page=yarpp" class="button">' . $msg . '</a>';
413
+ if ( $echo ) {
414
+ echo $out;
415
+ return null;
416
+ } else {
417
+ return $out;
418
+ }
419
+ }
420
+
421
+ function optin_button_script( $optinAction, $echo = false ) {
422
+ wp_nonce_field( 'yarpp_optin_' . $optinAction, 'yarpp_optin-nonce', false );
423
+
424
+ ob_start();
425
+ include YARPP_DIR . '/includes/optin_notice.js.php';
426
+ $out = ob_get_contents();
427
+ ob_end_clean();
428
+
429
+ if ( $echo ) {
430
+ echo $out;
431
+ return null;
432
+ } else {
433
+ return $out;
434
+ }
435
+ }
436
+
437
+ function upgrade_notice() {
438
+ $optinAction = ( $this->core->get_option( 'optin' ) ) ? 'disable' : 'enable';
439
+ $this->optin_notice( 'upgrade', $optinAction );
440
+ }
441
+
442
+ public function install_notice() {
443
+ $optinAction = ( $this->core->get_option( 'optin' ) ) ? 'disable' : 'enable';
444
+ $this->optin_notice( 'install', $optinAction );
445
+ }
446
+
447
+ public function optin_notice( $type = false, $optinAction = 'disable' ) {
448
+ $screen = get_current_screen();
449
+ if ( is_null( $screen ) || $screen->id == 'settings_page_yarpp' ) {
450
+ return;
451
+ }
452
+
453
+ switch ( $type ) {
454
+ case 'upgrade':
455
+ $this->core->db_options->delete_upgrade_flag();
456
+ break;
457
+ case 'install':
458
+ default:
459
+ $user = get_current_user_id();
460
+ update_user_option( $user, 'yarpp_saw_optin', true );
461
+ }
462
+
463
+ $out = '<div class="updated fade"><p>';
464
+
465
+ if ( $type === 'upgrade' ) {
466
+ $out .= '<strong>' . sprintf( __( '%1$s updated successfully.' ), 'Yet Another Related Posts Plugin' ) . '</strong>';
467
+ }
468
+
469
+ if ( $type === 'install' ) {
470
+ $tmp = __( 'Thank you for installing <span>Yet Another Related Posts Plugin</span>!', 'yarpp' );
471
+ $out .= '<strong>' . str_replace( '<span>', '<span style="font-style:italic; font-weight: inherit;">', $tmp ) . '</strong>';
472
+ }
473
+
474
+ if ( $this->core->yarppPro['active'] ) {
475
+
476
+ $out .=
477
+ '<p>' .
478
+ 'You currently have <strong>YARPP Basic</strong> and <strong>YARPP Pro</strong> enabled.<br/><br/>' .
479
+ '<a href="options-general.php?page=yarpp" class="button">Take me to the settings page</a>' .
480
+ '</p>';
481
+
482
+ } else {
483
+
484
+ $out .= '</p><p>';
485
+ if ( $optinAction !== 'disable' ) {
486
+ $out .= $this->the_donothing_button( 'No, thanks' ) . '&nbsp;&nbsp;';
487
+ } else {
488
+ $out .= $this->the_donothing_button( 'Yes, keep sending usage data' ) . '&nbsp;&nbsp;';
489
+ }
490
+ $out .= $this->the_optin_button( $optinAction );
491
+ $out .= $this->optin_button_script( $optinAction );
492
+
493
+ }
494
+
495
+ echo $out . '</div>';
496
+ }
497
+
498
+ // faux-markdown, required for the help text rendering
499
+ protected function markdown( $text ) {
500
+ $replacements = array(
501
+ // strip each line
502
+ '!\s*[\r\n] *!' => "\n",
503
+
504
+ // headers
505
+ '!^=(.*?)=\s*$!m' => '<h3>\1</h3>',
506
+
507
+ // bullets
508
+ '!^(\* .*([\r\n]\* .*)*)$!m' => "<ul>\n\\1\n</ul>",
509
+ '!^\* (.*?)$!m' => '<li>\1</li>',
510
+ '!^(\d+\. .*([\r\n]\d+\. .*)*)$!m' => "<ol>\n\\1\n</ol>",
511
+ '!^\d+\. (.*?)$!m' => '<li>\1</li>',
512
+
513
+ // code block
514
+ '!^(\t.*([\r\n]\t.*)*)$!m' => "<pre>\n\\1\n</pre>",
515
+
516
+ // wrap p
517
+ '!^([^<\t].*[^>])$!m' => '<p>\1</p>',
518
+ // bold
519
+ '!\*([^*]*?)\*!' => '<strong>\1</strong>',
520
+ // code
521
+ '!`([^`]*?)`!' => '<code>\1</code>',
522
+ // links
523
+ '!\[([^]]+)\]\(([^)]+)\)!' => '<a href="\2" target="_new">\1</a>',
524
+ );
525
+ $text = preg_replace( array_keys( $replacements ), array_values( $replacements ), $text );
526
+
527
+ return $text;
528
+ }
529
+
530
+ public function render_screen_settings( $output, $current_screen ) {
531
+ if ( $current_screen->id != 'settings_page_yarpp' ) {
532
+ return $output;
533
+ }
534
+
535
+ $output .= "<div id='yarpp_extra_screen_settings'><label for='yarpp_display_code'><input type='checkbox' name='yarpp_display_code' id='yarpp_display_code'";
536
+ $output .= checked( $this->core->get_option( 'display_code' ), true, false );
537
+ $output .= ' />';
538
+ $output .= __( 'Show example code output', 'yarpp' );
539
+ $output .= '</label></div>';
540
+
541
+ return $output;
542
+ }
543
+
544
+ // since 3.3
545
+ public function enqueue() {
546
+ $version = defined( 'WP_DEBUG' ) && WP_DEBUG ? time() : YARPP_VERSION;
547
+ $screen = get_current_screen();
548
+ if ( ! is_null( $screen ) && $screen->id === 'settings_page_yarpp' ) {
549
+ wp_enqueue_style( 'yarpp_switch_options', plugins_url( 'style/options_switch.css', dirname( __FILE__ ) ), array(), $version );
550
+ wp_enqueue_script( 'yarpp_switch_options', yarpp_get_file_url_for_environment( 'js/options_switch.min.js', 'src/js/options_switch.js' ), array( 'jquery' ), $version );
551
+
552
+ wp_enqueue_style( 'wp-pointer' );
553
+ wp_enqueue_style( 'yarpp_options', plugins_url( 'style/options_basic.css', dirname( __FILE__ ) ), array(), $version );
554
+ wp_enqueue_style( 'yarpp_remodal', plugins_url( 'lib/plugin-deactivation-survey/remodal.css', dirname( __FILE__ ) ), array(), $version );
555
+ wp_enqueue_style( 'yarpp_deactivate', plugins_url( 'lib/plugin-deactivation-survey/deactivate-feedback-form.css', dirname( __FILE__ ) ), array(), $version );
556
+ wp_enqueue_style( 'yarpp_default_theme', plugins_url( 'lib/plugin-deactivation-survey/remodal-default-theme.css', dirname( __FILE__ ) ), array(), $version );
557
+
558
+ wp_enqueue_script( 'postbox' );
559
+ wp_enqueue_script( 'wp-pointer' );
560
+ wp_enqueue_script( 'yarpp_remodal', plugins_url( 'lib/plugin-deactivation-survey/remodal.min.js', dirname( __FILE__ ) ), array(), $version );
561
+ wp_enqueue_script( 'yarpp_options', yarpp_get_file_url_for_environment( 'js/options_basic.min.js', 'src/js/options_basic.js' ), array( 'jquery' ), $version );
562
+ // Localize the script with messages
563
+ $translation_strings = array(
564
+ 'alert_message' => __( 'This will clear all of YARPP’s cached related results.<br> Are you sure?', 'yarpp' ),
565
+ 'model_title' => __( 'YARPP Cache', 'yarpp' ),
566
+ 'success' => __( 'Cache cleared successfully!', 'yarpp' ),
567
+ 'logo' => plugins_url( '/images/icon-256x256.png', YARPP_MAIN_FILE ),
568
+ 'bgcolor' => '#fff',
569
+ 'forbidden' => __( 'You are not allowed to do this!', 'yarpp' ),
570
+ 'nonce_fail' => __( 'You left this page open for too long. Please refresh the page and try again!', 'yarpp' ),
571
+ 'error' => __( 'There is some error. Please refresh the page and try again!', 'yarpp' ),
572
+ );
573
+ wp_localize_script( 'yarpp_options', 'yarpp_messages', $translation_strings );
574
+ }
575
+
576
+ $metabox_post_types = $this->core->get_option( 'auto_display_post_types' );
577
+ if ( ! is_null( $screen ) && ( $screen->id == 'post' || in_array( $screen->id, $metabox_post_types ) ) ) {
578
+ wp_enqueue_script( 'yarpp_metabox', yarpp_get_file_url_for_environment( 'js/metabox.min.js', 'src/js/metabox.js' ), array( 'jquery' ), $version );
579
+ }
580
+ }
581
+
582
+ public function settings_link( $links, $file ) {
583
+ $this_plugin = dirname( plugin_basename( dirname( __FILE__ ) ) ) . '/yarpp.php';
584
+ if ( $file == $this_plugin ) {
585
+ $links[] = '<a href="options-general.php?page=yarpp">' . __( 'Settings' ) . '</a>';
586
+ }
587
+ return $links;
588
+ }
589
+
590
+ public function options_page() {
591
+ $mode = ( isset( $_GET['mode'] ) ) ? htmlentities( strtolower( $_GET['mode'] ) ) : null;
592
+ if ( $mode !== 'basic' && ( $mode === 'pro' || $this->core->yarppPro['active'] ) ) {
593
+ include_once YARPP_DIR . '/includes/yarpp_pro_options.php';
594
+ } else {
595
+ include_once YARPP_DIR . '/includes/yarpp_options.php';
596
+ }
597
+ }
598
+ /**
599
+ * Function to save the meta box.
600
+ *
601
+ * @param mixed $post_id Post ID.
602
+ */
603
+ public function yarpp_save_meta_box( $post_id ) {
604
+ $yarpp_meta = array();
605
+ // Return if we're doing an autosave.
606
+ if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
607
+ return;
608
+ }
609
+ // Verify our nonce here.
610
+ if ( ! isset( $_POST['yarpp_display-nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['yarpp_display-nonce'] ), 'yarpp_display' ) ) {
611
+ return;
612
+ }
613
+ if ( isset( $_POST['yarpp_display_for_this_post'] ) ) {
614
+ $yarpp_meta['yarpp_display_for_this_post'] = 1;
615
+ } else {
616
+ $yarpp_meta['yarpp_display_for_this_post'] = 0;
617
+ }
618
+ update_post_meta( $post_id, 'yarpp_meta', $yarpp_meta );
619
+ }
620
+
621
+ // @since 3.4: don't actually compute results here, but use ajax instead
622
+ public function metabox() {
623
+ global $post;
624
+ $metabox_post_types = $this->core->get_option( 'auto_display_post_types' );
625
+ $yarpp_meta = get_post_meta( $post->ID, 'yarpp_meta', true );
626
+ if ( isset( $yarpp_meta['yarpp_display_for_this_post'] ) && 0 === $yarpp_meta['yarpp_display_for_this_post'] ) {
627
+ $yarpp_disable_here = 0;
628
+ } else {
629
+ $yarpp_disable_here = 1;
630
+ }
631
+ ?>
632
+ <style>
633
+ .yarpp-metabox-options {
634
+ margin: 10px 0;
635
+ }
636
+ #yarpp-related-posts .spinner {
637
+ float: none; visibility: hidden; opacity: 1; margin: 5px 7px 0 7px;
638
+ }
639
+ </style>
640
+ <?php if ( in_array( get_post_type(), $metabox_post_types ) ) { ?>
641
+ <p>
642
+ <input type="checkbox" id="yarpp_display_for_this_post" name="yarpp_display_for_this_post" <?php checked( 1, $yarpp_disable_here, true ); ?> />
643
+ <label for="yarpp_display_for_this_post"><strong><?php esc_html_e( 'Automatically display related content on this post', 'yarpp' ); ?></strong></label>
644
+ <br />
645
+ <em><?php esc_html_e( 'If this is unchecked, then YARPP will not automatically insert the related posts at the end of this post.', 'yarpp' ); ?></em>
646
+ </p>
647
+ <?php } ?>
648
+ <?php
649
+ if ( ! get_the_ID() ) {
650
+ echo '<div><p>' . __( 'Related posts will be displayed once you save this post', 'yarpp' ) . '.</p></div>';
651
+ } else {
652
+ echo '<div id="yarpp-related-posts"><img height="20px" width="20px" src="' . esc_url( admin_url( 'images/spinner-2x.gif' ) ) . '" alt="loading..." /></div>';
653
+ }
654
+ wp_nonce_field( 'yarpp_display', 'yarpp_display-nonce', false );
655
+ }
656
+
657
+ // @since 3.3: default metaboxes to show:
658
+ public function default_hidden_meta_boxes( $hidden, $screen ) {
659
+ if ( $screen->id === 'settings_page_yarpp' ) {
660
+ $hidden = $this->core->default_hidden_metaboxes;
661
+ }
662
+ return $hidden;
663
+ }
664
+
665
+ // @since 4: UI to copy templates
666
+ public function can_copy_templates() {
667
+ $theme_dir = get_stylesheet_directory();
668
+ // If we can't write to the theme, return false
669
+ if ( ! is_dir( $theme_dir ) || ! is_writable( $theme_dir ) ) {
670
+ return false;
671
+ }
672
+
673
+ require_once ABSPATH . 'wp-admin/includes/file.php';
674
+ WP_Filesystem( false, get_stylesheet_directory() );
675
+ global $wp_filesystem;
676
+ // direct method is the only method that I've tested so far
677
+ return $wp_filesystem->method === 'direct';
678
+ }
679
+
680
+ public function copy_templates() {
681
+ $templates_dir = trailingslashit( trailingslashit( YARPP_DIR ) . 'yarpp-templates' );
682
+
683
+ require_once ABSPATH . 'wp-admin/includes/file.php';
684
+ WP_Filesystem( false, get_stylesheet_directory() );
685
+ global $wp_filesystem;
686
+ if ( $wp_filesystem->method !== 'direct' ) {
687
+ return false;
688
+ }
689
+
690
+ return copy_dir( $templates_dir, get_stylesheet_directory(), array( '.svn' ) );
691
+ }
692
+
693
+ /*
694
+ * AJAX SERVICES
695
+ */
696
+
697
+ public function ajax_display_exclude_terms() {
698
+ check_ajax_referer( 'yarpp_display_exclude_terms' );
699
+
700
+ if ( ! isset( $_REQUEST['taxonomy'] ) ) {
701
+ return;
702
+ }
703
+
704
+ $taxonomy = (string) $_REQUEST['taxonomy'];
705
+
706
+ header( 'HTTP/1.1 200' );
707
+ header( 'Content-Type: text/html; charset=UTF-8' );
708
+
709
+ $exclude_tt_ids = wp_parse_id_list( $this->core->get_option( 'exclude' ) );
710
+ $exclude_term_ids = $this->get_term_ids_from_tt_ids( $taxonomy, $exclude_tt_ids );
711
+ // if ('category' === $taxonomy) $exclude .= ','.get_option('default_category');
712
+
713
+ $terms = get_terms(
714
+ $taxonomy,
715
+ array(
716
+ 'exclude' => $exclude_term_ids,
717
+ 'hide_empty' => false,
718
+ 'hierarchical' => false,
719
+ 'number' => 100,
720
+ 'offset' => $_REQUEST['offset'],
721
+ )
722
+ );
723
+
724
+ if ( ! count( $terms ) ) {
725
+ echo ':('; // no more :(
726
+ exit;
727
+ }
728
+
729
+ foreach ( $terms as $term ) {
730
+ echo "<span><input type='checkbox' name='exclude[{$term->term_taxonomy_id}]' id='exclude_{$term->term_taxonomy_id}' value='true' /> <label for='exclude_{$term->term_taxonomy_id}'>" . esc_html( $term->name ) . '</label></span> ';
731
+ }
732
+ exit;
733
+ }
734
+
735
+ public function get_term_ids_from_tt_ids( $taxonomy, $tt_ids ) {
736
+ global $wpdb;
737
+ $tt_ids = wp_parse_id_list( $tt_ids );
738
+ if ( empty( $tt_ids ) ) {
739
+ return array();
740
+ }
741
+ return $wpdb->get_col( "select term_id from $wpdb->term_taxonomy where taxonomy = '{$taxonomy}' and term_taxonomy_id in (" . join( ',', $tt_ids ) . ')' );
742
+ }
743
 
744
  /**
745
  * Handles populating the YARPP related metabox. When the page is initially loaded, this is called to populate it
746
+ * but $_REQUEST['refresh'] isn't set because we're happy using the cached results. But when the user clicks the
747
+ * "Refresh" button, $_REQUEST['refresh'] is set so we try to clear the cache and re-calculate the related content.
748
  */
749
+ public function ajax_display() {
750
+ check_ajax_referer( 'yarpp_display' );
751
+
752
+ if ( ! isset( $_REQUEST['ID'] ) ) {
753
+ return;
754
+ }
755
+
756
+ $args = array(
757
+ 'domain' => isset( $_REQUEST['domain'] ) ? $_REQUEST['domain'] : 'website',
758
+ );
759
+ if ( isset( $_REQUEST['refresh'] ) && $this->core->cache instanceof YARPP_Cache ) {
760
+ $this->core->cache->clear( $_REQUEST['ID'] );
761
+ }
762
+ $return = $this->core->display_related( absint( $_REQUEST['ID'] ), $args, false );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763
 
764
+ header( 'HTTP/1.1 200' );
765
+ header( 'Content-Type: text/html; charset=UTF-8' );
766
+ echo $return;
767
+
768
+ die();
769
+ }
770
+
771
+ public function ajax_display_demo() {
772
+ check_ajax_referer( 'yarpp_display_demo' );
773
+
774
+ header( 'HTTP/1.1 200' );
775
+ header( 'Content-Type: text/html; charset=UTF-8' );
776
+
777
+ $args = array(
778
+ 'post_type' => array( 'post' ),
779
+ 'domain' => ( isset( $_REQUEST['domain'] ) ) ? $_REQUEST['domain'] : 'website',
780
+ );
781
+
782
+ $return = $this->core->display_demo_related( $args, false );
783
+ echo preg_replace( "/[\n\r]/", '', nl2br( htmlspecialchars( $return ) ) );
784
+ exit;
785
+ }
786
+
787
+ /**
788
+ * Display optin data in a human readable format on the help tab.
789
+ */
790
+ public function ajax_optin_data() {
791
+ check_ajax_referer( 'yarpp_optin_data' );
792
+
793
+ header( 'HTTP/1.1 200' );
794
+ header( 'Content-Type: text/html; charset=UTF-8' );
795
+
796
+ $data = $this->core->optin_data();
797
+ $this->core->pretty_echo( $data );
798
+ die();
799
+ }
800
+
801
+ public function ajax_optin_disable() {
802
+ check_ajax_referer( 'yarpp_optin_disable' );
803
+
804
+ $this->core->set_option( 'optin', false );
805
+
806
+ header( 'HTTP/1.1 200' );
807
+ header( 'Content-Type: text; charset=UTF-8' );
808
+ echo 'ok';
809
+
810
+ die();
811
+ }
812
+
813
+ public function ajax_optin_enable() {
814
+ check_ajax_referer( 'yarpp_optin_enable' );
815
+
816
+ $this->core->set_option( 'optin', true );
817
+ $this->core->optin_ping();
818
+
819
+ header( 'HTTP/1.1 200' );
820
+ header( 'Content-Type: text; charset=UTF-8' );
821
+ echo 'ok';
822
+
823
+ die();
824
+ }
825
+
826
+ /**
827
+ * Handles switching between Pro and Basic versions
828
+ *
829
+ * For example:
830
+ * ../wp-admin/admin-ajax.php?action=yarpp_switch&go=pro
831
+ * ../wp-admin/admin-ajax.php?action=yarpp_switch&go=basic
832
+ *
833
+ * @since 5.1.0
834
+ */
835
+ public function ajax_switch() {
836
+ check_ajax_referer( 'yarpp_switch' );
837
+
838
+ if ( ! is_admin() ||
839
+ ! current_user_can( 'manage_options' ) ) {
840
+ return;
841
+ }
842
+
843
+ if ( ! isset( $_GET['go'] ) || trim( $_GET['go'] ) === '' ) {
844
+ die();
845
+ }
846
+
847
+ $switch = htmlentities( $_GET['go'] );
848
+
849
+ function switchYarppPro( $status ) {
850
+ $yarppPro = get_option( 'yarpp_pro' );
851
+ $yarpp = get_option( 'yarpp' );
852
+
853
+ if ( $status ) {
854
+ $yarppPro['optin'] = (bool) $yarpp['optin'];
855
+ $yarpp['optin'] = false;
856
+ } else {
857
+ $yarpp['optin'] = (bool) $yarppPro['optin'];
858
+ }
859
+
860
+ $yarppPro['active'] = $status;
861
+ update_option( 'yarpp', $yarpp );
862
+ update_option( 'yarpp_pro', $yarppPro );
863
+
864
+ header( 'HTTP/1.1 200' );
865
+ header( 'Content-Type: text/plain; charset=UTF-8' );
866
+ die( 'ok' );
867
+ }
868
+
869
+ switch ( $switch ) {
870
+ case 'basic':
871
+ switchYarppPro( 0 );
872
+ break;
873
+ case 'pro':
874
+ switchYarppPro( 1 );
875
+ break;
876
+ }
877
+ }
878
+
879
+ public function ajax_set_display_code() {
880
+ check_ajax_referer( 'yarpp_set_display_code' );
881
+
882
+ header( 'HTTP/1.1 200' );
883
+ header( 'Content-Type: text; charset=UTF-8' );
884
+
885
+ $data = $this->core->set_option( 'display_code', isset( $_REQUEST['checked'] ) );
886
+ echo 'ok';
887
+ die();
888
+ }
889
 
890
  /**
891
  * Registers YARPP plugin for the deactivation survey library code.
907
  $api_key = '';
908
  $verification_key = '';
909
  }
910
+ $plugin_data = get_plugin_data( YARPP_MAIN_FILE, false, false );
911
+ $plugins[] = (object) array(
912
+ 'title_slugged' => sanitize_title( $plugin_data['Name'] ),
913
+ 'basename' => plugin_basename( YARPP_MAIN_FILE ),
914
+ 'logo' => plugins_url( '/images/icon-256x256.png', YARPP_MAIN_FILE ),
915
+ 'api_server' => 'yarpp.com',
916
+ 'script_cache_ver' => YARPP_VERSION,
917
+ 'bgcolor' => '#fff',
918
+ 'send' => array(
919
  'plugin_name' => 'yarpp',
920
  'plugin_version' => YARPP_VERSION,
921
  'api_key' => $api_key,
924
  'domain' => site_url(),
925
  'language' => strtolower( get_bloginfo( 'language' ) ),
926
  ),
927
+ 'reasons' => array(
928
+ 'error' => esc_html__( 'I think I found a bug', 'yarpp' ),
929
+ 'feature-missing' => esc_html__( 'It\'s missing a feature I need', 'yarpp' ),
930
+ 'too-hard' => esc_html__( 'I couldn\'t figure out how to do something', 'yarpp' ),
931
+ 'inefficient' => esc_html__( 'It\'s too slow or inefficient', 'yarpp' ),
932
+ 'no-signup' => esc_html__( 'I don\'t want to signup', 'yarpp' ),
933
+ 'temporary-deactivation' => esc_html__( 'Temporarily deactivating or troubleshooting', 'yarpp' ),
934
+ 'other' => esc_html__( 'Other', 'yarpp' ),
935
+ ),
936
+ 'reasons_needing_comment' => array(
937
+ 'error',
938
+ 'feature-missing',
939
+ 'too-hard',
940
+ 'other',
941
+ ),
942
+ 'translations' => array(
943
+ 'quick_feedback' => esc_html__( 'Quick Feedback', 'yarpp' ),
944
+ 'foreword' => esc_html__(
945
+ 'If you would be kind enough, please tell us why you are deactivating the plugin:',
946
+ 'yarpp'
947
+ ),
948
+ 'please_tell_us' => esc_html__(
949
+ 'Please share anything you think might be helpful. The more we know about your problem, the faster we\'ll be able to fix it.',
950
+ 'yarpp'
951
+ ),
952
+ 'cancel' => esc_html__( 'Cancel', 'yarpp' ),
953
+ 'skip_and_deactivate' => esc_html__( 'Skip &amp; Deactivate', 'yarpp' ),
954
+ 'submit_and_deactivate' => esc_html__( 'Submit &amp; Deactivate', 'yarpp' ),
955
+ 'please_wait' => esc_html__( 'Please wait...', 'yarpp' ),
956
+ 'thank_you' => esc_html__( 'Thank you!', 'yarpp' ),
957
+ 'ask_for_support' => sprintf(
958
+ esc_html__(
959
+ 'Have you visited %1$sthe support forum%2$s and %3$sread the FAQs%2$s for help?',
960
+ 'yarpp'
961
+ ),
962
+ '<a href="https://wordpress.org/support/plugin/yet-another-related-posts-plugin/" target="_blank" >',
963
+ '</a>',
964
+ '<a href="https://wordpress.org/plugins/yet-another-related-posts-plugin/#faq" target="_blank" >'
965
+ ),
966
+ 'email_request' => esc_html__(
967
+ 'If you would like to tell us more, please leave your email here. We will be in touch (only for product feedback, nothing else).',
968
+ 'yarpp'
969
+ ),
970
+ ),
971
 
972
  );
973
 
classes/YARPP_Block.php CHANGED
@@ -20,7 +20,9 @@ if ( ! class_exists( 'YARPP_Block', false ) && function_exists( 'register_block_
20
  add_action( 'init', array( $this, 'yarpp_gutenberg_block_func' ), 100 );
21
  add_filter( 'block_categories', array( $this, 'yarpp_block_categories' ), 10, 2 );
22
  add_action( 'enqueue_block_editor_assets', array( $this, 'yarpp_enqueue_block_editor_assets' ) );
23
- }/**
 
 
24
  * YARPP enqueue thumbnail stylesheet.
25
  */
26
  public function yarpp_enqueue_block_editor_assets() {
@@ -41,7 +43,7 @@ if ( ! class_exists( 'YARPP_Block', false ) && function_exists( 'register_block_
41
  // If preview then return preview image.
42
  if ( $is_preview && ! empty( $block_attributes['yarpp_preview'] ) ) {
43
  $preview_image = YARPP_URL . '/images/yarpp-grid.svg';
44
- return '<img style="width:100%;" src="' . esc_attr( $preview_image ) . '">';
45
  }
46
  $yarpp_args = array(
47
  'domain' => 'block',
20
  add_action( 'init', array( $this, 'yarpp_gutenberg_block_func' ), 100 );
21
  add_filter( 'block_categories', array( $this, 'yarpp_block_categories' ), 10, 2 );
22
  add_action( 'enqueue_block_editor_assets', array( $this, 'yarpp_enqueue_block_editor_assets' ) );
23
+ }
24
+
25
+ /**
26
  * YARPP enqueue thumbnail stylesheet.
27
  */
28
  public function yarpp_enqueue_block_editor_assets() {
43
  // If preview then return preview image.
44
  if ( $is_preview && ! empty( $block_attributes['yarpp_preview'] ) ) {
45
  $preview_image = YARPP_URL . '/images/yarpp-grid.svg';
46
+ return '<img style="width:100%;" src="' . esc_url( $preview_image ) . '">';
47
  }
48
  $yarpp_args = array(
49
  'domain' => 'block',
classes/YARPP_Cache.php CHANGED
@@ -1,528 +1,573 @@
1
- <?php
2
- abstract class YARPP_Cache {
3
- /**
4
- * @var YARPP
5
- */
6
- protected $core;
7
- /**
8
- * During "YARPP Time", we add a bunch of filters to modify WP_Query
9
- * @var bool
10
- */
11
- protected $yarpp_time = false;
12
-
13
- /**
14
- * Keep track of when we're calculating, so YARPP core can know when to back off from initiating calculating
15
- * related again.
16
- * @var bool
17
- */
18
- protected $discovering_keywords = false;
19
- public $score_override = false;
20
- public $online_limit = false;
21
- public $last_sql;
22
- function __construct( &$core ) {
23
- $this->core = &$core;
24
- $this->name = __($this->name, 'yarpp');
25
- }
26
-
27
- function add_signature( $query ) {
28
- $query->yarpp_cache_type = $this->name;
29
- }
30
-
31
- /**
32
- * GENERAL CACHE CONTROL
33
- */
34
- public function is_yarpp_time() {
35
- return $this->yarpp_time;
36
- }
37
- public function flush() {
38
- }
39
-
40
- public function setup() {
41
- }
42
-
43
- public function upgrade( $last_version ) {
44
- }
45
-
46
- /*
47
- * POST CACHE CONTROL
48
- */
49
-
50
- /**
51
- * Ensures the YARPP cache is primed (if not, primes it).
52
- * Can return early if YARPP shouldn't run, for some reason.
53
- * @param int $reference_ID post ID to which we're finding related content
54
- * @param bool $force forces refreshing the cache
55
- * @param array $args @see YARPP::display_related()
56
- *
57
- * @return bool|string (YARPP_NO_RELATED | YARPP_RELATED | YARPP_DONT_RUN | false if no good input)
58
- */
59
- function enforce($reference_ID, $force = false, $args = array()) {
60
- /**
61
- * @since 3.5.3 Don't compute on revisions.
62
- * wp_is_post_revision will return the id of the revision parent instead.
63
- */
64
- if ($the_post = wp_is_post_revision($reference_ID)) $reference_ID = $the_post;
65
- if (!is_int($reference_ID)) return false;
66
-
67
- $status = $this->is_cached($reference_ID);
68
- $status = apply_filters('yarpp_cache_enforce_status', $status, $reference_ID);
69
-
70
- // There's a stop signal:
71
- if ($status === YARPP_DONT_RUN) return YARPP_DONT_RUN;
72
-
73
- // If not cached, process now:
74
- if ($status === YARPP_NOT_CACHED || $force) $status = $this->update((int) $reference_ID, $args);
75
- // Despite our earlier check, somehow the database doesn't seem to be setup properly
76
- if ($status === YARPP_DONT_RUN) return YARPP_DONT_RUN;
77
- // There are no related posts
78
- if ($status === YARPP_NO_RELATED) return YARPP_NO_RELATED;
79
-
80
- // There are results
81
- return YARPP_RELATED;
82
- }
83
-
84
- /**
85
- * @param int $reference_ID
86
- * @return string YARPP_NO_RELATED | YARPP_RELATED | YARPP_NOT_CACHED
87
- */
88
- public function is_cached($reference_ID) {
89
- return YARPP_NOT_CACHED;
90
- }
91
- public function clear($reference_ID) {
92
- }
93
-
94
- /*
95
- * POST STATUS INTERACTIONS
96
- */
97
- /**
98
- * Clear the cache for this entry and for all posts which are "related" to it.
99
- * @since 3.2 This is called when a post is deleted.
100
- */
101
- function delete_post($post_ID) {
102
- // Clear the cache for this post.
103
- $this->clear((int) $post_ID);
104
-
105
- // Find all "peers" which list this post as a related post and clear their caches
106
- if ($peers = $this->related(null, (int) $post_ID)) $this->clear($peers);
107
- }
108
-
109
- /**
110
- * @since 3.2.1 Handle various post_status transitions
111
- */
112
- function transition_post_status( $new_status, $old_status, $post ) {
113
- $post_ID = $post->ID;
114
- /**
115
- * @since 3.4 Don't compute on revisions
116
- * @since 3.5 Compute on the parent instead
117
- */
118
- if ($the_post = wp_is_post_revision($post_ID)) $post_ID = $the_post;
119
- // Un-publish
120
- if ($old_status === 'publish' && $new_status !== 'publish') {
121
- // Find all "peers" which list this post as a related post and clear their caches
122
- if ($peers = $this->related(null, (int) $post_ID)) $this->clear($peers);
123
- }
124
-
125
- // Publish
126
- if ($new_status === 'publish') {
127
- /*
128
- * Find everything which is related to this post, and clear them,
129
- * so that this post might show up as related to them.
130
- */
131
- if ($related = $this->related($post_ID, null)) $this->clear($related);
132
- }
133
- /**
134
- * @since 3.4 Simply clear the cache on save; don't recompute.
135
- */
136
- $this->clear((int) $post_ID);
137
- }
138
-
139
- function set_score_override_flag($q) {
140
- if ($this->is_yarpp_time()) {
141
- $this->score_override = (isset($q->query_vars['orderby']) && $q->query_vars['orderby'] === 'score');
142
-
143
- if (!empty($q->query_vars['showposts'])) {
144
- $this->online_limit = $q->query_vars['showposts'];
145
- } else {
146
- $this->online_limit = false;
147
- }
148
- } else {
149
- $this->score_override = false;
150
- $this->online_limit = false;
151
- }
152
- }
153
- /**
154
- * SQL!
155
- */
156
- protected function sql($reference_ID = false, $args = array()) {
157
- global $wpdb, $post;
158
-
159
- if (is_object($post) && !$reference_ID) {
160
- $reference_ID = $post->ID;
161
- }
162
-
163
- if (!is_object($post) || $reference_ID != $post->ID) {
164
- $reference_post = get_post($reference_ID);
165
- } else {
166
- $reference_post = $post;
167
- }
168
-
169
- $options = array(
170
- 'threshold',
171
- 'show_pass_post',
172
- 'past_only',
173
- 'weight',
174
- 'require_tax',
175
- 'exclude',
176
- 'recent',
177
- 'limit'
178
- );
179
- extract($this->core->parse_args($args, $options));
180
- // The maximum number of items we'll ever want to cache
181
- $limit = max($limit, $this->core->get_option('rss_limit'));
182
-
183
- // Fetch keywords
184
- $keywords = $this->get_keywords($reference_ID);
185
-
186
- // SELECT
187
- $newsql = $wpdb->prepare(
188
- "SELECT %d as reference_ID, ID, ",
189
- $reference_ID
190
- );
191
- $newsql .= 'ROUND(0';
192
- if (isset($weight) && is_array($weight)){
193
- if (isset($weight['body']) && (int) $weight['body']) {
194
- $newsql .= $wpdb->prepare(
195
- " + (MATCH (post_content) AGAINST (%s)) * %d",
196
- $keywords['body'],
197
- $weight['body']
198
- );
199
- }
200
- if (isset($weight['title']) && (int) $weight['title']) {
201
- $newsql .= $wpdb->prepare(
202
- " + (MATCH (post_title) AGAINST (%s)) * %d",
203
- $keywords['title'],
204
- $weight['title']
205
- );
206
- }
207
-
208
- // Build tax criteria query parts based on the weights
209
- if(isset($weight['tax']) && is_array($weight['tax'])){
210
- foreach ((array) $weight['tax'] as $tax => $tax_weight) {
211
- $newsql .= " + ".$this->tax_criteria($reference_ID, $tax)." * ".intval($tax_weight);
212
- }
213
- }
214
- }
215
-
216
- $newsql .= ',4) as score';
217
-
218
- $newsql .= "\n from $wpdb->posts \n";
219
-
220
- $exclude_tt_ids = wp_parse_id_list($exclude);
221
- if (count($exclude_tt_ids) || (isset($weight) && isset($weight['tax']) && count((array) $weight['tax'])) || count($require_tax)) {
222
- $newsql .= "left join $wpdb->term_relationships as terms on ( terms.object_id = {$wpdb->posts}.ID ) \n";
223
- }
224
-
225
- /*
226
- * Where
227
- */
228
-
229
- $newsql .= " where post_status in ( 'publish', 'static' )";
230
- /**
231
- * @since 3.1.8 Revised $past_only option
232
- */
233
- if ($past_only) {
234
- $newsql .= $wpdb->prepare(
235
- " and post_date <= %s ",
236
- $reference_post->post_date
237
- );
238
- }
239
- if (!$show_pass_post){
240
- $newsql .= " and post_password ='' ";
241
- }
242
- if ((bool) $recent){
243
- $recent_parts = explode(' ', $recent);
244
- if(count($recent_parts) === 2 && isset($recent_parts[0], $recent_parts[1])){
245
- $recent_number = $recent_parts[0];
246
- if(in_array(
247
- $recent_parts[1],
248
- array_keys(
249
- $this->core->recent_units()
250
- )
251
- )){
252
- $recent_unit = $recent_parts[1];
253
- } else {
254
- $recent_unit = 'day';
255
- }
256
- $newsql .= $wpdb->prepare(
257
- " and post_date > date_sub(now(), interval %d {$recent_unit}) ",
258
- $recent_number
259
- );
260
- }
261
-
262
- }
263
-
264
- $post_types = $this->core->get_query_post_types($reference_post, $args);
265
- $sanitized_post_types = (array)array_map(
266
- function($item){
267
- global $wpdb;
268
- return $wpdb->prepare('%s', $item);
269
- },
270
- $post_types
271
- );
272
- $newsql .= ' and post_type IN (' . implode(',',$sanitized_post_types). ')';
273
- $post_ids_to_exclude = array( ( int )$reference_ID);
274
- $include_sticky_posts = $this->core->get_option( 'include_sticky_posts' );
275
- if ( 1 !== (int) $include_sticky_posts ) {
276
- $get_sticky_posts = get_option( 'sticky_posts' );
277
- $post_ids_to_exclude = wp_parse_args( $get_sticky_posts, $post_ids_to_exclude );
278
- }
279
- // Allow to filter the exluded post ids.
280
- $post_ids_to_exclude = apply_filters( 'yarpp_post_ids_to_exclude', $post_ids_to_exclude, $reference_ID );
281
- $post__not_in = implode( ',', array_map( 'absint', $post_ids_to_exclude ) );
282
- $newsql .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
283
- // GROUP BY
284
- $newsql .= "\n group by ID \n";
285
-
286
- // HAVING
287
- // number_format fix suggested by vkovalcik! :)
288
- $safethreshold = number_format(max($threshold,0.1), 2, '.', '');
289
- /**
290
- * @since 3.5.3: ID=0 is a special value; never save such a result.
291
- */
292
- $newsql .= $wpdb->prepare(
293
- " having score >= %f and ID != 0",
294
- $safethreshold
295
- );
296
- if (count($exclude_tt_ids)) {
297
- // $exclude_tt_ids already ran through wp_parse_id_list
298
- $newsql .= " and bit_or(terms.term_taxonomy_id in (".join(',', $exclude_tt_ids).")) = 0";
299
- }
300
-
301
- $post_type_taxonomies = get_object_taxonomies($reference_post->post_type, 'names');
302
- foreach ((array) $require_tax as $tax => $number) {
303
- // Double-check the reference post's type actually supports this taxonomy. If not,
304
- // we'll never find any related posts, as the reference post can't be assigned any terms in this taxonomy.
305
- // See https://wordpress.org/support/topic/require-at-least-one-taxonomy-limited-to-taxonomies-available-the-post-type/
306
- if(in_array($tax, $post_type_taxonomies)){
307
- $newsql .= $wpdb->prepare(
308
- ' and '.$this->tax_criteria($reference_ID, $tax).' >= %d',
309
- $number
310
- );
311
- }
312
- }
313
-
314
- $newsql .= $wpdb->prepare(
315
- " order by score desc limit %d",
316
- $limit
317
- );
318
-
319
- if ($this->core->debug) echo "<!-- $newsql -->";
320
-
321
- $this->last_sql = $newsql;
322
-
323
- return $newsql;
324
- }
325
-
326
- private function tax_criteria($reference_ID, $taxonomy) {
327
- $terms = get_the_terms( $reference_ID, $taxonomy );
328
- // if there are no terms of that tax or WP error.
329
- if ( is_wp_error( $terms ) || false === $terms ) {
330
- return '(1 = 0)';
331
- }
332
- $make_term_object_to_array = wp_list_pluck( $terms, 'term_taxonomy_id' );
333
- // If empty then return.
334
- if ( empty( $make_term_object_to_array ) ) {
335
- return '(1 = 0)';
336
- }
337
- $tt_ids = join( ',', $make_term_object_to_array );
338
- return "count(distinct if( terms.term_taxonomy_id in (" . $tt_ids . "), terms.term_taxonomy_id, null ))";
339
- }
340
- /*
341
- * KEYWORDS
342
- */
343
- /**
344
- * @param int $ID
345
- * @param string $type body | title | all
346
- * @return string|array depending on whether "all" were requested or not
347
- */
348
- public function get_keywords($ID, $type = 'all') {
349
- if (!$ID = absint($ID)) return false;
350
- $keywords = array(
351
- 'body' => $this->body_keywords($ID),
352
- 'title' => $this->title_keywords($ID)
353
- );
354
- if (empty($keywords)) return false;
355
-
356
- if ($type === 'all') return $keywords;
357
- return $keywords[$type];
358
- }
359
-
360
- protected function title_keywords($ID, $max = 20) {
361
- return apply_filters('yarpp_title_keywords', $this->extract_keywords(get_the_title($ID), $max, $ID), $max, $ID);
362
- }
363
- protected function body_keywords( $ID, $max = 20 ) {
364
- $post = get_post( $ID );
365
- if ( empty( $post ) ) {
366
- return '';
367
- }
368
- $this->discovering_keywords = true;
369
- $body_content = apply_filters( 'the_content', $post->post_content );
370
- $this->discovering_keywords = false;
371
- $keywords = apply_filters( 'yarpp_body_keywords', $this->extract_keywords( $body_content, $max, $ID ), $max, $ID );
372
-
373
- return $keywords;
374
- }
375
-
376
- private function extract_keywords( $html, $max = 20, $ID = 0 ) {
377
-
378
- /**
379
- * @filter yarpp_extract_keywords
380
- *
381
- * Use this filter to override YARPP's built-in keyword computation
382
- * Return values should be a string of space-delimited words
383
- *
384
- * @param $keywords
385
- * @param $html unfiltered HTML content
386
- * @param (int) $max maximum number of keywords
387
- * @param (int) $ID
388
- */
389
- if ($keywords = apply_filters('yarpp_extract_keywords', false, $html, $max, $ID)) return $keywords;
390
- if (defined('WPLANG')) {
391
- switch ( substr(WPLANG, 0, 2) ) {
392
- case 'de':
393
- $lang = 'de_DE';
394
- break;
395
- case 'it':
396
- $lang = 'it_IT';
397
- break;
398
- case 'pl':
399
- $lang = 'pl_PL';
400
- break;
401
- case 'bg':
402
- $lang = 'bg_BG';
403
- break;
404
- case 'fr':
405
- $lang = 'fr_FR';
406
- break;
407
- case 'cs':
408
- $lang = 'cs_CZ';
409
- break;
410
- case 'nl':
411
- $lang = 'nl_NL';
412
- break;
413
- default:
414
- $lang = 'en_US';
415
- break;
416
- }
417
- }
418
- else {
419
- $lang = 'en_US';
420
- }
421
-
422
- $words_file = YARPP_DIR.'/lang/words-'.$lang.'.php';
423
- if (file_exists($words_file)) include($words_file);
424
- if (!isset($overusedwords)) $overusedwords = array();
425
-
426
- // strip tags and html entities
427
- $text = preg_replace('/&(#x[0-9a-f]+|#[0-9]+|[a-zA-Z]+);/', '', strip_tags($html) );
428
-
429
- // 3.2.2: ignore soft hyphens
430
- // Requires PHP 5: http://bugs.php.net/bug.php?id=25670
431
- $softhyphen = html_entity_decode('&#173;',ENT_NOQUOTES,'UTF-8');
432
- $text = str_replace($softhyphen, '', $text);
433
-
434
- $charset = get_option('blog_charset');
435
- if ( function_exists('mb_split') && !empty($charset) ) {
436
- mb_regex_encoding($charset);
437
- $wordlist = mb_split('\s*\W+\s*', mb_strtolower($text, $charset));
438
- } else
439
- $wordlist = preg_split('%\s*\W+\s*%', strtolower($text));
440
-
441
- // Build an array of the unique words and number of times they occur.
442
- $tokens = array_count_values($wordlist);
443
-
444
- // Remove the stop words from the list.
445
- $overusedwords = apply_filters( 'yarpp_keywords_overused_words', $overusedwords );
446
- if ( is_array($overusedwords) ) {
447
- foreach ($overusedwords as $word) {
448
- unset($tokens[$word]);
449
- }
450
- }
451
- // Remove words which are only a letter
452
- foreach (array_keys($tokens) as $word) {
453
- if ( function_exists('mb_strlen') )
454
- if (mb_strlen($word) < 2) unset($tokens[$word]);
455
- else
456
- if (strlen($word) < 2) unset($tokens[$word]);
457
- }
458
-
459
- arsort($tokens, SORT_NUMERIC);
460
-
461
- $types = array_keys($tokens);
462
-
463
- if (count($types) > $max)
464
- $types = array_slice($types, 0, $max);
465
- return implode(' ', $types);
466
- }
467
-
468
- /**
469
- * Does a database query without emitting any warnings if there's an SQL error. (Although they will still show up
470
- * in the Query Monitor plugin, which is a feature.)
471
- * Throws an exception if there is an error.
472
- * @param string $wpdb_method method on WPDB to call
473
- * @param array $args array of arguments to pass it.
474
- *
475
- * @return mixed|WP_Error
476
- */
477
- protected function query_safely($wpdb_method, $args) {
478
- global $wpdb;
479
- $value = call_user_func_array(
480
- array( $wpdb, $wpdb_method ),
481
- $args
482
- );
483
- if ( $wpdb->last_error ) {
484
- return new WP_Error( 'yarpp_bad_db', $wpdb->last_error );
485
- }
486
-
487
- return $value;
488
- }
489
-
490
- /*
491
- * Returns whether or not we're currently discovering the keywords on a reference post.
492
- * (This is a very bad time to start looking for related posts! So YARPP core should be able to detect this.)
493
- * @return bool
494
- */
495
- public function discovering_keywords(){
496
- return $this->discovering_keywords;
497
- }
498
-
499
- /**
500
- * Replaces the WP_Query's orderby clause (which normally orders by date) to orderby score instead
501
- * @param string $sql
502
- * @return string
503
- */
504
- protected function orderby_score($sql){
505
- global $wpdb;
506
- return str_replace(
507
- array(
508
- "$wpdb->posts.post_date ASC",
509
- "$wpdb->posts.post_date DESC"
510
- ),
511
- array(
512
- "score ASC, {$wpdb->posts}.ID ASC",
513
- "score DESC, {$wpdb->posts}.ID ASC"
514
- ),
515
- $sql
516
- );
517
- }
518
-
519
- /**
520
- * Updates the cache.
521
- * @param int $reference_ID post ID to which we're finding related posts
522
- * @param array $args @see YARPP::display_related()
523
- * @return string (YARPP_NO_RELATED | YARPP_RELATED | YARPP_DONT_RUN)
524
- */
525
- protected function update($reference_ID, $args = array()) {
526
- return YARPP_RELATED;
527
- }
528
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ abstract class YARPP_Cache {
3
+ /**
4
+ * @var YARPP
5
+ */
6
+ protected $core;
7
+ /**
8
+ * During "YARPP Time", we add a bunch of filters to modify WP_Query
9
+ *
10
+ * @var bool
11
+ */
12
+ protected $yarpp_time = false;
13
+
14
+ /**
15
+ * Keep track of when we're calculating, so YARPP core can know when to back off from initiating calculating
16
+ * related again.
17
+ *
18
+ * @var bool
19
+ */
20
+ protected $discovering_keywords = false;
21
+ public $score_override = false;
22
+ public $online_limit = false;
23
+ public $last_sql;
24
+ function __construct( &$core ) {
25
+ $this->core = &$core;
26
+ $this->name = __( $this->name, 'yarpp' );
27
+ }
28
+
29
+ function add_signature( $query ) {
30
+ $query->yarpp_cache_type = $this->name;
31
+ }
32
+
33
+ /**
34
+ * GENERAL CACHE CONTROL
35
+ */
36
+ public function is_yarpp_time() {
37
+ return $this->yarpp_time;
38
+ }
39
+ public function flush() {
40
+ }
41
+
42
+ public function setup() {
43
+ }
44
+
45
+ public function upgrade( $last_version ) {
46
+ }
47
+
48
+ /*
49
+ * POST CACHE CONTROL
50
+ */
51
+
52
+ /**
53
+ * Ensures the YARPP cache is primed (if not, primes it).
54
+ * Can return early if YARPP shouldn't run, for some reason.
55
+ *
56
+ * @param int $reference_ID post ID to which we're finding related content
57
+ * @param bool $force forces refreshing the cache
58
+ * @param array $args @see YARPP::display_related()
59
+ *
60
+ * @return bool|string (YARPP_NO_RELATED | YARPP_RELATED | YARPP_DONT_RUN | false if no good input)
61
+ */
62
+ function enforce( $reference_ID, $force = false, $args = array() ) {
63
+ /**
64
+ * @since 3.5.3 Don't compute on revisions.
65
+ * wp_is_post_revision will return the id of the revision parent instead.
66
+ */
67
+ if ( $the_post = wp_is_post_revision( $reference_ID ) ) {
68
+ $reference_ID = $the_post;
69
+ }
70
+ if ( ! is_int( $reference_ID ) ) {
71
+ return false;
72
+ }
73
+
74
+ $status = $this->is_cached( $reference_ID );
75
+ $status = apply_filters( 'yarpp_cache_enforce_status', $status, $reference_ID );
76
+
77
+ // There's a stop signal:
78
+ if ( $status === YARPP_DONT_RUN ) {
79
+ return YARPP_DONT_RUN;
80
+ }
81
+
82
+ // If not cached, process now:
83
+ if ( $status === YARPP_NOT_CACHED || $force ) {
84
+ $status = $this->update( (int) $reference_ID, $args );
85
+ }
86
+ // Despite our earlier check, somehow the database doesn't seem to be setup properly
87
+ if ( $status === YARPP_DONT_RUN ) {
88
+ return YARPP_DONT_RUN;
89
+ }
90
+ // There are no related posts
91
+ if ( $status === YARPP_NO_RELATED ) {
92
+ return YARPP_NO_RELATED;
93
+ }
94
+
95
+ // There are results
96
+ return YARPP_RELATED;
97
+ }
98
+
99
+ /**
100
+ * @param int $reference_ID
101
+ * @return string YARPP_NO_RELATED | YARPP_RELATED | YARPP_NOT_CACHED
102
+ */
103
+ public function is_cached( $reference_ID ) {
104
+ return YARPP_NOT_CACHED;
105
+ }
106
+ public function clear( $reference_ID ) {
107
+ }
108
+
109
+ /*
110
+ * POST STATUS INTERACTIONS
111
+ */
112
+ /**
113
+ * Clear the cache for this entry and for all posts which are "related" to it.
114
+ *
115
+ * @since 3.2 This is called when a post is deleted.
116
+ */
117
+ function delete_post( $post_ID ) {
118
+ // Clear the cache for this post.
119
+ $this->clear( (int) $post_ID );
120
+
121
+ // Find all "peers" which list this post as a related post and clear their caches
122
+ if ( $peers = $this->related( null, (int) $post_ID ) ) {
123
+ $this->clear( $peers );
124
+ }
125
+ }
126
+
127
+ /**
128
+ * @since 3.2.1 Handle various post_status transitions
129
+ */
130
+ function transition_post_status( $new_status, $old_status, $post ) {
131
+ $post_ID = $post->ID;
132
+ /**
133
+ * @since 3.4 Don't compute on revisions
134
+ * @since 3.5 Compute on the parent instead
135
+ */
136
+ if ( $the_post = wp_is_post_revision( $post_ID ) ) {
137
+ $post_ID = $the_post;
138
+ }
139
+ // Un-publish
140
+ if ( $old_status === 'publish' && $new_status !== 'publish' ) {
141
+ // Find all "peers" which list this post as a related post and clear their caches
142
+ if ( $peers = $this->related( null, (int) $post_ID ) ) {
143
+ $this->clear( $peers );
144
+ }
145
+ }
146
+
147
+ // Publish
148
+ if ( $new_status === 'publish' ) {
149
+ /*
150
+ * Find everything which is related to this post, and clear them,
151
+ * so that this post might show up as related to them.
152
+ */
153
+ if ( $related = $this->related( $post_ID, null ) ) {
154
+ $this->clear( $related );
155
+ }
156
+ }
157
+ /**
158
+ * @since 3.4 Simply clear the cache on save; don't recompute.
159
+ */
160
+ $this->clear( (int) $post_ID );
161
+ }
162
+
163
+ function set_score_override_flag( $q ) {
164
+ if ( $this->is_yarpp_time() ) {
165
+ $this->score_override = ( isset( $q->query_vars['orderby'] ) && $q->query_vars['orderby'] === 'score' );
166
+
167
+ if ( ! empty( $q->query_vars['showposts'] ) ) {
168
+ $this->online_limit = $q->query_vars['showposts'];
169
+ } else {
170
+ $this->online_limit = false;
171
+ }
172
+ } else {
173
+ $this->score_override = false;
174
+ $this->online_limit = false;
175
+ }
176
+ }
177
+ /**
178
+ * SQL!
179
+ */
180
+ protected function sql( $reference_ID = false, $args = array() ) {
181
+ global $wpdb, $post;
182
+
183
+ if ( is_object( $post ) && ! $reference_ID ) {
184
+ $reference_ID = $post->ID;
185
+ }
186
+
187
+ if ( ! is_object( $post ) || $reference_ID != $post->ID ) {
188
+ $reference_post = get_post( $reference_ID );
189
+ } else {
190
+ $reference_post = $post;
191
+ }
192
+
193
+ $options = array(
194
+ 'threshold',
195
+ 'show_pass_post',
196
+ 'past_only',
197
+ 'weight',
198
+ 'require_tax',
199
+ 'exclude',
200
+ 'recent',
201
+ 'limit',
202
+ );
203
+ extract( $this->core->parse_args( $args, $options ) );
204
+ // The maximum number of items we'll ever want to cache
205
+ $limit = max( $limit, $this->core->get_option( 'rss_limit' ) );
206
+
207
+ // Fetch keywords
208
+ $keywords = $this->get_keywords( $reference_ID );
209
+
210
+ // SELECT
211
+ $newsql = $wpdb->prepare(
212
+ 'SELECT %d as reference_ID, ID, ',
213
+ $reference_ID
214
+ );
215
+ $newsql .= 'ROUND(0';
216
+ if ( isset( $weight ) && is_array( $weight ) ) {
217
+ if ( isset( $weight['body'] ) && (int) $weight['body'] ) {
218
+ $newsql .= $wpdb->prepare(
219
+ ' + (MATCH (post_content) AGAINST (%s)) * %d',
220
+ $keywords['body'],
221
+ $weight['body']
222
+ );
223
+ }
224
+ if ( isset( $weight['title'] ) && (int) $weight['title'] ) {
225
+ $newsql .= $wpdb->prepare(
226
+ ' + (MATCH (post_title) AGAINST (%s)) * %d',
227
+ $keywords['title'],
228
+ $weight['title']
229
+ );
230
+ }
231
+
232
+ // Build tax criteria query parts based on the weights
233
+ if ( isset( $weight['tax'] ) && is_array( $weight['tax'] ) ) {
234
+ foreach ( (array) $weight['tax'] as $tax => $tax_weight ) {
235
+ $newsql .= ' + ' . $this->tax_criteria( $reference_ID, $tax ) . ' * ' . intval( $tax_weight );
236
+ }
237
+ }
238
+ }
239
+
240
+ $newsql .= ',4) as score';
241
+
242
+ $newsql .= "\n from $wpdb->posts \n";
243
+
244
+ $exclude_tt_ids = wp_parse_id_list( $exclude );
245
+ if ( count( $exclude_tt_ids ) || ( isset( $weight ) && isset( $weight['tax'] ) && count( (array) $weight['tax'] ) ) || count( $require_tax ) ) {
246
+ $newsql .= "left join $wpdb->term_relationships as terms on ( terms.object_id = {$wpdb->posts}.ID ) \n";
247
+ }
248
+
249
+ /*
250
+ * Where
251
+ */
252
+
253
+ $newsql .= " where post_status in ( 'publish', 'static' )";
254
+ /**
255
+ * @since 3.1.8 Revised $past_only option
256
+ */
257
+ if ( $past_only ) {
258
+ $newsql .= $wpdb->prepare(
259
+ ' and post_date <= %s ',
260
+ $reference_post->post_date
261
+ );
262
+ }
263
+ if ( ! $show_pass_post ) {
264
+ $newsql .= " and post_password ='' ";
265
+ }
266
+ if ( (bool) $recent ) {
267
+ $recent_parts = explode( ' ', $recent );
268
+ if ( count( $recent_parts ) === 2 && isset( $recent_parts[0], $recent_parts[1] ) ) {
269
+ $recent_number = $recent_parts[0];
270
+ if ( in_array(
271
+ $recent_parts[1],
272
+ array_keys(
273
+ $this->core->recent_units()
274
+ )
275
+ ) ) {
276
+ $recent_unit = $recent_parts[1];
277
+ } else {
278
+ $recent_unit = 'day';
279
+ }
280
+ $newsql .= $wpdb->prepare(
281
+ " and post_date > date_sub(now(), interval %d {$recent_unit}) ",
282
+ $recent_number
283
+ );
284
+ }
285
+ }
286
+
287
+ $post_types = $this->core->get_query_post_types( $reference_post, $args );
288
+ $sanitized_post_types = (array) array_map(
289
+ function( $item ) {
290
+ global $wpdb;
291
+ return $wpdb->prepare( '%s', $item );
292
+ },
293
+ $post_types
294
+ );
295
+ $newsql .= ' and post_type IN (' . implode( ',', $sanitized_post_types ) . ')';
296
+ $post_ids_to_exclude = array( (int) $reference_ID );
297
+ $include_sticky_posts = $this->core->get_option( 'include_sticky_posts' );
298
+ if ( 1 !== (int) $include_sticky_posts ) {
299
+ $get_sticky_posts = get_option( 'sticky_posts' );
300
+ $post_ids_to_exclude = wp_parse_args( $get_sticky_posts, $post_ids_to_exclude );
301
+ }
302
+ // Allow to filter the exluded post ids.
303
+ $post_ids_to_exclude = apply_filters( 'yarpp_post_ids_to_exclude', $post_ids_to_exclude, $reference_ID );
304
+ $post__not_in = implode( ',', array_map( 'absint', $post_ids_to_exclude ) );
305
+ $newsql .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
306
+ // GROUP BY
307
+ $newsql .= "\n group by ID \n";
308
+
309
+ // HAVING
310
+ // number_format fix suggested by vkovalcik! :)
311
+ $safethreshold = number_format( max( $threshold, 0.1 ), 2, '.', '' );
312
+ /**
313
+ * @since 3.5.3: ID=0 is a special value; never save such a result.
314
+ */
315
+ $newsql .= $wpdb->prepare(
316
+ ' having score >= %f and ID != 0',
317
+ $safethreshold
318
+ );
319
+ if ( count( $exclude_tt_ids ) ) {
320
+ // $exclude_tt_ids already ran through wp_parse_id_list
321
+ $newsql .= ' and bit_or(terms.term_taxonomy_id in (' . join( ',', $exclude_tt_ids ) . ')) = 0';
322
+ }
323
+
324
+ $post_type_taxonomies = get_object_taxonomies( $reference_post->post_type, 'names' );
325
+ foreach ( (array) $require_tax as $tax => $number ) {
326
+ // Double-check the reference post's type actually supports this taxonomy. If not,
327
+ // we'll never find any related posts, as the reference post can't be assigned any terms in this taxonomy.
328
+ // See https://wordpress.org/support/topic/require-at-least-one-taxonomy-limited-to-taxonomies-available-the-post-type/
329
+ if ( in_array( $tax, $post_type_taxonomies ) ) {
330
+ $newsql .= $wpdb->prepare(
331
+ ' and ' . $this->tax_criteria( $reference_ID, $tax ) . ' >= %d',
332
+ $number
333
+ );
334
+ }
335
+ }
336
+
337
+ $newsql .= $wpdb->prepare(
338
+ ' order by score desc limit %d',
339
+ $limit
340
+ );
341
+
342
+ if ( $this->core->debug ) {
343
+ echo "<!-- $newsql -->";
344
+ }
345
+
346
+ $this->last_sql = $newsql;
347
+
348
+ return $newsql;
349
+ }
350
+
351
+ private function tax_criteria( $reference_ID, $taxonomy ) {
352
+ $terms = get_the_terms( $reference_ID, $taxonomy );
353
+ // if there are no terms of that tax or WP error.
354
+ if ( is_wp_error( $terms ) || false === $terms ) {
355
+ return '(1 = 0)';
356
+ }
357
+ $make_term_object_to_array = wp_list_pluck( $terms, 'term_taxonomy_id' );
358
+ // If empty then return.
359
+ if ( empty( $make_term_object_to_array ) ) {
360
+ return '(1 = 0)';
361
+ }
362
+ $tt_ids = join( ',', $make_term_object_to_array );
363
+ return 'count(distinct if( terms.term_taxonomy_id in (' . $tt_ids . '), terms.term_taxonomy_id, null ))';
364
+ }
365
+ /*
366
+ * KEYWORDS
367
+ */
368
+ /**
369
+ * @param int $ID
370
+ * @param string $type body | title | all
371
+ * @return string|array depending on whether "all" were requested or not
372
+ */
373
+ public function get_keywords( $ID, $type = 'all' ) {
374
+ if ( ! $ID = absint( $ID ) ) {
375
+ return false;
376
+ }
377
+ $keywords = array(
378
+ 'body' => $this->body_keywords( $ID ),
379
+ 'title' => $this->title_keywords( $ID ),
380
+ );
381
+ if ( empty( $keywords ) ) {
382
+ return false;
383
+ }
384
+
385
+ if ( $type === 'all' ) {
386
+ return $keywords;
387
+ }
388
+ return $keywords[ $type ];
389
+ }
390
+
391
+ protected function title_keywords( $ID, $max = 20 ) {
392
+ return apply_filters( 'yarpp_title_keywords', $this->extract_keywords( get_the_title( $ID ), $max, $ID ), $max, $ID );
393
+ }
394
+ protected function body_keywords( $ID, $max = 20 ) {
395
+ $post = get_post( $ID );
396
+ if ( empty( $post ) ) {
397
+ return '';
398
+ }
399
+ $this->discovering_keywords = true;
400
+ $body_content = apply_filters( 'the_content', $post->post_content );
401
+ $this->discovering_keywords = false;
402
+ $keywords = apply_filters( 'yarpp_body_keywords', $this->extract_keywords( $body_content, $max, $ID ), $max, $ID );
403
+
404
+ return $keywords;
405
+ }
406
+
407
+ private function extract_keywords( $html, $max = 20, $ID = 0 ) {
408
+
409
+ /**
410
+ * @filter yarpp_extract_keywords
411
+ *
412
+ * Use this filter to override YARPP's built-in keyword computation
413
+ * Return values should be a string of space-delimited words
414
+ *
415
+ * @param $keywords
416
+ * @param $html unfiltered HTML content
417
+ * @param (int) $max maximum number of keywords
418
+ * @param (int) $ID
419
+ */
420
+ if ( $keywords = apply_filters( 'yarpp_extract_keywords', false, $html, $max, $ID ) ) {
421
+ return $keywords;
422
+ }
423
+ if ( defined( 'WPLANG' ) ) {
424
+ switch ( substr( WPLANG, 0, 2 ) ) {
425
+ case 'de':
426
+ $lang = 'de_DE';
427
+ break;
428
+ case 'it':
429
+ $lang = 'it_IT';
430
+ break;
431
+ case 'pl':
432
+ $lang = 'pl_PL';
433
+ break;
434
+ case 'bg':
435
+ $lang = 'bg_BG';
436
+ break;
437
+ case 'fr':
438
+ $lang = 'fr_FR';
439
+ break;
440
+ case 'cs':
441
+ $lang = 'cs_CZ';
442
+ break;
443
+ case 'nl':
444
+ $lang = 'nl_NL';
445
+ break;
446
+ default:
447
+ $lang = 'en_US';
448
+ break;
449
+ }
450
+ } else {
451
+ $lang = 'en_US';
452
+ }
453
+
454
+ $words_file = YARPP_DIR . '/lang/words-' . $lang . '.php';
455
+ if ( file_exists( $words_file ) ) {
456
+ include $words_file;
457
+ }
458
+ if ( ! isset( $overusedwords ) ) {
459
+ $overusedwords = array();
460
+ }
461
+
462
+ // strip tags and html entities
463
+ $text = preg_replace( '/&(#x[0-9a-f]+|#[0-9]+|[a-zA-Z]+);/', '', strip_tags( $html ) );
464
+
465
+ // 3.2.2: ignore soft hyphens
466
+ // Requires PHP 5: http://bugs.php.net/bug.php?id=25670
467
+ $softhyphen = html_entity_decode( '&#173;', ENT_NOQUOTES, 'UTF-8' );
468
+ $text = str_replace( $softhyphen, '', $text );
469
+
470
+ $charset = get_option( 'blog_charset' );
471
+ if ( function_exists( 'mb_split' ) && ! empty( $charset ) ) {
472
+ mb_regex_encoding( $charset );
473
+ $wordlist = mb_split( '\s*\W+\s*', mb_strtolower( $text, $charset ) );
474
+ } else {
475
+ $wordlist = preg_split( '%\s*\W+\s*%', strtolower( $text ) );
476
+ }
477
+
478
+ // Build an array of the unique words and number of times they occur.
479
+ $tokens = array_count_values( $wordlist );
480
+
481
+ // Remove the stop words from the list.
482
+ $overusedwords = apply_filters( 'yarpp_keywords_overused_words', $overusedwords );
483
+ if ( is_array( $overusedwords ) ) {
484
+ foreach ( $overusedwords as $word ) {
485
+ unset( $tokens[ $word ] );
486
+ }
487
+ }
488
+ // Remove words which are only a letter
489
+ foreach ( array_keys( $tokens ) as $word ) {
490
+ if ( function_exists( 'mb_strlen' ) ) {
491
+ if ( mb_strlen( $word ) < 2 ) {
492
+ unset( $tokens[ $word ] );
493
+ } elseif ( strlen( $word ) < 2 ) {
494
+ unset( $tokens[ $word ] );
495
+ }
496
+ }
497
+ }
498
+
499
+ arsort( $tokens, SORT_NUMERIC );
500
+
501
+ $types = array_keys( $tokens );
502
+
503
+ if ( count( $types ) > $max ) {
504
+ $types = array_slice( $types, 0, $max );
505
+ }
506
+ return implode( ' ', $types );
507
+ }
508
+
509
+ /**
510
+ * Does a database query without emitting any warnings if there's an SQL error. (Although they will still show up
511
+ * in the Query Monitor plugin, which is a feature.)
512
+ * Throws an exception if there is an error.
513
+ *
514
+ * @param string $wpdb_method method on WPDB to call
515
+ * @param array $args array of arguments to pass it.
516
+ *
517
+ * @return mixed|WP_Error
518
+ */
519
+ protected function query_safely( $wpdb_method, $args ) {
520
+ global $wpdb;
521
+ $value = call_user_func_array(
522
+ array( $wpdb, $wpdb_method ),
523
+ $args
524
+ );
525
+ if ( $wpdb->last_error ) {
526
+ return new WP_Error( 'yarpp_bad_db', $wpdb->last_error );
527
+ }
528
+
529
+ return $value;
530
+ }
531
+
532
+ /**
533
+ * Returns whether or not we're currently discovering the keywords on a reference post.
534
+ * (This is a very bad time to start looking for related posts! So YARPP core should be able to detect this.)
535
+ *
536
+ * @return bool
537
+ */
538
+ public function discovering_keywords() {
539
+ return $this->discovering_keywords;
540
+ }
541
+
542
+ /**
543
+ * Replaces the WP_Query's orderby clause (which normally orders by date) to orderby score instead
544
+ *
545
+ * @param string $sql
546
+ * @return string
547
+ */
548
+ protected function orderby_score( $sql ) {
549
+ global $wpdb;
550
+ return str_replace(
551
+ array(
552
+ "$wpdb->posts.post_date ASC",
553
+ "$wpdb->posts.post_date DESC",
554
+ ),
555
+ array(
556
+ "score ASC, {$wpdb->posts}.ID ASC",
557
+ "score DESC, {$wpdb->posts}.ID ASC",
558
+ ),
559
+ $sql
560
+ );
561
+ }
562
+
563
+ /**
564
+ * Updates the cache.
565
+ *
566
+ * @param int $reference_ID post ID to which we're finding related posts
567
+ * @param array $args @see YARPP::display_related()
568
+ * @return string (YARPP_NO_RELATED | YARPP_RELATED | YARPP_DONT_RUN)
569
+ */
570
+ protected function update( $reference_ID, $args = array() ) {
571
+ return YARPP_RELATED;
572
+ }
573
+ }
classes/YARPP_Cache_Bypass.php CHANGED
@@ -2,101 +2,104 @@
2
 
3
  class YARPP_Cache_Bypass extends YARPP_Cache {
4
 
5
- public $name = "bypass";
6
- public $demo_time = false;
7
-
8
- private $related_postdata = array();
9
- private $related_IDs = array();
10
- private $demo_limit = 0;
11
-
12
- /**
13
- * SETUP/STATUS
14
- */
15
- function __construct(&$core) {
16
- parent::__construct($core);
17
- }
18
-
19
- public function is_enabled() {
20
- return true; // always enabled.
21
- }
22
-
23
- public function cache_status() {
24
- return 0; // always uncached
25
- }
26
-
27
- public function stats() {
28
- return array(); // always unknown
29
- }
30
-
31
- public function uncached($limit = 20, $offset = 0) {
32
- return array(); // nothing to cache
33
- }
34
-
35
- /**
36
- * MAGIC FILTERS
37
- */
38
- public function where_filter($arg) {
39
- global $wpdb;
40
-
41
- // modify the where clause to use the related ID list.
42
- if (!count($this->related_IDs)) $this->related_IDs = array(0);
43
-
44
- $arg = preg_replace("!{$wpdb->posts}.ID = \d+!","{$wpdb->posts}.ID in (".join(',',$this->related_IDs).")",$arg);
45
-
46
- // if we have recent set, add an additional condition
47
- if ((bool) $this->args['recent']) $arg .= " and post_date > date_sub(now(), interval {$this->args['recent']}) ";
48
-
49
- return $arg;
50
- }
51
-
52
- public function orderby_filter($arg) {
53
- /*
54
- * Only order by score if the score function is added in fields_filter,
55
- * which only happens if there are related posts in the post-data.
56
- * If ordering by score also order by post ID to keep them consistent in cases where the score is the same
57
- * for multiple posts.
58
- */
59
- if ($this->score_override && is_array($this->related_postdata) && count($this->related_postdata)) {
60
- $arg = $this->orderby_score($arg);
61
- }
62
-
63
- return $arg;
64
- }
65
-
66
- public function fields_filter($arg) {
67
- global $wpdb;
68
-
69
- if (is_array($this->related_postdata) && count($this->related_postdata)) {
70
- $scores = array();
71
- foreach ($this->related_postdata as $related_entry) {
72
- $scores[] = " WHEN {$related_entry['ID']} THEN {$related_entry['score']}";
73
- }
74
- $arg .= ", CASE {$wpdb->posts}.ID" . join('',$scores) ." END as score";
75
- }
76
- return $arg;
77
- }
78
-
79
- public function demo_request_filter($arg) {
80
- global $wpdb;
81
-
82
- $wpdb->query("set @count = 0;");
83
-
84
- $loremipsum =
85
- 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras tincidunt justo a urna. Ut turpis. Phasellus'.
86
- 'convallis, odio sit amet cursus convallis, eros orci scelerisque velit, ut sodales neque nisl at ante. '.
87
- 'Suspendisse metus. Curabitur auctor pede quis mi. Pellentesque lorem justo, condimentum ac, dapibus sit '.
88
- 'amet, ornare et, erat. Quisque velit. Etiam sodales dui feugiat neque suscipit bibendum. Integer mattis. '.
89
- 'Nullam et ante non sem commodo malesuada. Pellentesque ultrices fermentum lectus. Maecenas hendrerit neque ac '.
90
- 'est. Fusce tortor mi, tristique sed, cursus at, pellentesque non, dui. Suspendisse potenti.';
91
-
92
- return
93
- "SELECT
 
 
 
94
  SQL_CALC_FOUND_ROWS ID + {$this->demo_limit} as ID,
95
  post_author,
96
  post_date,
97
  post_date_gmt,
98
  '{$loremipsum}' as post_content,
99
- concat('".__('Example post ','yarpp')."', @count:=@count+1) as post_title,
100
  0 as post_category,
101
  '' as post_excerpt,
102
  'publish' as post_status,
@@ -118,100 +121,101 @@ class YARPP_Cache_Bypass extends YARPP_Cache {
118
  'SCORE' as score
119
  FROM $wpdb->posts
120
  ORDER BY ID DESC LIMIT 0, {$this->demo_limit}";
121
- }
122
-
123
- public function limit_filter($arg) {
124
- global $wpdb;
125
- return ($this->online_limit) ? " limit {$this->online_limit} " : $arg;
126
- }
127
-
128
- /**
129
- * RELATEDNESS CACHE CONTROL
130
- */
131
- public function begin_yarpp_time($reference_ID, $args) {
132
- global $wpdb;
133
-
134
- $this->yarpp_time = true;
135
- $options = array(
136
- 'threshold',
137
- 'show_pass_post',
138
- 'past_only',
139
- 'weight',
140
- 'require_tax',
141
- 'exclude',
142
- 'recent',
143
- 'limit'
144
- );
145
- $this->args = $this->core->parse_args($args, $options);
146
-
147
- $this->related_postdata = $wpdb->get_results($this->sql($reference_ID, $args), ARRAY_A);
148
- $this->related_IDs = wp_list_pluck($this->related_postdata, 'ID');
149
-
150
- add_filter('posts_where',array(&$this,'where_filter'));
151
- add_filter('posts_orderby',array(&$this,'orderby_filter'));
152
- add_filter('posts_fields',array(&$this,'fields_filter'));
153
- add_filter('post_limits',array(&$this,'limit_filter'));
154
-
155
- add_action('pre_get_posts',array(&$this,'add_signature'));
156
- add_action('parse_query',array(&$this,'set_score_override_flag')); // sets the score override flag.
157
- }
158
-
159
- public function begin_demo_time($limit) {
160
- $this->demo_time = true;
161
- $this->demo_limit = $limit;
162
-
163
- add_action('pre_get_posts',array(&$this,'add_signature'));
164
- add_filter('posts_request',array(&$this,'demo_request_filter'));
165
- }
166
-
167
- public function end_yarpp_time() {
168
- $this->yarpp_time = false;
169
-
170
- remove_filter('posts_where',array(&$this,'where_filter'));
171
- remove_filter('posts_orderby',array(&$this,'orderby_filter'));
172
- remove_filter('posts_fields',array(&$this,'fields_filter'));
173
- remove_filter('post_limits',array(&$this,'limit_filter'));
174
-
175
- remove_action('pre_get_posts',array(&$this,'add_signature'));
176
- remove_action('parse_query',array(&$this,'set_score_override_flag'));
177
- }
178
-
179
- public function end_demo_time() {
180
- $this->demo_time = false;
181
-
182
- remove_action('pre_get_posts',array(&$this,'add_signature'));
183
- remove_filter('posts_request',array(&$this,'demo_request_filter'));
184
- }
185
-
186
- public function related($reference_ID = null, $related_ID = null) {
187
- global $wpdb;
188
-
189
- if ( !is_int( $reference_ID ) && !is_int( $related_ID ) ) {
190
- _doing_it_wrong( __METHOD__, 'reference ID and/or related ID must be set', '3.4' );
191
- return;
192
- }
193
-
194
- // reverse lookup
195
- if ( is_int($related_ID) && is_null($reference_ID) ) {
196
- _doing_it_wrong( __METHOD__, 'YARPP_Cache_Bypass::related cannot do a reverse lookup', '3.4' );
197
- return;
198
- }
199
-
200
- $results = $this->query_safely(
201
- 'get_results',
202
- array(
203
- $this->sql($reference_ID),
204
- ARRAY_A
205
- )
206
- );
207
- if ( !$results || !count($results) || $results instanceof WP_Error)
208
- return false;
209
-
210
- $results_ids = wp_list_pluck( $results, 'ID' );
211
- if ( is_null($related_ID) ) {
212
- return $results_ids;
213
- } else {
214
- return in_array( $related_ID, $results_ids );
215
- }
216
- }
217
- }
 
2
 
3
  class YARPP_Cache_Bypass extends YARPP_Cache {
4
 
5
+ public $name = 'bypass';
6
+ public $demo_time = false;
7
+
8
+ private $related_postdata = array();
9
+ private $related_IDs = array();
10
+ private $demo_limit = 0;
11
+
12
+ /**
13
+ * SETUP/STATUS
14
+ */
15
+ function __construct( &$core ) {
16
+ parent::__construct( $core );
17
+ }
18
+
19
+ public function is_enabled() {
20
+ return true; // always enabled.
21
+ }
22
+
23
+ public function cache_status() {
24
+ return 0; // always uncached.
25
+ }
26
+
27
+ public function stats() {
28
+ return array(); // always unknown.
29
+ }
30
+
31
+ public function uncached( $limit = 20, $offset = 0 ) {
32
+ return array(); // nothing to cache.
33
+ }
34
+
35
+ /**
36
+ * MAGIC FILTERS
37
+ */
38
+ public function where_filter( $arg ) {
39
+ global $wpdb;
40
+
41
+ // modify the where clause to use the related ID list.
42
+ if ( ! count( $this->related_IDs ) ) {
43
+ $this->related_IDs = array( 0 );
44
+ }
45
+
46
+ $arg = preg_replace( "!{$wpdb->posts}.ID = \d+!", "{$wpdb->posts}.ID in (" . join( ',', $this->related_IDs ) . ')', $arg );
47
+
48
+ // if we have recent set, add an additional condition
49
+ if ( (bool) $this->args['recent'] ) {
50
+ $arg .= " and post_date > date_sub(now(), interval {$this->args['recent']}) ";
51
+ }
52
+
53
+ return $arg;
54
+ }
55
+
56
+ public function orderby_filter( $arg ) {
57
+ /*
58
+ * Only order by score if the score function is added in fields_filter,
59
+ * which only happens if there are related posts in the post-data.
60
+ * If ordering by score also order by post ID to keep them consistent in cases where the score is the same
61
+ * for multiple posts.
62
+ */
63
+ if ( $this->score_override && is_array( $this->related_postdata ) && count( $this->related_postdata ) ) {
64
+ $arg = $this->orderby_score( $arg );
65
+ }
66
+
67
+ return $arg;
68
+ }
69
+
70
+ public function fields_filter( $arg ) {
71
+ global $wpdb;
72
+
73
+ if ( is_array( $this->related_postdata ) && count( $this->related_postdata ) ) {
74
+ $scores = array();
75
+ foreach ( $this->related_postdata as $related_entry ) {
76
+ $scores[] = " WHEN {$related_entry['ID']} THEN {$related_entry['score']}";
77
+ }
78
+ $arg .= ", CASE {$wpdb->posts}.ID" . join( '', $scores ) . ' END as score';
79
+ }
80
+ return $arg;
81
+ }
82
+
83
+ public function demo_request_filter( $arg ) {
84
+ global $wpdb;
85
+
86
+ $wpdb->query( 'set @count = 0;' );
87
+
88
+ $loremipsum =
89
+ 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras tincidunt justo a urna. Ut turpis. Phasellus' .
90
+ 'convallis, odio sit amet cursus convallis, eros orci scelerisque velit, ut sodales neque nisl at ante. ' .
91
+ 'Suspendisse metus. Curabitur auctor pede quis mi. Pellentesque lorem justo, condimentum ac, dapibus sit ' .
92
+ 'amet, ornare et, erat. Quisque velit. Etiam sodales dui feugiat neque suscipit bibendum. Integer mattis. ' .
93
+ 'Nullam et ante non sem commodo malesuada. Pellentesque ultrices fermentum lectus. Maecenas hendrerit neque ac ' .
94
+ 'est. Fusce tortor mi, tristique sed, cursus at, pellentesque non, dui. Suspendisse potenti.';
95
+
96
+ return "SELECT
97
  SQL_CALC_FOUND_ROWS ID + {$this->demo_limit} as ID,
98
  post_author,
99
  post_date,
100
  post_date_gmt,
101
  '{$loremipsum}' as post_content,
102
+ concat('" . __( 'Example post ', 'yarpp' ) . "', @count:=@count+1) as post_title,
103
  0 as post_category,
104
  '' as post_excerpt,
105
  'publish' as post_status,
121
  'SCORE' as score
122
  FROM $wpdb->posts
123
  ORDER BY ID DESC LIMIT 0, {$this->demo_limit}";
124
+ }
125
+
126
+ public function limit_filter( $arg ) {
127
+ global $wpdb;
128
+ return ( $this->online_limit ) ? " limit {$this->online_limit} " : $arg;
129
+ }
130
+
131
+ /**
132
+ * RELATEDNESS CACHE CONTROL
133
+ */
134
+ public function begin_yarpp_time( $reference_ID, $args ) {
135
+ global $wpdb;
136
+
137
+ $this->yarpp_time = true;
138
+ $options = array(
139
+ 'threshold',
140
+ 'show_pass_post',
141
+ 'past_only',
142
+ 'weight',
143
+ 'require_tax',
144
+ 'exclude',
145
+ 'recent',
146
+ 'limit',
147
+ );
148
+ $this->args = $this->core->parse_args( $args, $options );
149
+
150
+ $this->related_postdata = $wpdb->get_results( $this->sql( $reference_ID, $args ), ARRAY_A );
151
+ $this->related_IDs = wp_list_pluck( $this->related_postdata, 'ID' );
152
+
153
+ add_filter( 'posts_where', array( &$this, 'where_filter' ) );
154
+ add_filter( 'posts_orderby', array( &$this, 'orderby_filter' ) );
155
+ add_filter( 'posts_fields', array( &$this, 'fields_filter' ) );
156
+ add_filter( 'post_limits', array( &$this, 'limit_filter' ) );
157
+
158
+ add_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
159
+ add_action( 'parse_query', array( &$this, 'set_score_override_flag' ) ); // sets the score override flag.
160
+ }
161
+
162
+ public function begin_demo_time( $limit ) {
163
+ $this->demo_time = true;
164
+ $this->demo_limit = $limit;
165
+
166
+ add_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
167
+ add_filter( 'posts_request', array( &$this, 'demo_request_filter' ) );
168
+ }
169
+
170
+ public function end_yarpp_time() {
171
+ $this->yarpp_time = false;
172
+
173
+ remove_filter( 'posts_where', array( &$this, 'where_filter' ) );
174
+ remove_filter( 'posts_orderby', array( &$this, 'orderby_filter' ) );
175
+ remove_filter( 'posts_fields', array( &$this, 'fields_filter' ) );
176
+ remove_filter( 'post_limits', array( &$this, 'limit_filter' ) );
177
+
178
+ remove_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
179
+ remove_action( 'parse_query', array( &$this, 'set_score_override_flag' ) );
180
+ }
181
+
182
+ public function end_demo_time() {
183
+ $this->demo_time = false;
184
+
185
+ remove_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
186
+ remove_filter( 'posts_request', array( &$this, 'demo_request_filter' ) );
187
+ }
188
+
189
+ public function related( $reference_ID = null, $related_ID = null ) {
190
+ global $wpdb;
191
+
192
+ if ( ! is_int( $reference_ID ) && ! is_int( $related_ID ) ) {
193
+ _doing_it_wrong( __METHOD__, 'reference ID and/or related ID must be set', '3.4' );
194
+ return;
195
+ }
196
+
197
+ // reverse lookup
198
+ if ( is_int( $related_ID ) && is_null( $reference_ID ) ) {
199
+ _doing_it_wrong( __METHOD__, 'YARPP_Cache_Bypass::related cannot do a reverse lookup', '3.4' );
200
+ return;
201
+ }
202
+
203
+ $results = $this->query_safely(
204
+ 'get_results',
205
+ array(
206
+ $this->sql( $reference_ID ),
207
+ ARRAY_A,
208
+ )
209
+ );
210
+ if ( ! $results || ! count( $results ) || $results instanceof WP_Error ) {
211
+ return false;
212
+ }
213
+
214
+ $results_ids = wp_list_pluck( $results, 'ID' );
215
+ if ( is_null( $related_ID ) ) {
216
+ return $results_ids;
217
+ } else {
218
+ return in_array( $related_ID, $results_ids );
219
+ }
220
+ }
221
+ }
classes/YARPP_Cache_Postmeta.php CHANGED
@@ -2,11 +2,11 @@
2
 
3
  class YARPP_Cache_Postmeta extends YARPP_Cache {
4
 
5
- public $name = "postmeta";
6
 
7
  // variables used for lookup
8
  private $related_postdata = array();
9
- private $related_IDs = array();
10
 
11
  /**
12
  * SETUP/STATUS
@@ -21,25 +21,27 @@ class YARPP_Cache_Postmeta extends YARPP_Cache {
21
 
22
  public function setup() {
23
  }
24
-
25
  public function upgrade( $last_version ) {
26
- if ( $last_version && version_compare('3.4b1', $last_version) > 0 ) {
27
  // 3.4 moved _yarpp_body_keywords and _yarpp_title_keywords into the single
28
  // postmeta _yarpp_keywords, so clear out the old data now.
29
- delete_post_meta_by_key('_yarpp_title_keywords');
30
- delete_post_meta_by_key('_yarpp_body_keywords');
31
- }
32
  }
33
 
34
  public function cache_status() {
35
  global $wpdb;
36
- return $wpdb->get_var("select (count(p.ID)-sum(m.meta_value IS NULL))/count(p.ID)
 
37
  FROM `{$wpdb->posts}` as p
38
  LEFT JOIN `{$wpdb->postmeta}` as m ON (p.ID = m.post_id and m.meta_key = '" . YARPP_POSTMETA_RELATED_KEY . "')
39
- WHERE p.post_status = 'publish'");
 
40
  }
41
 
42
- public function uncached($limit = 20, $offset = 0) {
43
  global $wpdb;
44
 
45
  return $wpdb->get_col(
@@ -57,105 +59,114 @@ class YARPP_Cache_Postmeta extends YARPP_Cache {
57
 
58
  public function stats() {
59
  global $wpdb;
60
- return wp_list_pluck($wpdb->get_results("select num, count(*) as ct from (select 0 + if(meta_value = '" . YARPP_NO_RELATED . "', 0, substring(substring_index(meta_value,':',2),3)) as num from `{$wpdb->postmeta}` where meta_key = '" . YARPP_POSTMETA_RELATED_KEY . "') as t group by num order by num asc", OBJECT_K), 'ct');
61
  }
62
 
63
  /**
64
  * MAGIC FILTERS
65
  */
66
- public function where_filter($arg) {
67
  global $wpdb;
68
  // modify the where clause to use the related ID list.
69
- if (!count($this->related_IDs))
70
- $this->related_IDs = array(0);
71
- $arg = preg_replace("!{$wpdb->posts}.ID = \d+!","{$wpdb->posts}.ID in (".join(',',$this->related_IDs).")",$arg);
 
72
 
73
  // if recent is set, add an additional condition
74
- $recent = $this->core->get_option('recent');
75
- if ((bool) $recent) $arg .= " and post_date > date_sub(now(), interval {$recent}) ";
 
 
76
  return $arg;
77
  }
78
 
79
- public function orderby_filter($arg) {
80
  /*
81
- * Only order by score if the score function is added in fields_filter,
82
- * which only happens if there are related posts in the post-data.
83
- * If ordering by score also order by post ID to keep them consistent in cases where the score is the same
84
- * for multiple posts.
85
- */
86
- if ($this->score_override &&
87
- is_array($this->related_postdata) && count($this->related_postdata))
88
- $arg = $this->orderby_score($arg);
 
89
  return $arg;
90
  }
91
 
92
- public function fields_filter($arg) {
93
  global $wpdb;
94
- if (is_array($this->related_postdata) && count($this->related_postdata)) {
95
  $scores = array();
96
- foreach ($this->related_postdata as $related_entry) {
97
  $scores[] = " WHEN {$related_entry['ID']} THEN {$related_entry['score']}";
98
  }
99
- $arg .= ", CASE {$wpdb->posts}.ID" . join('',$scores) ." END as score";
100
  }
101
  return $arg;
102
  }
103
 
104
- public function limit_filter($arg) {
105
- if ($this->online_limit)
106
  return " limit {$this->online_limit} ";
 
107
  return $arg;
108
  }
109
 
110
  /**
111
  * RELATEDNESS CACHE CONTROL
112
  */
113
- public function begin_yarpp_time($reference_ID) {
114
  $this->yarpp_time = true;
115
  // get the related posts from postmeta, and also construct the relate_IDs array
116
- $this->related_postdata = get_post_meta($reference_ID,YARPP_POSTMETA_RELATED_KEY,true);
117
- if (is_array($this->related_postdata) && count($this->related_postdata))
118
  $this->related_IDs = wp_list_pluck( $this->related_postdata, 'ID' );
119
- add_filter('posts_where',array(&$this,'where_filter'));
120
- add_filter('posts_orderby',array(&$this,'orderby_filter'));
121
- add_filter('posts_fields',array(&$this,'fields_filter'));
122
- add_filter('post_limits',array(&$this,'limit_filter'));
123
- add_action('pre_get_posts',array(&$this,'add_signature'));
 
124
  // sets the score override flag.
125
- add_action('parse_query',array(&$this,'set_score_override_flag'));
126
  }
127
 
128
  public function end_yarpp_time() {
129
- $this->yarpp_time = false;
130
- $this->related_IDs = array();
131
  $this->related_postdata = array();
132
- remove_filter('posts_where',array(&$this,'where_filter'));
133
- remove_filter('posts_orderby',array(&$this,'orderby_filter'));
134
- remove_filter('posts_fields',array(&$this,'fields_filter'));
135
- remove_filter('post_limits',array(&$this,'limit_filter'));
136
- remove_action('pre_get_posts',array(&$this,'add_signature'));
137
  // sets the score override flag.
138
- remove_action('parse_query',array(&$this,'set_score_override_flag'));
139
  }
140
 
141
  // @return YARPP_NO_RELATED | YARPP_RELATED | YARPP_NOT_CACHED
142
- public function is_cached($reference_ID) {
143
- $related = get_post_meta($reference_ID, YARPP_POSTMETA_RELATED_KEY, true);
144
- if ( YARPP_NO_RELATED === $related )
145
- return YARPP_NO_RELATED;
146
- if ( '' == $related )
 
147
  return YARPP_NOT_CACHED;
 
148
  return YARPP_RELATED;
149
  }
150
 
151
  public function clear( $reference_IDs ) {
152
  $reference_IDs = wp_parse_id_list( $reference_IDs );
153
-
154
- if ( !count($reference_IDs) )
155
  return;
156
-
 
157
  // clear each cache
158
- foreach( $reference_IDs as $id ) {
159
  delete_post_meta( $id, YARPP_POSTMETA_RELATED_KEY );
160
  delete_post_meta( $id, YARPP_POSTMETA_KEYWORDS_KEY );
161
  }
@@ -163,42 +174,46 @@ class YARPP_Cache_Postmeta extends YARPP_Cache {
163
 
164
  /**
165
  * Caches the related posts in postmeta.
166
- * @param int $reference_ID post ID to which we want to find related content
 
167
  * @param array $args see YARPP::display_related()
168
  *
169
  * @return string (YARPP_NO_RELATED | YARPP_RELATED)
170
  */
171
- protected function update($reference_ID, $args = array()) {
172
- $original_related = $this->related($reference_ID);
173
- $related = $this->query_safely(
174
  'get_results',
175
  array(
176
- $this->sql($reference_ID, $args),
177
- ARRAY_A
178
  )
179
  );
180
- if($related instanceof WP_Error){
181
  return YARPP_DONT_RUN;
182
  }
183
  $new_related = wp_list_pluck( $related, 'ID' );
184
 
185
- if ( count($new_related) ) {
186
- update_post_meta($reference_ID, YARPP_POSTMETA_RELATED_KEY, $related);
187
- if ($this->core->debug) echo "<!--YARPP just set the cache for post $reference_ID-->";
 
 
188
 
189
  // Clear the caches of any items which are no longer related or are newly related.
190
- if (count($original_related)) {
191
- $this->clear(array_diff($original_related, $new_related));
192
- $this->clear(array_diff($new_related, $original_related));
193
  }
194
 
195
  return YARPP_RELATED;
196
  } else {
197
- update_post_meta($reference_ID, YARPP_POSTMETA_RELATED_KEY, YARPP_NO_RELATED);
198
 
199
  // Clear the caches of those which are no longer related.
200
- if (count($original_related))
201
- $this->clear($original_related);
 
202
 
203
  return YARPP_NO_RELATED;
204
  }
@@ -209,33 +224,35 @@ class YARPP_Cache_Postmeta extends YARPP_Cache {
209
  delete_post_meta_by_key( YARPP_POSTMETA_KEYWORDS_KEY );
210
  }
211
 
212
- public function related($reference_ID = null, $related_ID = null) {
213
  global $wpdb;
214
 
215
- if ( !is_int( $reference_ID ) && !is_int( $related_ID ) ) {
216
  _doing_it_wrong( __METHOD__, 'reference ID and/or related ID must be set', '3.4' );
217
  return;
218
  }
219
 
220
- if (!is_null($reference_ID) && !is_null($related_ID)) {
221
- $results = get_post_meta($reference_ID,YARPP_POSTMETA_RELATED_KEY,true);
222
- foreach($results as $result) {
223
- if ($result['ID'] == $related_ID)
224
  return true;
 
225
  }
226
  return false;
227
  }
228
 
229
  // return a list of ID's of "related" entries
230
- if (!is_null($reference_ID)) {
231
- $results = get_post_meta($reference_ID,YARPP_POSTMETA_RELATED_KEY,true);
232
- if (!$results || $results == YARPP_NO_RELATED)
233
  return array();
 
234
  return wp_list_pluck( $results, 'ID' );
235
  }
236
 
237
  // return a list of entities which list this post as "related"
238
- if (!is_null($related_ID)) {
239
  return $wpdb->get_col(
240
  $wpdb->prepare(
241
  "select post_id from `{$wpdb->postmeta}` where meta_key = '" . YARPP_POSTMETA_RELATED_KEY . "' and meta_value regexp 's:2:\"ID\";s:\d+:\"%d\"'",
@@ -250,14 +267,14 @@ class YARPP_Cache_Postmeta extends YARPP_Cache {
250
  /**
251
  * KEYWORDS CACHE CONTROL
252
  */
253
-
254
  // @return (array) with body and title keywords
255
- private function cache_keywords($ID) {
256
  $keywords = array(
257
- 'body' => $this->body_keywords($ID),
258
- 'title' => $this->title_keywords($ID)
259
  );
260
- update_post_meta($ID, YARPP_POSTMETA_KEYWORDS_KEY, $keywords);
261
  return $keywords;
262
  }
263
 
@@ -265,19 +282,23 @@ class YARPP_Cache_Postmeta extends YARPP_Cache {
265
  // @param $type (string) body | title | all
266
  // @return (string|array) depending on whether "all" were requested or not
267
  public function get_keywords( $ID, $type = 'all' ) {
268
- if ( !$ID = absint($ID) )
269
  return false;
270
-
271
- $keywords = get_post_meta($ID, YARPP_POSTMETA_KEYWORDS_KEY, true);
 
272
 
273
- if ( empty($keywords) ) // if empty, try caching them first.
274
- $keywords = $this->cache_keywords($ID);
 
275
 
276
- if ( empty($keywords) )
277
  return false;
278
-
279
- if ( 'all' == $type )
 
280
  return $keywords;
281
- return $keywords[$type];
 
282
  }
283
- }
2
 
3
  class YARPP_Cache_Postmeta extends YARPP_Cache {
4
 
5
+ public $name = 'postmeta';
6
 
7
  // variables used for lookup
8
  private $related_postdata = array();
9
+ private $related_IDs = array();
10
 
11
  /**
12
  * SETUP/STATUS
21
 
22
  public function setup() {
23
  }
24
+
25
  public function upgrade( $last_version ) {
26
+ if ( $last_version && version_compare( '3.4b1', $last_version ) > 0 ) {
27
  // 3.4 moved _yarpp_body_keywords and _yarpp_title_keywords into the single
28
  // postmeta _yarpp_keywords, so clear out the old data now.
29
+ delete_post_meta_by_key( '_yarpp_title_keywords' );
30
+ delete_post_meta_by_key( '_yarpp_body_keywords' );
31
+ }
32
  }
33
 
34
  public function cache_status() {
35
  global $wpdb;
36
+ return $wpdb->get_var(
37
+ "select (count(p.ID)-sum(m.meta_value IS NULL))/count(p.ID)
38
  FROM `{$wpdb->posts}` as p
39
  LEFT JOIN `{$wpdb->postmeta}` as m ON (p.ID = m.post_id and m.meta_key = '" . YARPP_POSTMETA_RELATED_KEY . "')
40
+ WHERE p.post_status = 'publish'"
41
+ );
42
  }
43
 
44
+ public function uncached( $limit = 20, $offset = 0 ) {
45
  global $wpdb;
46
 
47
  return $wpdb->get_col(
59
 
60
  public function stats() {
61
  global $wpdb;
62
+ return wp_list_pluck( $wpdb->get_results( "select num, count(*) as ct from (select 0 + if(meta_value = '" . YARPP_NO_RELATED . "', 0, substring(substring_index(meta_value,':',2),3)) as num from `{$wpdb->postmeta}` where meta_key = '" . YARPP_POSTMETA_RELATED_KEY . "') as t group by num order by num asc", OBJECT_K ), 'ct' );
63
  }
64
 
65
  /**
66
  * MAGIC FILTERS
67
  */
68
+ public function where_filter( $arg ) {
69
  global $wpdb;
70
  // modify the where clause to use the related ID list.
71
+ if ( ! count( $this->related_IDs ) ) {
72
+ $this->related_IDs = array( 0 );
73
+ }
74
+ $arg = preg_replace( "!{$wpdb->posts}.ID = \d+!", "{$wpdb->posts}.ID in (" . join( ',', $this->related_IDs ) . ')', $arg );
75
 
76
  // if recent is set, add an additional condition
77
+ $recent = $this->core->get_option( 'recent' );
78
+ if ( (bool) $recent ) {
79
+ $arg .= " and post_date > date_sub(now(), interval {$recent}) ";
80
+ }
81
  return $arg;
82
  }
83
 
84
+ public function orderby_filter( $arg ) {
85
  /*
86
+ * Only order by score if the score function is added in fields_filter,
87
+ * which only happens if there are related posts in the post-data.
88
+ * If ordering by score also order by post ID to keep them consistent in cases where the score is the same
89
+ * for multiple posts.
90
+ */
91
+ if ( $this->score_override &&
92
+ is_array( $this->related_postdata ) && count( $this->related_postdata ) ) {
93
+ $arg = $this->orderby_score( $arg );
94
+ }
95
  return $arg;
96
  }
97
 
98
+ public function fields_filter( $arg ) {
99
  global $wpdb;
100
+ if ( is_array( $this->related_postdata ) && count( $this->related_postdata ) ) {
101
  $scores = array();
102
+ foreach ( $this->related_postdata as $related_entry ) {
103
  $scores[] = " WHEN {$related_entry['ID']} THEN {$related_entry['score']}";
104
  }
105
+ $arg .= ", CASE {$wpdb->posts}.ID" . join( '', $scores ) . ' END as score';
106
  }
107
  return $arg;
108
  }
109
 
110
+ public function limit_filter( $arg ) {
111
+ if ( $this->online_limit ) {
112
  return " limit {$this->online_limit} ";
113
+ }
114
  return $arg;
115
  }
116
 
117
  /**
118
  * RELATEDNESS CACHE CONTROL
119
  */
120
+ public function begin_yarpp_time( $reference_ID ) {
121
  $this->yarpp_time = true;
122
  // get the related posts from postmeta, and also construct the relate_IDs array
123
+ $this->related_postdata = get_post_meta( $reference_ID, YARPP_POSTMETA_RELATED_KEY, true );
124
+ if ( is_array( $this->related_postdata ) && count( $this->related_postdata ) ) {
125
  $this->related_IDs = wp_list_pluck( $this->related_postdata, 'ID' );
126
+ }
127
+ add_filter( 'posts_where', array( &$this, 'where_filter' ) );
128
+ add_filter( 'posts_orderby', array( &$this, 'orderby_filter' ) );
129
+ add_filter( 'posts_fields', array( &$this, 'fields_filter' ) );
130
+ add_filter( 'post_limits', array( &$this, 'limit_filter' ) );
131
+ add_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
132
  // sets the score override flag.
133
+ add_action( 'parse_query', array( &$this, 'set_score_override_flag' ) );
134
  }
135
 
136
  public function end_yarpp_time() {
137
+ $this->yarpp_time = false;
138
+ $this->related_IDs = array();
139
  $this->related_postdata = array();
140
+ remove_filter( 'posts_where', array( &$this, 'where_filter' ) );
141
+ remove_filter( 'posts_orderby', array( &$this, 'orderby_filter' ) );
142
+ remove_filter( 'posts_fields', array( &$this, 'fields_filter' ) );
143
+ remove_filter( 'post_limits', array( &$this, 'limit_filter' ) );
144
+ remove_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
145
  // sets the score override flag.
146
+ remove_action( 'parse_query', array( &$this, 'set_score_override_flag' ) );
147
  }
148
 
149
  // @return YARPP_NO_RELATED | YARPP_RELATED | YARPP_NOT_CACHED
150
+ public function is_cached( $reference_ID ) {
151
+ $related = get_post_meta( $reference_ID, YARPP_POSTMETA_RELATED_KEY, true );
152
+ if ( YARPP_NO_RELATED === $related ) {
153
+ return YARPP_NO_RELATED;
154
+ }
155
+ if ( '' == $related ) {
156
  return YARPP_NOT_CACHED;
157
+ }
158
  return YARPP_RELATED;
159
  }
160
 
161
  public function clear( $reference_IDs ) {
162
  $reference_IDs = wp_parse_id_list( $reference_IDs );
163
+
164
+ if ( ! count( $reference_IDs ) ) {
165
  return;
166
+ }
167
+
168
  // clear each cache
169
+ foreach ( $reference_IDs as $id ) {
170
  delete_post_meta( $id, YARPP_POSTMETA_RELATED_KEY );
171
  delete_post_meta( $id, YARPP_POSTMETA_KEYWORDS_KEY );
172
  }
174
 
175
  /**
176
  * Caches the related posts in postmeta.
177
+ *
178
+ * @param int $reference_ID post ID to which we want to find related content
179
  * @param array $args see YARPP::display_related()
180
  *
181
  * @return string (YARPP_NO_RELATED | YARPP_RELATED)
182
  */
183
+ protected function update( $reference_ID, $args = array() ) {
184
+ $original_related = $this->related( $reference_ID );
185
+ $related = $this->query_safely(
186
  'get_results',
187
  array(
188
+ $this->sql( $reference_ID, $args ),
189
+ ARRAY_A,
190
  )
191
  );
192
+ if ( $related instanceof WP_Error ) {
193
  return YARPP_DONT_RUN;
194
  }
195
  $new_related = wp_list_pluck( $related, 'ID' );
196
 
197
+ if ( count( $new_related ) ) {
198
+ update_post_meta( $reference_ID, YARPP_POSTMETA_RELATED_KEY, $related );
199
+ if ( $this->core->debug ) {
200
+ echo "<!--YARPP just set the cache for post $reference_ID-->";
201
+ }
202
 
203
  // Clear the caches of any items which are no longer related or are newly related.
204
+ if ( count( $original_related ) ) {
205
+ $this->clear( array_diff( $original_related, $new_related ) );
206
+ $this->clear( array_diff( $new_related, $original_related ) );
207
  }
208
 
209
  return YARPP_RELATED;
210
  } else {
211
+ update_post_meta( $reference_ID, YARPP_POSTMETA_RELATED_KEY, YARPP_NO_RELATED );
212
 
213
  // Clear the caches of those which are no longer related.
214
+ if ( count( $original_related ) ) {
215
+ $this->clear( $original_related );
216
+ }
217
 
218
  return YARPP_NO_RELATED;
219
  }
224
  delete_post_meta_by_key( YARPP_POSTMETA_KEYWORDS_KEY );
225
  }
226
 
227
+ public function related( $reference_ID = null, $related_ID = null ) {
228
  global $wpdb;
229
 
230
+ if ( ! is_int( $reference_ID ) && ! is_int( $related_ID ) ) {
231
  _doing_it_wrong( __METHOD__, 'reference ID and/or related ID must be set', '3.4' );
232
  return;
233
  }
234
 
235
+ if ( ! is_null( $reference_ID ) && ! is_null( $related_ID ) ) {
236
+ $results = get_post_meta( $reference_ID, YARPP_POSTMETA_RELATED_KEY, true );
237
+ foreach ( $results as $result ) {
238
+ if ( $result['ID'] == $related_ID ) {
239
  return true;
240
+ }
241
  }
242
  return false;
243
  }
244
 
245
  // return a list of ID's of "related" entries
246
+ if ( ! is_null( $reference_ID ) ) {
247
+ $results = get_post_meta( $reference_ID, YARPP_POSTMETA_RELATED_KEY, true );
248
+ if ( ! $results || $results == YARPP_NO_RELATED ) {
249
  return array();
250
+ }
251
  return wp_list_pluck( $results, 'ID' );
252
  }
253
 
254
  // return a list of entities which list this post as "related"
255
+ if ( ! is_null( $related_ID ) ) {
256
  return $wpdb->get_col(
257
  $wpdb->prepare(
258
  "select post_id from `{$wpdb->postmeta}` where meta_key = '" . YARPP_POSTMETA_RELATED_KEY . "' and meta_value regexp 's:2:\"ID\";s:\d+:\"%d\"'",
267
  /**
268
  * KEYWORDS CACHE CONTROL
269
  */
270
+
271
  // @return (array) with body and title keywords
272
+ private function cache_keywords( $ID ) {
273
  $keywords = array(
274
+ 'body' => $this->body_keywords( $ID ),
275
+ 'title' => $this->title_keywords( $ID ),
276
  );
277
+ update_post_meta( $ID, YARPP_POSTMETA_KEYWORDS_KEY, $keywords );
278
  return $keywords;
279
  }
280
 
282
  // @param $type (string) body | title | all
283
  // @return (string|array) depending on whether "all" were requested or not
284
  public function get_keywords( $ID, $type = 'all' ) {
285
+ if ( ! $ID = absint( $ID ) ) {
286
  return false;
287
+ }
288
+
289
+ $keywords = get_post_meta( $ID, YARPP_POSTMETA_KEYWORDS_KEY, true );
290
 
291
+ if ( empty( $keywords ) ) { // if empty, try caching them first.
292
+ $keywords = $this->cache_keywords( $ID );
293
+ }
294
 
295
+ if ( empty( $keywords ) ) {
296
  return false;
297
+ }
298
+
299
+ if ( 'all' == $type ) {
300
  return $keywords;
301
+ }
302
+ return $keywords[ $type ];
303
  }
304
+ }
classes/YARPP_Cache_Tables.php CHANGED
@@ -1,7 +1,7 @@
1
  <?php
2
 
3
  class YARPP_Cache_Tables extends YARPP_Cache {
4
- public $name = "custom tables";
5
 
6
  /**
7
  * SETUP/STATUS
@@ -17,44 +17,49 @@ class YARPP_Cache_Tables extends YARPP_Cache {
17
  public function setup() {
18
  $this->core->db_schema->create_cache_table();
19
  }
20
-
21
- public function upgrade($last_version) {
22
  global $wpdb;
23
- if ( $last_version && version_compare('3.2.1b4', $last_version) > 0 ) {
24
  // Change primary key to be (reference_ID, ID) to ensure that we don't
25
  // get duplicates.
26
  // We unfortunately have to clear the cache first here, to ensure that there
27
  // are no duplicates.
28
  $this->flush();
29
- $wpdb->query('ALTER TABLE ' . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE .
30
- ' DROP PRIMARY KEY ,' .
31
- ' ADD PRIMARY KEY ( `reference_ID` , `ID` ),' .
32
- ' ADD INDEX (`score`), ADD INDEX (`ID`)');
 
 
33
  }
34
- if ( $last_version && version_compare('3.5.2b3', $last_version) > 0 ) {
35
  // flush object cache, as bad is_cached_* values were stored before
36
  wp_cache_flush();
37
  }
38
- if ( $last_version && version_compare('3.6b1', $last_version) > 0 ) {
39
  // remove keywords table
40
- if ( defined('YARPP_TABLES_KEYWORDS_TABLE') )
41
  $old_keywords_table = $wpdb->prefix . YARPP_TABLES_KEYWORDS_TABLE;
42
- else
43
  $old_keywords_table = $wpdb->prefix . 'yarpp_keyword_cache';
44
-
45
- $wpdb->query("drop table if exists `$old_keywords_table`");
 
46
  }
47
  }
48
 
49
  public function cache_status() {
50
  global $wpdb;
51
- return $wpdb->get_var("select (count(p.ID)-sum(c.ID IS NULL))/count(p.ID)
 
52
  FROM `{$wpdb->posts}` as p
53
  LEFT JOIN `{$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . "` as c ON (p.ID = c.reference_ID)
54
- WHERE p.post_status = 'publish' ");
 
55
  }
56
 
57
- public function uncached($limit = 20, $offset = 0) {
58
  global $wpdb;
59
  return $wpdb->get_col(
60
  $wpdb->prepare(
@@ -68,67 +73,74 @@ class YARPP_Cache_Tables extends YARPP_Cache {
68
  )
69
  );
70
  }
71
-
72
  public function stats() {
73
  global $wpdb;
74
- return wp_list_pluck($wpdb->get_results("select num, count(*) as ct from (select 0 + if(id = 0, 0, count(ID)) as num from {$wpdb->prefix}yarpp_related_cache group by reference_ID) as t group by num order by num asc", OBJECT_K), 'ct');
75
  }
76
-
77
  public function graph_data( $threshold = 5 ) {
78
  global $wpdb;
79
-
80
- $threshold = absint($threshold);
81
- $results = $wpdb->get_results("select pair, sum(score) as score from
 
82
  ((select concat(reference_ID, '-', ID) as pair, score from {$wpdb->prefix}yarpp_related_cache where reference_ID < ID)
83
  union
84
  (select concat(ID, '-', reference_ID) as pair, score from {$wpdb->prefix}yarpp_related_cache where ID < reference_ID)) as t
85
  group by pair
86
- having sum(score) > {$threshold}");
 
87
  return $results;
88
  }
89
 
90
  /**
91
  * MAGIC FILTERS
92
  */
93
- public function join_filter($arg) {
94
  global $wpdb;
95
- if ($this->yarpp_time)
96
  $arg .= " join {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " as yarpp on {$wpdb->posts}.ID = yarpp.ID";
 
97
  return $arg;
98
  }
99
 
100
- public function where_filter($arg) {
101
  global $wpdb;
102
- $threshold = $this->core->get_option('threshold');
103
- if ($this->yarpp_time) {
104
 
105
- $arg = str_replace("$wpdb->posts.ID = ","yarpp.score >= $threshold and yarpp.reference_ID = ",$arg);
106
 
107
- $recent = $this->core->get_option('recent');
108
- if ((bool) $recent) $arg .= " and post_date > date_sub(now(), interval {$recent}) ";
 
 
109
  }
110
  return $arg;
111
  }
112
 
113
- public function orderby_filter($arg) {
114
  global $wpdb;
115
  // If ordering by score also order by post ID to keep them consistent in cases where the score is the same
116
  // for multiple posts.
117
- if ($this->yarpp_time and $this->score_override)
118
- $arg = $this->orderby_score($arg);
 
119
  return $arg;
120
  }
121
 
122
- public function fields_filter($arg) {
123
  global $wpdb;
124
- if ($this->yarpp_time)
125
- $arg .= ", yarpp.score";
 
126
  return $arg;
127
  }
128
 
129
- public function limit_filter($arg) {
130
  global $wpdb;
131
- if ($this->yarpp_time and $this->online_limit) {
132
  return " limit {$this->online_limit} ";
133
  }
134
  return $arg;
@@ -139,35 +151,36 @@ class YARPP_Cache_Tables extends YARPP_Cache {
139
  */
140
  public function begin_yarpp_time() {
141
  $this->yarpp_time = true;
142
- add_filter('posts_join',array(&$this,'join_filter'));
143
- add_filter('posts_where',array(&$this,'where_filter'));
144
- add_filter('posts_orderby',array(&$this,'orderby_filter'));
145
- add_filter('posts_fields',array(&$this,'fields_filter'));
146
- add_filter('post_limits',array(&$this,'limit_filter'));
147
- add_action('pre_get_posts',array(&$this,'add_signature'));
148
  // sets the score override flag.
149
- add_action('parse_query',array(&$this,'set_score_override_flag'));
150
  }
151
-
152
  public function end_yarpp_time() {
153
  $this->yarpp_time = false;
154
- remove_filter('posts_join',array(&$this,'join_filter'));
155
- remove_filter('posts_where',array(&$this,'where_filter'));
156
- remove_filter('posts_orderby',array(&$this,'orderby_filter'));
157
- remove_filter('posts_fields',array(&$this,'fields_filter'));
158
- remove_filter('post_limits',array(&$this,'limit_filter'));
159
- remove_action('pre_get_posts',array(&$this,'add_signature'));
160
- remove_action('parse_query',array(&$this,'set_score_override_flag'));
161
  }
162
-
163
  // @return YARPP_NO_RELATED | YARPP_RELATED | YARPP_NOT_CACHED | YARPP_DONT_RUN
164
- public function is_cached($reference_ID) {
165
  global $wpdb;
166
-
167
  $result = wp_cache_get( 'is_cached_' . $reference_ID, 'yarpp' );
168
- if ( false !== $result )
169
  return $result;
170
-
 
171
  // @since 3.5.3b3: check for max instead of min, so that if ID=0 and ID=X
172
  // are both saved, we act like there *are* related posts, because there are.
173
 
@@ -176,24 +189,26 @@ class YARPP_Cache_Tables extends YARPP_Cache {
176
  $max_id = $this->query_safely(
177
  'get_var',
178
  array(
179
- "select max(ID) as max_id from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " where reference_ID = $reference_ID"
180
  )
181
  );
182
 
183
- if($max_id instanceof WP_Error){
184
  return YARPP_DONT_RUN;
185
  }
186
 
187
- if ( is_null( $max_id ) )
188
  return YARPP_NOT_CACHED;
189
-
190
- if ( 0 == $max_id )
 
191
  $result = YARPP_NO_RELATED;
192
- else
193
  $result = YARPP_RELATED;
194
-
 
195
  wp_cache_set( 'is_cached_' . $reference_ID, $result, 'yarpp' );
196
-
197
  return $result;
198
  }
199
 
@@ -201,67 +216,73 @@ class YARPP_Cache_Tables extends YARPP_Cache {
201
  global $wpdb;
202
 
203
  $reference_IDs = wp_parse_id_list( $reference_IDs );
204
-
205
- if ( !count($reference_IDs) )
206
  return;
207
-
208
- $wpdb->query("delete from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " where reference_ID in (".implode(',',$reference_IDs).")");
 
209
  // @since 3.5.2: clear is_cached_* values as well
210
- foreach ( $reference_IDs as $id )
211
  wp_cache_delete( 'is_cached_' . $id, 'yarpp' );
 
212
  }
213
 
214
  /**
215
  * Primes the YARPP related cache table.
216
- * @param int $reference_ID post ID to which we will find related content
 
217
  * @param array $args see YARPP::display_related()
218
  *
219
  * @return string (YARPP_RELATED | YARPP_NO_RELATED | YARPP_DONT_RUN)
220
  */
221
- protected function update($reference_ID, $args = array()) {
222
  global $wpdb;
223
-
224
- $original_related = (array) @$this->related($reference_ID);
225
 
226
- if ( count($original_related) ) {
 
 
227
  // clear out the cruft
228
- $this->clear($reference_ID);
229
  }
230
 
231
  $result = $this->query_safely(
232
- 'query',
233
- array(
234
- "insert into {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " (reference_ID,ID,score) " . $this->sql( $reference_ID, $args ) . " on duplicate key update date = now()"
235
- )
236
- );
237
- if($result instanceof WP_Error){
238
  return YARPP_DONT_RUN;
239
  }
240
 
241
  // If there were related entries saved...
242
  if ( $wpdb->rows_affected ) {
243
- $new_related = $this->related($reference_ID);
244
 
245
- if ($this->core->debug) echo "<!--YARPP just set the cache for post $reference_ID-->";
 
 
246
 
247
  // Clear the caches of any items which are no longer related or are newly related.
248
- if ( count($original_related) ) {
249
- $this->clear(array_diff($original_related, $new_related));
250
- $this->clear(array_diff($new_related, $original_related));
251
  }
252
-
253
  return YARPP_RELATED;
254
  } else {
255
  $wpdb->query(
256
  $wpdb->prepare(
257
- "insert into " . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE . " (reference_ID,ID,score) values (%d,0,0) on duplicate key update date = now()",
258
  $reference_ID
259
  )
260
  );
261
 
262
  // Clear the caches of those which are no longer related.
263
- if ( count($original_related) )
264
- $this->clear($original_related);
 
265
 
266
  return YARPP_NO_RELATED;
267
  }
@@ -269,45 +290,45 @@ class YARPP_Cache_Tables extends YARPP_Cache {
269
 
270
  public function flush() {
271
  global $wpdb;
272
- $wpdb->query("truncate table `" . $wpdb->prefix. YARPP_TABLES_RELATED_TABLE . '`');
273
  // @since 3.5.2: clear object cache, used for is_cached_* values
274
  wp_cache_flush();
275
  }
276
 
277
- public function related($reference_ID = null, $related_ID = null) {
278
  global $wpdb;
279
 
280
- if ( !is_int( $reference_ID ) && !is_int( $related_ID ) ) {
281
  _doing_it_wrong( __METHOD__, 'reference ID and/or related ID must be set', '3.4' );
282
  return;
283
  }
284
 
285
- if (!is_null($reference_ID) && !is_null($related_ID)) {
286
  $results = $wpdb->get_col(
287
  $wpdb->prepare(
288
- "select ID from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " where reference_ID = %d and ID = %d",
289
  $reference_ID,
290
  $related_ID
291
  )
292
  );
293
- return count($results) > 0;
294
  }
295
 
296
  // return a list of ID's of "related" entries
297
- if ( !is_null($reference_ID) ) {
298
  return $wpdb->get_col(
299
  $wpdb->prepare(
300
- "select distinct ID from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " where reference_ID = %d and ID != 0",
301
  $related_ID
302
  )
303
  );
304
  }
305
 
306
  // return a list of entities which list this post as "related"
307
- if ( !is_null($related_ID) ) {
308
  return $wpdb->get_col(
309
  $wpdb->prepare(
310
- "select distinct reference_ID from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " where ID = %d",
311
  $related_ID
312
  )
313
  );
@@ -322,23 +343,26 @@ class YARPP_Cache_Tables extends YARPP_Cache {
322
  public function get_keywords( $ID, $type = 'all' ) {
323
  global $wpdb;
324
 
325
- if ( !is_int($ID) )
326
  return false;
 
327
 
328
  // @since 4: compute fresh each time, instead of using cache table.
329
  // the old keyword cache would basically have to be recomputed every time the
330
  // relatedness cache was recomputed, but no more, so there's no point in keeping
331
  // these around separately.
332
  $keywords = array(
333
- 'body' => $this->body_keywords($ID),
334
- 'title' => $this->title_keywords($ID)
335
  );
336
 
337
- if ( empty($keywords) )
338
  return false;
339
-
340
- if ( 'all' == $type )
 
341
  return $keywords;
342
- return $keywords[$type];
 
343
  }
344
- }
1
  <?php
2
 
3
  class YARPP_Cache_Tables extends YARPP_Cache {
4
+ public $name = 'custom tables';
5
 
6
  /**
7
  * SETUP/STATUS
17
  public function setup() {
18
  $this->core->db_schema->create_cache_table();
19
  }
20
+
21
+ public function upgrade( $last_version ) {
22
  global $wpdb;
23
+ if ( $last_version && version_compare( '3.2.1b4', $last_version ) > 0 ) {
24
  // Change primary key to be (reference_ID, ID) to ensure that we don't
25
  // get duplicates.
26
  // We unfortunately have to clear the cache first here, to ensure that there
27
  // are no duplicates.
28
  $this->flush();
29
+ $wpdb->query(
30
+ 'ALTER TABLE ' . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE .
31
+ ' DROP PRIMARY KEY ,' .
32
+ ' ADD PRIMARY KEY ( `reference_ID` , `ID` ),' .
33
+ ' ADD INDEX (`score`), ADD INDEX (`ID`)'
34
+ );
35
  }
36
+ if ( $last_version && version_compare( '3.5.2b3', $last_version ) > 0 ) {
37
  // flush object cache, as bad is_cached_* values were stored before
38
  wp_cache_flush();
39
  }
40
+ if ( $last_version && version_compare( '3.6b1', $last_version ) > 0 ) {
41
  // remove keywords table
42
+ if ( defined( 'YARPP_TABLES_KEYWORDS_TABLE' ) ) {
43
  $old_keywords_table = $wpdb->prefix . YARPP_TABLES_KEYWORDS_TABLE;
44
+ } else {
45
  $old_keywords_table = $wpdb->prefix . 'yarpp_keyword_cache';
46
+ }
47
+
48
+ $wpdb->query( "drop table if exists `$old_keywords_table`" );
49
  }
50
  }
51
 
52
  public function cache_status() {
53
  global $wpdb;
54
+ return $wpdb->get_var(
55
+ "select (count(p.ID)-sum(c.ID IS NULL))/count(p.ID)
56
  FROM `{$wpdb->posts}` as p
57
  LEFT JOIN `{$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . "` as c ON (p.ID = c.reference_ID)
58
+ WHERE p.post_status = 'publish' "
59
+ );
60
  }
61
 
62
+ public function uncached( $limit = 20, $offset = 0 ) {
63
  global $wpdb;
64
  return $wpdb->get_col(
65
  $wpdb->prepare(
73
  )
74
  );
75
  }
76
+
77
  public function stats() {
78
  global $wpdb;
79
+ return wp_list_pluck( $wpdb->get_results( "select num, count(*) as ct from (select 0 + if(id = 0, 0, count(ID)) as num from {$wpdb->prefix}yarpp_related_cache group by reference_ID) as t group by num order by num asc", OBJECT_K ), 'ct' );
80
  }
81
+
82
  public function graph_data( $threshold = 5 ) {
83
  global $wpdb;
84
+
85
+ $threshold = absint( $threshold );
86
+ $results = $wpdb->get_results(
87
+ "select pair, sum(score) as score from
88
  ((select concat(reference_ID, '-', ID) as pair, score from {$wpdb->prefix}yarpp_related_cache where reference_ID < ID)
89
  union
90
  (select concat(ID, '-', reference_ID) as pair, score from {$wpdb->prefix}yarpp_related_cache where ID < reference_ID)) as t
91
  group by pair
92
+ having sum(score) > {$threshold}"
93
+ );
94
  return $results;
95
  }
96
 
97
  /**
98
  * MAGIC FILTERS
99
  */
100
+ public function join_filter( $arg ) {
101
  global $wpdb;
102
+ if ( $this->yarpp_time ) {
103
  $arg .= " join {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " as yarpp on {$wpdb->posts}.ID = yarpp.ID";
104
+ }
105
  return $arg;
106
  }
107
 
108
+ public function where_filter( $arg ) {
109
  global $wpdb;
110
+ $threshold = $this->core->get_option( 'threshold' );
111
+ if ( $this->yarpp_time ) {
112
 
113
+ $arg = str_replace( "$wpdb->posts.ID = ", "yarpp.score >= $threshold and yarpp.reference_ID = ", $arg );
114
 
115
+ $recent = $this->core->get_option( 'recent' );
116
+ if ( (bool) $recent ) {
117
+ $arg .= " and post_date > date_sub(now(), interval {$recent}) ";
118
+ }
119
  }
120
  return $arg;
121
  }
122
 
123
+ public function orderby_filter( $arg ) {
124
  global $wpdb;
125
  // If ordering by score also order by post ID to keep them consistent in cases where the score is the same
126
  // for multiple posts.
127
+ if ( $this->yarpp_time and $this->score_override ) {
128
+ $arg = $this->orderby_score( $arg );
129
+ }
130
  return $arg;
131
  }
132
 
133
+ public function fields_filter( $arg ) {
134
  global $wpdb;
135
+ if ( $this->yarpp_time ) {
136
+ $arg .= ', yarpp.score';
137
+ }
138
  return $arg;
139
  }
140
 
141
+ public function limit_filter( $arg ) {
142
  global $wpdb;
143
+ if ( $this->yarpp_time and $this->online_limit ) {
144
  return " limit {$this->online_limit} ";
145
  }
146
  return $arg;
151
  */
152
  public function begin_yarpp_time() {
153
  $this->yarpp_time = true;
154
+ add_filter( 'posts_join', array( &$this, 'join_filter' ) );
155
+ add_filter( 'posts_where', array( &$this, 'where_filter' ) );
156
+ add_filter( 'posts_orderby', array( &$this, 'orderby_filter' ) );
157
+ add_filter( 'posts_fields', array( &$this, 'fields_filter' ) );
158
+ add_filter( 'post_limits', array( &$this, 'limit_filter' ) );
159
+ add_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
160
  // sets the score override flag.
161
+ add_action( 'parse_query', array( &$this, 'set_score_override_flag' ) );
162
  }
163
+
164
  public function end_yarpp_time() {
165
  $this->yarpp_time = false;
166
+ remove_filter( 'posts_join', array( &$this, 'join_filter' ) );
167
+ remove_filter( 'posts_where', array( &$this, 'where_filter' ) );
168
+ remove_filter( 'posts_orderby', array( &$this, 'orderby_filter' ) );
169
+ remove_filter( 'posts_fields', array( &$this, 'fields_filter' ) );
170
+ remove_filter( 'post_limits', array( &$this, 'limit_filter' ) );
171
+ remove_action( 'pre_get_posts', array( &$this, 'add_signature' ) );
172
+ remove_action( 'parse_query', array( &$this, 'set_score_override_flag' ) );
173
  }
174
+
175
  // @return YARPP_NO_RELATED | YARPP_RELATED | YARPP_NOT_CACHED | YARPP_DONT_RUN
176
+ public function is_cached( $reference_ID ) {
177
  global $wpdb;
178
+
179
  $result = wp_cache_get( 'is_cached_' . $reference_ID, 'yarpp' );
180
+ if ( false !== $result ) {
181
  return $result;
182
+ }
183
+
184
  // @since 3.5.3b3: check for max instead of min, so that if ID=0 and ID=X
185
  // are both saved, we act like there *are* related posts, because there are.
186
 
189
  $max_id = $this->query_safely(
190
  'get_var',
191
  array(
192
+ "select max(ID) as max_id from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . " where reference_ID = $reference_ID",
193
  )
194
  );
195
 
196
+ if ( $max_id instanceof WP_Error ) {
197
  return YARPP_DONT_RUN;
198
  }
199
 
200
+ if ( is_null( $max_id ) ) {
201
  return YARPP_NOT_CACHED;
202
+ }
203
+
204
+ if ( 0 == $max_id ) {
205
  $result = YARPP_NO_RELATED;
206
+ } else {
207
  $result = YARPP_RELATED;
208
+ }
209
+
210
  wp_cache_set( 'is_cached_' . $reference_ID, $result, 'yarpp' );
211
+
212
  return $result;
213
  }
214
 
216
  global $wpdb;
217
 
218
  $reference_IDs = wp_parse_id_list( $reference_IDs );
219
+
220
+ if ( ! count( $reference_IDs ) ) {
221
  return;
222
+ }
223
+
224
+ $wpdb->query( "delete from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . ' where reference_ID in (' . implode( ',', $reference_IDs ) . ')' );
225
  // @since 3.5.2: clear is_cached_* values as well
226
+ foreach ( $reference_IDs as $id ) {
227
  wp_cache_delete( 'is_cached_' . $id, 'yarpp' );
228
+ }
229
  }
230
 
231
  /**
232
  * Primes the YARPP related cache table.
233
+ *
234
+ * @param int $reference_ID post ID to which we will find related content
235
  * @param array $args see YARPP::display_related()
236
  *
237
  * @return string (YARPP_RELATED | YARPP_NO_RELATED | YARPP_DONT_RUN)
238
  */
239
+ protected function update( $reference_ID, $args = array() ) {
240
  global $wpdb;
 
 
241
 
242
+ $original_related = (array) @$this->related( $reference_ID );
243
+
244
+ if ( count( $original_related ) ) {
245
  // clear out the cruft
246
+ $this->clear( $reference_ID );
247
  }
248
 
249
  $result = $this->query_safely(
250
+ 'query',
251
+ array(
252
+ "insert into {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . ' (reference_ID,ID,score) ' . $this->sql( $reference_ID, $args ) . ' on duplicate key update date = now()',
253
+ )
254
+ );
255
+ if ( $result instanceof WP_Error ) {
256
  return YARPP_DONT_RUN;
257
  }
258
 
259
  // If there were related entries saved...
260
  if ( $wpdb->rows_affected ) {
261
+ $new_related = $this->related( $reference_ID );
262
 
263
+ if ( $this->core->debug ) {
264
+ echo "<!--YARPP just set the cache for post $reference_ID-->";
265
+ }
266
 
267
  // Clear the caches of any items which are no longer related or are newly related.
268
+ if ( count( $original_related ) ) {
269
+ $this->clear( array_diff( $original_related, $new_related ) );
270
+ $this->clear( array_diff( $new_related, $original_related ) );
271
  }
272
+
273
  return YARPP_RELATED;
274
  } else {
275
  $wpdb->query(
276
  $wpdb->prepare(
277
+ 'insert into ' . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE . ' (reference_ID,ID,score) values (%d,0,0) on duplicate key update date = now()',
278
  $reference_ID
279
  )
280
  );
281
 
282
  // Clear the caches of those which are no longer related.
283
+ if ( count( $original_related ) ) {
284
+ $this->clear( $original_related );
285
+ }
286
 
287
  return YARPP_NO_RELATED;
288
  }
290
 
291
  public function flush() {
292
  global $wpdb;
293
+ $wpdb->query( 'truncate table `' . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE . '`' );
294
  // @since 3.5.2: clear object cache, used for is_cached_* values
295
  wp_cache_flush();
296
  }
297
 
298
+ public function related( $reference_ID = null, $related_ID = null ) {
299
  global $wpdb;
300
 
301
+ if ( ! is_int( $reference_ID ) && ! is_int( $related_ID ) ) {
302
  _doing_it_wrong( __METHOD__, 'reference ID and/or related ID must be set', '3.4' );
303
  return;
304
  }
305
 
306
+ if ( ! is_null( $reference_ID ) && ! is_null( $related_ID ) ) {
307
  $results = $wpdb->get_col(
308
  $wpdb->prepare(
309
+ "select ID from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . ' where reference_ID = %d and ID = %d',
310
  $reference_ID,
311
  $related_ID
312
  )
313
  );
314
+ return count( $results ) > 0;
315
  }
316
 
317
  // return a list of ID's of "related" entries
318
+ if ( ! is_null( $reference_ID ) ) {
319
  return $wpdb->get_col(
320
  $wpdb->prepare(
321
+ "select distinct ID from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . ' where reference_ID = %d and ID != 0',
322
  $related_ID
323
  )
324
  );
325
  }
326
 
327
  // return a list of entities which list this post as "related"
328
+ if ( ! is_null( $related_ID ) ) {
329
  return $wpdb->get_col(
330
  $wpdb->prepare(
331
+ "select distinct reference_ID from {$wpdb->prefix}" . YARPP_TABLES_RELATED_TABLE . ' where ID = %d',
332
  $related_ID
333
  )
334
  );
343
  public function get_keywords( $ID, $type = 'all' ) {
344
  global $wpdb;
345
 
346
+ if ( ! is_int( $ID ) ) {
347
  return false;
348
+ }
349
 
350
  // @since 4: compute fresh each time, instead of using cache table.
351
  // the old keyword cache would basically have to be recomputed every time the
352
  // relatedness cache was recomputed, but no more, so there's no point in keeping
353
  // these around separately.
354
  $keywords = array(
355
+ 'body' => $this->body_keywords( $ID ),
356
+ 'title' => $this->title_keywords( $ID ),
357
  );
358
 
359
+ if ( empty( $keywords ) ) {
360
  return false;
361
+ }
362
+
363
+ if ( 'all' == $type ) {
364
  return $keywords;
365
+ }
366
+ return $keywords[ $type ];
367
  }
368
+ }
classes/YARPP_Core.php CHANGED
@@ -5,106 +5,106 @@
5
  */
6
  class YARPP {
7
 
8
- /*
9
- * Here's a list of all the options YARPP uses (except version), as well as their default values,
10
- * sans the yarpp_ prefix, split up into binary options and value options. These arrays are used in updating
11
- * settings (yarpp_options.php) and other tasks.
12
- */
13
- public $default_options = array();
14
- public $pro_default_options = array();
15
- public $default_hidden_metaboxes = array();
16
- public $debug = false;
17
- public $yarppPro = null;
18
  /**
19
  * @var YARPP_Cache_Bypass
20
  */
21
- public $cache_bypass;
22
  /**
23
  * @var YARPP_Cache
24
  */
25
- public $cache;
26
- public $admin;
27
  /**
28
  * @var YARPP_DB_Schema
29
  */
30
- public $db_schema;
31
 
32
  /**
33
  * @var YARPP_Cache
34
  */
35
- private $active_cache;
36
- private $storage_class;
37
- private $default_dimensions = array(
38
- 'width' => 120,
39
- 'height' => 120,
40
- 'crop' => false,
41
- 'size' => '120x120',
42
- '_default' => true
43
- );
44
  /**
45
  * @var bool Set to true while YARPP is rendering related posts (a very bad time to start looking for related
46
  * content, and start infintely recursing !)
47
  */
48
- private $rendering_related_content;
49
 
50
  public function __construct() {
 
51
  $this->load_default_options();
52
- $this->yarppPro = $this->get_pro_options();
53
 
54
  /* Loads the plugin's translated strings. */
55
- load_plugin_textdomain('yarpp', false, plugin_basename(YARPP_DIR).'/lang');
56
 
57
  /* Load cache object. */
58
- $this->storage_class = 'YARPP_Cache_'.ucfirst(YARPP_CACHE_TYPE);
59
- $this->cache = new $this->storage_class($this);
60
- $this->cache_bypass = new YARPP_Cache_Bypass($this);
61
  $this->db_schema = new YARPP_DB_Schema();
62
  $this->db_options = new YARPP_DB_Options();
63
 
64
- register_activation_hook(__FILE__, array($this, 'activate'));
65
 
66
- /**
67
  * @since 3.2 Update cache on delete.
68
- */
69
- add_action('delete_post', array($this->cache, 'delete_post'), 10, 1);
70
 
71
- /**
72
- * @since 3.5.3 Use transition_post_status instead of save_post hook.
73
  * @since 3.2.1 Handle post_status transitions.
74
- */
75
- add_action('transition_post_status', array($this->cache, 'transition_post_status'), 10, 3);
76
 
77
  /**
78
  * Initializes yarpp rest routes
79
  */
80
- if(apply_filters('rest_enabled', true) && class_exists('WP_REST_Controller') && class_exists('WP_REST_Posts_Controller')){
81
- include_once( YARPP_DIR . '/classes/YARPP_Rest_Api.php' );
82
  new YARPP_Rest_Api();
83
  }
84
 
85
-
86
  /* Automatic display hooks: */
87
  /**
88
  * Allow filtering the priority of YARPP's placement.
89
  */
90
- $content_priority = apply_filters('yarpp_content_priority', 1200);
91
- $feed_priority = apply_filters('yarpp_feed_priority', 600);
92
- $excerpt_rss_priority = apply_filters('yarpp_excerpt_rss_priority', 600);
93
-
94
- add_filter('the_content', array($this, 'the_content'), $content_priority);
95
- add_action('bbp_template_after_single_topic', array($this,'add_to_bbpress'));
96
- add_filter('the_content_feed', array($this, 'the_content_feed'), $feed_priority);
97
- add_filter('the_excerpt_rss', array($this, 'the_excerpt_rss' ), $excerpt_rss_priority);
98
- add_action('wp_enqueue_scripts', array($this, 'maybe_enqueue_thumbnails_stylesheet'));
99
  add_filter( 'is_protected_meta', array( $this, 'is_protected_meta' ), 10, 3 );
100
 
101
- /**
102
  * If we're using thumbnails, register yarpp-thumbnail size, if theme has not already.
103
  * Note: see FAQ in the readme if you would like to change the YARPP thumbnail size.
104
  * If theme has already yarpp-thumbnail size registered and we also try to register yarpp-thumbnail then it will throw a fatal error. So it is necessary to check if yarpp-thumbnail size is not registered.
105
- */
106
  global $add_image_size_by_yarpp;
107
- if ( false === yarpp_get_image_sizes( 'yarpp-thumbnail' ) ) {
108
  $width = 120;
109
  $height = 120;
110
  $crop = true;
@@ -114,27 +114,32 @@ class YARPP {
114
  $add_image_size_by_yarpp = false;
115
  }
116
 
117
- if (isset($_REQUEST['yarpp_debug'])) $this->debug = true;
118
-
119
- if (! $this->db_options->plugin_version_in_db()) $this->db_options->add_upgrade_flag();
120
 
121
- /**
 
 
 
 
122
  * @since 3.4 Only load UI if we're in the admin.
123
- */
124
- if (is_admin()) {
125
- require_once(YARPP_DIR.'/classes/YARPP_Admin.php');
126
- $this->admin = new YARPP_Admin($this);
127
- if( ! defined('DOING_AJAX')){
128
  $this->enforce();
129
  }
130
  }
131
  $shortcode = new YARPP_Shortcode();
132
  $shortcode->register();
133
  }
 
134
  /**
135
  * Add yarpp_meta key to protected list.
136
- *
137
- * @since 5.19
138
  *
139
  * @param bool $protected Whether the key is considered protected.
140
  * @param string $meta_key Metadata key.
@@ -147,168 +152,180 @@ class YARPP {
147
  }
148
  return $protected;
149
  }
150
- /*
 
151
  * OPTIONS
152
  */
153
- private function load_pro_default_options() {
154
- return
155
- array(
156
- 'active' => '0',
157
- 'aid' => null,
158
- 'st' => null,
159
- 'v' => null,
160
- 'dpid' => null,
161
- 'optin' => false,
162
- 'auto_display_post_types' => array('post')
163
- );
164
- }
165
 
166
  private function load_default_options() {
167
  $this->default_options = array(
168
- 'threshold' => 1,
169
- 'limit' => 4,
170
- 'excerpt_length' => 10,
171
- 'recent' => false,
172
- 'before_title' => '<li>',
173
- 'after_title' => '</li>',
174
- 'before_post' => ' <small>',
175
- 'after_post' => '</small>',
176
- 'before_related' => '<h3>'.__('Related posts:','yarpp').'</h3><ol>',
177
- 'after_related' => '</ol>',
178
- 'no_results' => '<p>'.__('No related posts.','yarpp').'</p>',
179
- 'order' => 'score DESC',
180
- 'rss_limit' => 3,
181
- 'rss_excerpt_length' => 10,
182
- 'rss_before_title' => '<li>',
183
- 'rss_after_title' => '</li>',
184
- 'rss_before_post' => ' <small>',
185
- 'rss_after_post' => '</small>',
186
- 'rss_before_related' => '<h3>'.__('Related posts:','yarpp').'</h3><ol>',
187
- 'rss_after_related' => '</ol>',
188
- 'rss_no_results' => '<p>'.__('No related posts.','yarpp').'</p>',
189
- 'rss_order' => 'score DESC',
190
- 'past_only' => false,
191
- 'show_excerpt' => false,
192
- 'rss_show_excerpt' => false,
193
- 'template' => false,
194
- 'rss_template' => false,
195
- 'show_pass_post' => false,
196
- 'cross_relate' => false,
197
- 'include_sticky_posts' => true,
198
- 'generate_missing_thumbnails' => false,
199
- 'rss_display' => false,
200
- 'rss_excerpt_display' => true,
201
- 'promote_yarpp' => false,
202
- 'rss_promote_yarpp' => false,
203
- 'myisam_override' => false,
204
- 'exclude' => '',
205
- 'include_post_type' => get_post_types( array() ),
206
- 'weight' => array(
207
  'title' => 0,
208
- 'body' => 0,
209
- 'tax' => array(
210
  'category' => 1,
211
- 'post_tag' => 1
212
- )
213
  ),
214
- 'require_tax' => array(),
215
- 'optin' => false,
216
- 'thumbnails_heading' => __('Related posts:','yarpp'),
217
- 'thumbnails_default' => plugins_url('images/default.png', dirname(__FILE__)),
218
- 'rss_thumbnails_heading' => __('Related posts:','yarpp'),
219
- 'rss_thumbnails_default' => plugins_url('images/default.png', dirname( __FILE__)),
220
- 'display_code' => false,
221
- 'auto_display_archive' => false,
222
- 'auto_display_post_types' => array('post'),
223
- 'pools' => array(),
224
- 'manually_using_thumbnails' => false,
225
- 'rest_api_display' => true,
226
- 'thumbnail_size_display' => 0,
227
  'custom_theme_thumbnail_size_display' => 0,
228
- 'thumbnail_size_feed_display' => 0,
229
- 'rest_api_client_side_caching' => false,
230
- 'yarpp_rest_api_cache_time' => 15
231
  );
232
  }
233
-
234
- public function set_option($options, $value = null) {
235
  $current_options = $this->get_option();
236
-
237
  /* We can call yarpp_set_option(key,value) if we like. */
238
- if (!is_array($options)) {
239
- if (isset($value)) {
240
- $options = array($options => $value);
241
- } else {
242
  return false;
243
- }
244
  }
245
-
246
- $new_options = array_merge($current_options, $options);
247
- $this->db_options->set_yarpp_options($new_options);
248
-
249
- // new in 3.1: clear cache when updating certain settings.
250
- $clear_cache_options = array('show_pass_post' => 1, 'recent' => 1, 'threshold' => 1, 'past_only' => 1, 'include_sticky_posts' => 1, 'cross_relate' => 1);
251
 
252
- $relevant_options = array_intersect_key($options, $clear_cache_options);
253
- $relevant_current_options = array_intersect_key($current_options, $clear_cache_options);
254
- $new_options_which_require_flush = array_diff_assoc($relevant_options, $relevant_current_options);
255
 
256
- if (count($new_options_which_require_flush)
257
- || ($new_options['limit'] > $current_options['limit'])
258
- || ($new_options['weight'] != $current_options['weight'])
259
- || ($new_options['exclude'] != $current_options['exclude'])
260
- || ($new_options['require_tax'] != $current_options['require_tax'])
261
- || ($new_options['include_post_type'] != $current_options['include_post_type'])
262
- ) {
263
- $this->cache->flush();
264
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  }
266
 
267
- /**
268
  * @since 3.4b8 $option can be a path, of the query_str variety, i.e. "option[suboption][subsuboption]"
269
- */
270
- public function get_option($option = null) {
271
  $options = $this->db_options->get_yarpp_options();
272
 
273
  // ensure defaults if not set:
274
- $options = array_merge($this->default_options, $options);
275
-
276
- if (is_null($option)) return $options;
277
-
278
- $optionpath = array();
279
- $parsed_option = array();
280
- wp_parse_str($option, $parsed_option);
281
- $optionpath = $this->array_flatten($parsed_option);
282
-
 
 
283
  $current = $options;
284
- foreach ($optionpath as $optionpart) {
285
- if (!is_array($current) || !isset($current[$optionpart])) return null;
286
- $current = $current[$optionpart];
 
 
287
  }
288
 
289
  return $current;
290
  }
291
 
292
- private function get_pro_options(){
293
- $current = get_option('yarpp_pro');
294
- $defaults = $this->load_pro_default_options();
 
 
 
 
 
 
 
 
295
 
296
- if ($current) {
297
- $out = array_merge($defaults,$current);
298
- update_option('yarpp_pro', $out);
299
- } else {
300
- $out = $defaults;
301
- add_option('yarpp_pro',$out);
302
- }
303
 
304
- return $out;
305
- }
306
-
307
- private function array_flatten($array, $given = array()) {
308
- foreach ($array as $key => $val) {
309
  $given[] = $key;
310
- if ( is_array($val) )
311
- $given = $this->array_flatten($val, $given);
 
312
  }
313
  return $given;
314
  }
@@ -317,17 +334,19 @@ class YARPP {
317
  * INFRASTRUCTURE
318
  */
319
 
320
- /**
321
- * @since 3.5.2 Function to enforce YARPP setup if not ready, activate; else upgrade.
322
- */
323
- public function enforce() {
324
- if (!$this->enabled()) {
325
- $this->activate(); // activate calls upgrade later, so it's covered.
326
- } else {
327
- $this->upgrade();
328
- }
329
- if ($this->get_option('optin')) $this->optin_ping();
330
- }
 
 
331
 
332
  public function enabled() {
333
  if ( ! (bool) $this->cache->is_enabled() ) {
@@ -336,34 +355,37 @@ class YARPP {
336
  return $this->diagnostic_fulltext_indices();
337
  }
338
  }
339
-
340
  public function activate() {
341
- if ((bool) $this->cache->is_enabled() === false) {
342
  $this->cache->setup();
343
  }
344
 
345
  /* If we're not enabled, give up. */
346
- if (!$this->enabled()) return false;
 
 
347
 
348
- if (!$this->db_options->plugin_version_in_db()) {
349
  $this->db_options->update_plugin_version_in_db();
350
- $this->version_info(true);
351
  } else {
352
  $this->upgrade();
353
  }
354
-
355
  return true;
356
  }
357
 
358
  /**
359
  * DIAGNOSTICS
 
360
  * @since 4.0 Moved into separate functions. Note return value types can differ.
361
  * @since 5.2.0 consider using $this->db_schema->posta_table_database_engine() or
362
  * $this->db_schema->database_supports_fulltext_indexes() instead
363
  */
364
  public function diagnostic_myisam_posts() {
365
  $engine = $this->db_schema->posts_table_database_engine();
366
- switch($engine){
367
  case 'MyISAM':
368
  return true;
369
  case null:
@@ -390,33 +412,33 @@ class YARPP {
390
  * @return bool
391
  */
392
  public function enable_fulltext() {
393
- _deprecated_function('YARPP::enable_fulltext','5.15.0');
394
- if(! $this->db_supports_fulltext()){
395
- return false;
396
- }
397
- if(! $this->enable_fulltext_titles()){
398
- return false;
399
- }
400
- if( ! $this->enable_fulltext_contents()){
401
- return false;
402
- }
403
- return true;
404
- }
405
-
406
- protected function db_supports_fulltext(){
407
  /*
408
- * If we haven't already re-attempted creating the database indexes and the database doesn't support adding
409
- * those indexes, disable it.
410
- */
411
- if (!(bool) $this->get_option(YARPP_DB_Options::YARPP_MYISAM_OVERRIDE) &&
412
- ! $this->db_schema->database_supports_fulltext_indexes()) {
413
  $this->disable_fulltext();
414
  return false;
415
  }
416
  return true;
417
  }
418
- public function enable_fulltext_titles(){
419
- if(! $this->db_schema->title_column_has_index()) {
420
  if ( $this->db_schema->add_title_index() ) {
421
  $this->db_options->delete_fulltext_db_error_record();
422
  } else {
@@ -428,9 +450,9 @@ class YARPP {
428
  return true;
429
  }
430
 
431
- public function enable_fulltext_contents(){
432
- if(! $this->db_schema->content_column_has_index()){
433
- if ( $this->db_schema->add_content_index()) {
434
  $this->db_options->delete_fulltext_db_error_record();
435
  } else {
436
  $this->disable_fulltext();
@@ -445,39 +467,43 @@ class YARPP {
445
  * Stop considering post title and body in relatedness criteria.
446
  */
447
  public function disable_fulltext() {
448
- if ($this->db_options->is_fulltext_disabled()) return;
449
-
 
 
450
  /* Remove title and body weights: */
451
- $weight = $this->get_option('weight');
452
- unset($weight['title']);
453
- unset($weight['body']);
454
- $this->set_option(array('weight' => $weight));
455
 
456
  /* cut threshold by half: */
457
- $threshold = (float) $this->get_option('threshold');
458
- $this->set_option(array('threshold' => round($threshold / 2)));
459
  }
460
 
461
  /**
462
  * Returns true if we consider this to be a big database (based on posts records); false otherwise.
463
  * Uses the constants YARPP_BIG_DB
 
464
  * @return bool
465
  */
466
- public function diagnostic_big_db(){
467
  global $wpdb;
468
- if(! defined('YARPP_BIG_DB')){
469
- define('YARPP_BIG_DB', 5000);
470
  }
471
  $sql = 'SELECT count(*) FROM ' . $wpdb->posts;
472
- // Note: count includes drafts, revisions, etc
473
- $posts_count = $wpdb->get_var($sql);
474
- return (int)$posts_count > YARPP_BIG_DB;
475
  }
476
 
477
- /*
478
- * Try to retrieve fulltext index from database.
479
- * @return bool
480
- */
 
481
  public function diagnostic_fulltext_indices() {
482
  return $this->db_schema->title_column_has_index() && $this->db_schema->content_column_has_index();
483
  }
@@ -485,46 +511,58 @@ class YARPP {
485
  public function diagnostic_hidden_metaboxes() {
486
  global $wpdb;
487
  $raw = $wpdb->get_var(
488
- "SELECT meta_value FROM $wpdb->usermeta ".
489
- "WHERE meta_key = 'metaboxhidden_settings_page_yarpp' ".
490
- "ORDER BY length(meta_value) ASC LIMIT 1"
491
- );
492
 
493
- if (!$raw) return $this->default_hidden_metaboxes;
 
 
494
 
495
- $list = maybe_unserialize($raw);
496
- if (!is_array($list)) return $this->default_hidden_metaboxes;
 
 
497
 
498
- return implode('|', $list);
499
  }
500
-
501
  public function diagnostic_post_thumbnails() {
502
- return current_theme_supports('post-thumbnails', 'post');
503
  }
504
-
505
  public function diagnostic_custom_templates() {
506
- return count($this->admin->get_templates());
507
  }
508
-
509
  public function diagnostic_happy() {
510
  $stats = $this->cache->stats();
511
 
512
- if (!(array_sum($stats) > 0)) return false;
513
-
514
- $sum = array_sum((array)array_map('array_product', array_map(null, array_values($stats), array_keys($stats))));
 
 
515
  $avg = $sum / array_sum( $stats );
516
 
517
- return ($this->cache->cache_status() > 0.1 && $avg > 2);
518
  }
519
-
520
  public function diagnostic_generate_thumbnails() {
521
- return (defined( 'YARPP_GENERATE_THUMBNAILS' ) && YARPP_GENERATE_THUMBNAILS) || (bool) $this->get_option( 'generate_missing_thumbnails' );
522
  }
523
 
524
  public function diagnostic_using_thumbnails() {
525
- if ($this->get_option('manually_using_thumbnails')) return true;
526
- if ($this->get_option('template') === 'thumbnails') return true;
527
- if ($this->get_option('rss_template') === 'thumbnails' && $this->get_option('rss_display')) return true;
 
 
 
 
 
 
528
  return false;
529
  }
530
  public function get_thumbnail_option_name() {
@@ -533,22 +571,24 @@ class YARPP {
533
  }
534
  $chosen_template = yarpp_get_option( 'template' );
535
  // check if they're using a custom template
536
- if ( 'thumbnails' === $chosen_template){
537
  return 'thumbnail_size_display';
538
  }
539
  return 'custom_theme_thumbnail_size_display';
540
  }
541
  public function thumbnail_dimensions() {
542
  global $_wp_additional_image_sizes;
543
- if (!isset($_wp_additional_image_sizes['yarpp-thumbnail'])) return $this->default_dimensions;
 
 
544
 
545
  // get user selected thumbnail size.
546
- $dimensions = yarpp_get_thumbnail_image_dimensions( $this->get_thumbnail_option_name() );
547
- if ( empty($dimensions) ) {
548
- $dimensions = $_wp_additional_image_sizes['yarpp-thumbnail'];
549
  $dimensions['size'] = 'yarpp-thumbnail';
550
- }
551
-
552
  /* Ensure YARPP dimensions format: */
553
  $dimensions['width'] = (int) $dimensions['width'];
554
  $dimensions['height'] = (int) $dimensions['height'];
@@ -559,24 +599,32 @@ class YARPP {
559
  * @deprecated 5.11.0
560
  * @see \YARPP::maybe_enqueue_thumbnails_stylesheet
561
  */
562
- public function maybe_enqueue_thumbnails(){
563
- _deprecated_function('YARPP::maybe_enqueue_thumbnails','5.11.0','YARPP::maybe_enqueue_thumbnails_stylesheet');
564
- return $this->maybe_enqueue_thumbnails_stylesheet();
565
  }
566
 
567
  public function maybe_enqueue_thumbnails_stylesheet() {
568
- if (is_feed()) return;
 
 
569
 
570
- $auto_display_post_types = $this->get_option('auto_display_post_types');
571
 
572
  /* If it's not an auto-display post type, return. */
573
- if (!in_array(get_post_type(), $auto_display_post_types)) return;
 
 
574
 
575
- if (!is_singular() && !($this->get_option('auto_display_archive') && (is_archive() || is_home()))) return;
 
 
576
 
577
- if ($this->get_option('template') !== 'thumbnails') return;
 
 
578
 
579
- $this->enqueue_thumbnails_stylesheet($this->thumbnail_dimensions());
580
  }
581
 
582
  /**
@@ -584,17 +632,17 @@ class YARPP {
584
  * @see YARPP::enqueue_thumbnails_stylesheet()
585
  * @param $dimensions
586
  */
587
- public function enqueue_thumbnails($dimensions) {
588
- _deprecated_function('YARPP::enqueue_thumbnails','5.11.0','YARPP::enqueue_thumbnails_stylesheet');
589
- return $this->enqueue_thumbnails_stylesheet($dimensions);
590
  }
591
 
592
  /**
593
  * @param $dimensions
594
  */
595
  public function enqueue_thumbnails_stylesheet( $dimensions ) {
596
-
597
- wp_register_style('yarpp-thumbnails', plugins_url('/style/styles_thumbnails.css', YARPP_MAIN_FILE ), array(), YARPP_VERSION);
598
  /**
599
  * Filter to allow dequeing of styles_thumbnails.css.
600
  *
@@ -602,309 +650,344 @@ class YARPP {
602
  */
603
  $enqueue_yarpp_thumbnails = apply_filters( 'yarpp_enqueue_thumbnails_style', true );
604
  if ( true === $enqueue_yarpp_thumbnails ) {
605
- $yarpp_custom_css = yarpp_thumbnail_inline_css( $dimensions );
606
  wp_enqueue_style( 'yarpp-thumbnails' );
607
  wp_add_inline_style( 'yarpp-thumbnails', $yarpp_custom_css );
608
- }
609
  }
610
 
611
- /*
612
  * Code based on Viper's Regenerate Thumbnails plugin '$dimensions' must be an array with size, crop, height, width attributes.
613
- */
614
- public function ensure_resized_post_thumbnail($post_id, $dimensions) {
615
 
616
- $thumbnail_id = get_post_thumbnail_id($post_id);
617
- $downsized = image_downsize($thumbnail_id, $dimensions['size']);
618
 
619
- if ($dimensions['crop'] && $downsized[1] && $downsized[2]
620
- && ($downsized[1] != $dimensions['width'] || $downsized[2] != $dimensions['height'])
621
- ) {
622
- /*
623
  * We want to trigger re-computation of the thumbnail here.
624
- * (only if downsized width and height are specified, for Photon behavior)
625
- */
626
- $fullSizePath = get_attached_file($thumbnail_id);
627
- if ($fullSizePath !== false && file_exists($fullSizePath)) {
628
- require_once(ABSPATH.'wp-admin/includes/image.php');
629
- $metadata = wp_generate_attachment_metadata($thumbnail_id, $fullSizePath);
630
- if (!is_wp_error($metadata)) {
631
- wp_update_attachment_metadata($thumbnail_id, $metadata);
632
  }
633
  }
634
  }
635
  }
636
-
637
  private $templates = null;
638
  public function get_templates() {
639
- if (is_null($this->templates)) {
640
- $this->templates = glob(STYLESHEETPATH.'/yarpp-template-*.php');
641
 
642
  // if glob hits an error, it returns false.
643
- if ($this->templates === false) $this->templates = array();
 
 
644
 
645
- // get basenames only
646
- $this->templates = (array)array_map(array($this, 'get_template_data'), $this->templates);
647
  }
648
  return (array) $this->templates;
649
  }
650
-
651
- public function get_template_data($file) {
652
- $headers = array(
653
- 'name' => 'YARPP Template',
654
- 'description' => 'Description',
655
- 'author' => 'Author',
656
- 'uri' => 'Author URI',
657
  );
658
- $data = get_file_data($file, $headers);
659
- $data['file'] = $file;
660
- $data['basename'] = basename($file);
661
 
662
- if (empty($data['name'])) $data['name'] = $data['basename'];
 
 
663
 
664
- return $data;
665
  }
666
-
667
- /*
668
  * UPGRADE ROUTINES
669
  */
670
-
671
  public function upgrade() {
672
  $last_version = $this->db_options->plugin_version_in_db();
673
 
674
- if (version_compare(YARPP_VERSION, $last_version) === 0) return;
675
- if ($last_version && version_compare('3.4b2', $last_version) > 0) $this->upgrade_3_4b2();
676
- if ($last_version && version_compare('3.4b5', $last_version) > 0) $this->upgrade_3_4b5();
677
- if ($last_version && version_compare('3.4b8', $last_version) > 0) $this->upgrade_3_4b8();
678
- if ($last_version && version_compare('3.4.4b2', $last_version) > 0) $this->upgrade_3_4_4b2();
679
- if ($last_version && version_compare('3.4.4b3', $last_version) > 0) $this->upgrade_3_4_4b3();
680
- if ($last_version && version_compare('3.4.4b4', $last_version) > 0) $this->upgrade_3_4_4b4();
681
- if ($last_version && version_compare('3.5.2b2', $last_version) > 0) $this->upgrade_3_5_2b2();
682
- if ($last_version && version_compare('3.6b7', $last_version) > 0) $this->upgrade_3_6b7();
683
- if ($last_version && version_compare('4.0.1', $last_version) > 0) $this->upgrade_4_0_1();
684
-
685
- $this->cache->upgrade($last_version);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
686
  /* flush cache in 3.4.1b5 as 3.4 messed up calculations. */
687
- if ($last_version && version_compare('3.4.1b5', $last_version) > 0) $this->cache->flush();
688
-
689
- $this->version_info(true);
690
-
 
 
691
  $this->db_options->update_plugin_version_in_db();
692
  $this->db_options->add_upgrade_flag();
693
- $this->delete_transient('yarpp_optin');
694
  }
695
-
696
  public function upgrade_3_4b2() {
697
  global $wpdb;
698
-
699
  $yarpp_3_3_options = array(
700
- 'threshold' => 4,
701
- 'limit' => 4,
702
- 'template_file' => '',
703
- 'excerpt_length' => 10,
704
- 'recent_number' => 12,
705
- 'recent_units' => 'month',
706
- 'before_title' => '<li>',
707
- 'after_title' => '</li>',
708
- 'before_post' => ' <small>',
709
- 'after_post' => '</small>',
710
- 'before_related' => '<h3>'.__('Related posts:','yarpp').'</h3><ol>',
711
- 'after_related' => '</ol>',
712
- 'no_results' => '<p>'.__('No related posts.','yarpp').'</p>',
713
- 'order' => 'score DESC',
714
- 'rss_limit' => 3,
715
- 'rss_template_file' => '',
716
- 'rss_excerpt_length' => 10,
717
- 'rss_before_title' => '<li>',
718
- 'rss_after_title' => '</li>',
719
- 'rss_before_post' => ' <small>',
720
- 'rss_after_post' => '</small>',
721
- 'rss_before_related' => '<h3>'.__('Related posts:','yarpp').'</h3><ol>',
722
- 'rss_after_related' => '</ol>',
723
- 'rss_no_results' => '<p>'.__('No related posts.','yarpp').'</p>',
724
- 'rss_order' => 'score DESC',
725
- 'title' => '2',
726
- 'body' => '2',
727
- 'categories' => '1',
728
- 'tags' => '2',
729
- 'distags' => '',
730
- 'discats' => '',
731
- 'past_only' => false,
732
- 'show_excerpt' => false,
733
- 'recent_only' => false,
734
- 'use_template' => false,
735
- 'rss_show_excerpt' => false,
736
- 'rss_use_template' => false,
737
- 'show_pass_post' => false,
738
- 'cross_relate' => false,
739
- 'auto_display' => true,
740
- 'rss_display' => false,
741
  'rss_excerpt_display' => true,
742
- 'promote_yarpp' => false,
743
- 'rss_promote_yarpp' => false
744
- );
745
-
746
  $yarpp_options = array();
747
- foreach ($yarpp_3_3_options as $key => $default) {
748
- $value = get_option("yarpp_$key", null);
749
- if (is_null($value)) continue;
 
 
750
 
751
- if (is_bool($default)) {
752
- $yarpp_options[$key] = (boolean) $value;
753
  continue;
754
  }
755
 
756
  // value options used to be stored with a bajillion slashes...
757
- $value = stripslashes(stripslashes($value));
758
  // value options used to be stored with a blank space at the end... don't ask.
759
- $value = rtrim($value, ' ');
760
-
761
- if (is_int($default)) {
762
- $yarpp_options[$key] = absint($value);
763
- } else {
764
- $yarpp_options[$key] = $value;
765
- }
766
- }
767
-
768
  // add the options directly first, then call set_option which will ensure defaults,
769
  // in case any new options have been added.
770
- update_option('yarpp', $yarpp_options);
771
- $this->set_option($yarpp_options);
772
-
773
- $option_keys = array_keys($yarpp_options);
774
  // append some keys for options which are long deprecated:
775
  $option_keys[] = 'ad_hoc_caching';
776
  $option_keys[] = 'excerpt_len';
777
  $option_keys[] = 'show_score';
778
- if (count($option_keys)) {
779
  // This sanitization is sufficient because $option_keys are hardcoded above.
780
- $in = "('yarpp_".join("', 'yarpp_", $option_keys)."')";
781
- $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name IN {$in}");
782
  }
783
  }
784
-
785
  public function upgrade_3_4b5() {
786
- $options = $this->get_option();
787
  $options['exclude'] = array(
788
  'post_tag' => $options['distags'],
789
- 'category' => $options['discats']
790
  );
791
- unset($options['distags']);
792
- unset($options['discats']);
793
- update_option('yarpp', $options);
794
  }
795
-
796
  public function upgrade_3_4b8() {
797
- $options = $this->get_option();
798
  $options['weight'] = array(
799
  'title' => (int) @$options['title'],
800
  'body' => (int) @$options['body'],
801
  'tax' => array(
802
  'post_tag' => (int) @$options['tags'],
803
  'category' => (int) @$options['categories'],
804
- )
805
  );
806
-
807
- // ensure that we consider something
808
- if ($options['weight']['title'] < 2
809
- && $options['weight']['body'] < 2
810
- && $options['weight']['tax']['post_tag'] < 2
811
- && $options['weight']['tax']['category'] < 2
812
- ) {
813
  $options['weight'] = $this->default_options['weight'];
814
- }
815
-
816
- unset($options['title']);
817
- unset($options['body']);
818
- unset($options['tags']);
819
- unset($options['categories']);
820
 
821
- update_option('yarpp', $options);
 
 
 
 
 
822
  }
823
-
824
  public function upgrade_3_4_4b2() {
825
  $options = $this->get_option();
826
 
827
  // update weight values; split out tax weights into weight[tax] and require_tax
828
- $weight_map = array(2 => 1, 3 => YARPP_EXTRA_WEIGHT);
 
 
 
829
 
830
- if ((int) $options['weight']['title'] == 1) {
831
- unset($options['weight']['title']);
832
- } else {
833
- $options['weight']['title'] = $weight_map[(int) $options['weight']['title']];
834
- }
835
 
836
- if ((int) $options['weight']['body'] == 1) {
837
  unset( $options['weight']['body'] );
838
- } else {
839
- $options['weight']['body'] = $weight_map[(int) $options['weight']['body']];
840
- }
841
-
842
  $options['require_tax'] = array();
843
- foreach ($options['weight']['tax'] as $tax => $value) {
844
- if ($value == 3) $options['require_tax'][$tax] = 1;
845
- if ($value == 4) $options['require_tax'][$tax] = 2;
 
 
 
 
846
 
847
- if ($value > 1) {
848
- $options['weight']['tax'][$tax] = 1;
849
- } else {
850
- unset( $options['weight']['tax'][$tax] );
851
- }
852
  }
853
 
854
  // consolidate excludes, using tt_ids.
855
  $exclude_tt_ids = array();
856
- if (isset($options['exclude']) && is_array($options['exclude'])) {
857
- foreach ($options['exclude'] as $tax => $term_ids) {
858
- if (!empty($term_ids)) {
859
- $lp_tmp = wp_list_pluck(get_terms($tax, array('include' => $term_ids)), 'term_taxonomy_id');
860
- $exclude_tt_ids = array_merge($lp_tmp, $exclude_tt_ids );
861
- }
862
  }
863
  }
864
- $options['exclude'] = join(',', $exclude_tt_ids);
865
 
866
  update_option( 'yarpp', $options );
867
  }
868
-
869
  public function upgrade_3_4_4b3() {
870
  $options = $this->get_option();
871
 
872
- $options['template'] = ($options['use_template']) ? $options['template_file'] : false;
873
- $options['rss_template'] = ($options['rss_use_template']) ? $options['rss_template_file'] : false;
874
 
875
- unset($options['use_template']);
876
- unset($options['template_file']);
877
- unset($options['rss_use_template']);
878
- unset($options['rss_template_file']);
879
 
880
- update_option('yarpp', $options);
881
  }
882
-
883
  public function upgrade_3_4_4b4() {
884
  $options = $this->get_option();
885
 
886
- $options['recent'] = ($options['recent_only']) ? $options['recent_number'].' '.$options['recent_units'] : false;
887
 
888
- unset($options['recent_only']);
889
- unset($options['recent_number']);
890
- unset($options['recent_units']);
891
 
892
- update_option('yarpp', $options);
893
  }
894
-
895
  public function upgrade_3_5_2b2() {
896
  // fixing the effects of a previous bug affecting non-MyISAM users
897
- if (is_null($this->get_option('weight')) || !is_array( $this->get_option('weight'))) {
898
  $weight = $this->default_options['weight'];
899
 
900
  // if we're still not using MyISAM
901
- if ( !$this->get_option(YARPP_DB_Options::YARPP_MYISAM_OVERRIDE) &&
902
- ! $this->db_schema->database_supports_fulltext_indexes()) {
903
- unset($weight['title']);
904
- unset($weight['body']);
905
  }
906
 
907
- $this->set_option(array('weight' => $weight));
908
  }
909
  }
910
 
@@ -912,332 +995,402 @@ class YARPP {
912
  // migrate auto_display setting to auto_display_post_types
913
  $options = $this->get_option();
914
 
915
- $options['auto_display_post_types'] = ($options['auto_display']) ? array('post') : array();
916
 
917
- unset($options['auto_display']);
918
 
919
- update_option('yarpp', $options);
920
  }
921
-
922
  public function upgrade_4_0_1() {
923
- delete_transient('yarpp_version_info');
924
  }
925
 
926
- public function upgrade_4_2(){
927
- $this->load_pro_default_options();
928
- $new = array_merge($this->pro_default_options,$this->yarppPro);
929
- update_option('yarpp_pro', $new);
930
- }
931
-
932
- /*
933
  * UTILITIES
934
  */
935
  private $current_post;
936
  private $current_query;
937
  private $current_pagenow;
938
- // so we can return to normal later
939
  public function save_post_context() {
940
  global $wp_query, $pagenow, $post;
941
 
942
- $this->current_query = $wp_query;
943
- $this->current_pagenow = $pagenow;
944
- $this->current_post = $post;
945
  }
946
 
947
  public function restore_post_context() {
948
  global $wp_query, $pagenow, $post;
949
 
950
  $wp_query = $this->current_query;
951
- unset($this->current_query);
952
 
953
  $pagenow = $this->current_pagenow;
954
- unset($this->current_pagenow);
955
 
956
- if (isset($this->current_post)) {
957
  $post = $this->current_post;
958
- setup_postdata($post);
959
- unset($this->current_post);
960
  }
961
  }
962
-
963
  private $post_types = null;
964
 
965
  /**
966
  * Gets all the post types YARPP can add related content to, and the post types YARPP can include in
967
  * "the pool"
 
968
  * @param string $field 'objects', or any property on WP_Post_Type, like 'name'. Defaults to 'name'.
969
  *
970
  * @return array|null
971
  */
972
- public function get_post_types($field = 'name') {
973
- if (is_null($this->post_types)) {
974
- $this->post_types = get_post_types(array(), 'objects');
975
- $this->post_types = array_filter($this->post_types, array($this, 'post_type_filter'));
 
 
 
 
976
  }
977
-
978
- if ($field === 'objects') return $this->post_types;
979
 
980
  return wp_list_pluck( $this->post_types, $field );
981
  }
982
 
983
  /**
984
  * Gets the post types to use for the current YARPP query
 
985
  * @param string|WP_Post $reference_ID
986
- * @param array $args
987
  * @return string[]
988
  */
989
- public function get_query_post_types($reference_ID = null, $args = array()){
990
- $include_post_type = yarpp_get_option( 'include_post_type' );
991
  $include_post_type = wp_parse_list( $include_post_type );
992
- if(isset($args['post_type'])){
993
- $post_types = (array)$args['post_type'];
994
- } else if ( ! $this->get_option('cross_relate') ) {
995
  $current_post_type = get_post_type( $reference_ID );
996
- $post_types = array( $current_post_type );
997
- if ( ! in_array( $current_post_type, $include_post_type) ) {
998
- $post_types = array('');
999
  }
1000
- }else if ( ! empty( $include_post_type ) ) {
1001
  $post_types = $include_post_type;
1002
- }else if ( $this->get_option('cross_relate') ) {
1003
  $post_types = $this->get_post_types();
1004
  } else {
1005
- $post_types = array(get_post_type($reference_ID));
1006
  }
1007
  return apply_filters(
1008
  'yarpp_map_post_types',
1009
  $post_types,
1010
- is_array($args) && isset($args['domain']) ? $args['domain'] : null
1011
  );
1012
  }
1013
 
1014
- private function post_type_filter($post_type) {
1015
  // Remove blacklisted post types.
1016
- if(class_exists( 'bbPress' ) && in_array(
1017
  $post_type->name,
1018
  array(
1019
  'forum', // bbPress forums (ie, group of topics).
1020
- 'reply' // bbPress replies to topics
1021
  )
1022
- )){
1023
  return false;
1024
  }
1025
- if ($post_type->public) return true;
1026
- if (isset($post_type->yarpp_support)) return $post_type->yarpp_support;
 
 
 
 
1027
  return false;
1028
  }
1029
-
1030
  private $taxonomies = null;
1031
- function get_taxonomies($field = false) {
1032
- if (is_null($this->taxonomies)) {
1033
- $this->taxonomies = get_taxonomies(array(), 'objects');
1034
- $this->taxonomies = array_filter($this->taxonomies, array($this, 'taxonomy_filter'));
 
 
 
 
1035
  }
1036
-
1037
- if ($field) return wp_list_pluck($this->taxonomies, $field);
1038
 
1039
  return $this->taxonomies;
1040
  }
1041
-
1042
- private function taxonomy_filter($taxonomy) {
1043
- if (!count(array_intersect($taxonomy->object_type, $this->get_post_types()))) return false;
1044
 
1045
- // if yarpp_support is set, follow that; otherwise include if show_ui is true
1046
- if (isset($taxonomy->yarpp_support)) return $taxonomy->yarpp_support;
 
 
 
 
 
 
 
1047
 
1048
  return $taxonomy->show_ui;
1049
  }
1050
 
1051
- /**
1052
- * Gather optin data.
1053
- * @return array
1054
- */
1055
- public function optin_data() {
 
1056
  global $wpdb;
1057
 
1058
- $comments = wp_count_comments();
1059
- $users = $wpdb->get_var("SELECT COUNT(ID) FROM ".$wpdb->users); //count_users();
1060
- $posts = $wpdb->get_var("SELECT COUNT(ID) FROM ".$wpdb->posts." WHERE post_type = 'post' AND comment_count > 0");
1061
- $settings = $this->get_option();
1062
 
1063
- $collect = array_flip(array(
1064
- 'threshold', 'limit', 'excerpt_length', 'recent', 'rss_limit',
1065
- 'rss_excerpt_length', 'past_only', 'show_excerpt', 'rss_show_excerpt',
1066
- 'template', 'rss_template', 'show_pass_post', 'cross_relate', 'generate_missing_thumbnails', 'include_sticky_posts',
1067
- 'rss_display', 'rss_excerpt_display', 'promote_yarpp', 'rss_promote_yarpp',
1068
- 'myisam_override', 'weight', 'require_tax', 'auto_display_archive', 'exclude',
1069
- 'include_post_type'
1070
- ));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1071
 
1072
  $check_changed = array(
1073
- 'before_title', 'after_title', 'before_post', 'after_post',
1074
- 'after_related', 'no_results', 'order', 'rss_before_title',
1075
- 'rss_after_title', 'rss_before_post', 'rss_after_post', 'rss_after_related',
1076
- 'rss_no_results', 'rss_order', 'exclude', 'thumbnails_heading',
1077
- 'thumbnails_default', 'rss_thumbnails_heading', 'rss_thumbnails_default', 'display_code'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1078
  );
1079
 
1080
  $data = array(
1081
- 'versions' => array(
1082
  'yarpp' => YARPP_VERSION,
1083
- 'wp' => get_bloginfo('version'),
1084
- 'php' => phpversion()
1085
  ),
1086
- 'yarpp' => array(
1087
- 'settings' => array_intersect_key($settings, $collect),
1088
- 'cache_engine' => YARPP_CACHE_TYPE
1089
  ),
1090
  'diagnostics' => array(
1091
- 'myisam_posts' => $this->diagnostic_myisam_posts(),
1092
- 'fulltext_indices' => $this->diagnostic_fulltext_indices(),
1093
- 'hidden_metaboxes' => $this->diagnostic_hidden_metaboxes(),
1094
- 'post_thumbnails' => $this->diagnostic_post_thumbnails(),
1095
- 'happy' => $this->diagnostic_happy(),
1096
- 'using_thumbnails' => $this->diagnostic_using_thumbnails(),
1097
- 'generate_thumbnails' => $this->diagnostic_generate_thumbnails(),
1098
  ),
1099
- 'stats' => array(
1100
- 'counts' => array(),
1101
- 'terms' => array(),
1102
  'comments' => array(
1103
  'moderated' => $comments->moderated,
1104
  'approved' => $comments->approved,
1105
  'total' => $comments->total_comments,
1106
- 'posts' => $posts
1107
  ),
1108
- 'users' => $users,
1109
  ),
1110
- 'locale' => get_bloginfo('language'),
1111
- 'url' => get_bloginfo('url'),
1112
- 'plugins' => array(
1113
- 'active' => implode('|', get_option('active_plugins', array())),
1114
- 'sitewide' => implode('|', array_keys(get_site_option('active_sitewide_plugins', array())))
1115
  ),
1116
- 'pools' => $settings['pools']
1117
  );
1118
 
1119
- $data['yarpp']['settings']['auto_display_post_types'] = implode('|',$settings['auto_display_post_types']);
1120
-
1121
  $changed = array();
1122
- foreach ($check_changed as $key) {
1123
- if ($this->default_options[$key] !== $settings[$key]) $changed[] = $key;
 
 
1124
  }
1125
 
1126
- foreach (array('before_related','rss_before_related') as $key) {
1127
- if ($settings[$key] !== '<p>'.__('Related posts:','yarpp').'</p><ol>'
1128
- && $settings[$key] !== $this->default_options[$key]
1129
- ) {
1130
  $changed[] = $key;
1131
- }
 
 
 
 
 
 
1132
  }
1133
 
1134
- $data['yarpp']['changed_settings'] = implode('|', $changed);
1135
-
1136
- if (method_exists($this->cache, 'cache_status')) $data['yarpp']['cache_status'] = $this->cache->cache_status();
1137
 
1138
- if (method_exists($this->cache, 'stats')) {
1139
- $stats = $this->cache->stats();
1140
- $flattened = array();
 
 
1141
 
1142
- foreach ($stats as $key => $value) $flattened[] = "$key:$value";
1143
- $data['yarpp']['stats'] = implode('|', $flattened);
1144
  }
1145
-
1146
- if (method_exists($wpdb, 'db_version')) {
1147
- $data['versions']['mysql'] = preg_replace('/[^0-9.].*/', '', $wpdb->db_version());
1148
- }
1149
 
1150
  $counts = array();
1151
- foreach (get_post_types(array('public' => true)) as $post_type) {
1152
- $counts[$post_type] = wp_count_posts($post_type);
1153
  }
1154
 
1155
- $data['stats']['counts'] = wp_list_pluck($counts, 'publish');
1156
 
1157
- foreach (get_taxonomies(array('public' => true)) as $taxonomy) {
1158
- $data['stats']['terms'][$taxonomy] = wp_count_terms($taxonomy);
1159
  }
1160
-
1161
- if (is_multisite()) {
1162
  $data['multisite'] = array(
1163
  'url' => network_site_url(),
1164
  'users' => get_user_count(),
1165
- 'sites' => get_blog_count()
1166
  );
1167
  }
1168
 
1169
  return $data;
1170
  }
1171
 
1172
- public function pretty_echo($data) {
1173
- echo "<pre>";
1174
- $formatted = print_r($data, true);
1175
- $formatted = str_replace(array('Array', '(', ')', "\n "), array('', '', '', "\n"), $formatted);
1176
- echo preg_replace("/\n\s*\n/u", "\n", $formatted);
1177
- echo "</pre>";
1178
  }
1179
-
1180
- /*
1181
  * CORE LOOKUP + DISPLAY FUNCTIONS
1182
  */
1183
- protected function display_basic(){
1184
- /* if it's not an auto-display post type, return */
1185
- if (!in_array(get_post_type(), $this->get_option('auto_display_post_types'))) return null;
1186
-
1187
- if (!is_singular() && !($this->get_option('auto_display_archive') && (is_archive() || is_home()))) {
1188
- return null;
1189
- }
1190
- // If we're only viewing a single post with page breaks, only show YARPP its the last page.
1191
- global $page, $pages;
1192
- if(is_singular() && is_int($page) && is_array($pages) && $page < count($pages)){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1193
  return null;
1194
- }
1195
-
1196
- return $this->display_related(
1197
- null,
1198
- array(
1199
- 'domain' => 'website'
1200
- ),
1201
- false
1202
- );
1203
- }
1204
-
1205
- public function display_pro($domain) {
1206
- if ((is_archive() || is_home() || $domain !== 'website')) return null;
1207
- if (!in_array(get_post_type(), $this->yarppPro['auto_display_post_types'])) return null;
1208
- if (!(isset($this->yarppPro['active']) && $this->yarppPro['active'])) return null;
1209
- if (!(isset($this->yarppPro['aid']) && isset($this->yarppPro['v'])) ||
1210
- !($this->yarppPro['aid'] && $this->yarppPro['v'])) return null;
1211
-
1212
- $output = null;
1213
- $aid = $this->yarppPro['aid'];
1214
- $v = $this->yarppPro['v'];
1215
- $dpid = (isset($this->yarppPro['dpid'])) ? $this->yarppPro['dpid'] : null;
1216
- $ru = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
1217
- $ssp = ($dpid) ? '_ssp' : null;
1218
-
1219
- ob_start();
1220
- include(YARPP_DIR.'/includes/phtmls/yarpp_pro_tag'.$ssp.'.phtml');
1221
- $output .= ob_get_contents();
1222
- ob_end_clean();
1223
-
1224
- return $output;
1225
- }
1226
-
1227
- /**
1228
- * Display related posts
1229
  * @since 2.1 The domain global refers to {website, widget, rss, metabox}
1230
  * @since 3.0 New query-based approach: EXTREMELY HACKY!
1231
  *
1232
  * @param integer $reference_ID
1233
- * @param array $args
1234
- * @param bool $echo
1235
- * @return string
1236
  */
1237
- public function display_related($reference_ID = null, $args = array(), $echo = true) {
1238
  // Avoid infinite recursion here.
1239
- if ( $this->do_not_query_for_related()) return false;
1240
- wp_register_style('yarppRelatedCss', plugins_url('/style/related.css', YARPP_MAIN_FILE ), array(), YARPP_VERSION);
 
 
1241
  /**
1242
  * Filter to allow dequeing of related.css.
1243
  *
@@ -1247,401 +1400,438 @@ class YARPP {
1247
  if ( true === $enqueue_related_style ) {
1248
  wp_enqueue_style( 'yarppRelatedCss' );
1249
  }
1250
- $output = null;
1251
-
1252
- if (is_numeric($reference_ID)) {
1253
- $reference_ID = (int) $reference_ID;
1254
- } else {
1255
- $reference_ID = get_the_ID();
1256
- }
1257
-
1258
- /**
1259
- * @since 3.5.3 don't compute on revisions.
1260
- */
1261
- if ($the_post = wp_is_post_revision($reference_ID)) $reference_ID = $the_post;
1262
-
1263
- $this->setup_active_cache($args);
1264
-
1265
- $options = array(
1266
- 'domain',
1267
- 'limit',
1268
- 'template',
1269
- 'order',
1270
- 'promote_yarpp',
1271
- 'optin'
1272
- );
1273
-
1274
- extract($this->parse_args($args, $options));
1275
-
1276
- $cache_status = $this->active_cache->enforce($reference_ID, false, $args);
1277
- if ($cache_status === YARPP_DONT_RUN){
1278
- return;
1279
- }
1280
- if ($cache_status !== YARPP_NO_RELATED) $this->active_cache->begin_yarpp_time($reference_ID, $args);
1281
-
1282
- $this->save_post_context();
1283
-
1284
- global $wp_query; $wp_query = new WP_Query();
1285
-
1286
- if ($cache_status !== YARPP_NO_RELATED) {
1287
- $orders = explode(' ', $order);
1288
- $wp_query->query(
1289
- array(
1290
- 'p' => $reference_ID,
1291
- 'orderby' => $orders[0],
1292
- 'order' => $orders[1],
1293
- 'showposts' => $limit,
1294
- 'post_type' => $this->get_query_post_types($reference_ID, $args)
1295
- )
1296
- );
1297
- }
1298
-
1299
- $this->prep_query($this->current_query->is_feed);
1300
-
1301
- $wp_query->posts = apply_filters('yarpp_results', $wp_query->posts, array(
1302
- 'function' => 'display_related',
1303
- 'args' => $args,
1304
- 'related_ID' => $reference_ID)
1305
- );
1306
-
1307
- $related_query = $wp_query; // backwards compatibility
1308
- $related_count = $related_query->post_count;
1309
-
1310
- // CSS class "yarpp-related" exists for backwards compatibility in-case older custom themes are dependent on it
1311
- $output .= "<div class='yarpp yarpp-related";
1312
-
1313
- // Add CSS class to identify domain
1314
- if (isset($domain) && $domain) {
1315
- $output .= " yarpp-related-{$domain}";
1316
- }
1317
-
1318
- // Add CSS class to identify no results
1319
- if ($related_count < 1) {
1320
- $output .= " yarpp-related-none";
1321
- }
1322
-
1323
- // Add CSS class to identify template
1324
- if (isset($template) && $template) {
 
 
 
 
 
 
 
 
 
1325
  // Normalize "thumbnail" and "thumbnails" to reference the same inbuilt template
1326
- if ($template === "thumbnail") {
1327
- $template = "thumbnails";
1328
- }
1329
  // Sanitize template name; remove file extension if exists
1330
- if (strpos($template, '.php')) {
1331
- $template_css_class_suffix = preg_replace('/'. preg_quote('.php', '/') . '$/', '', $template);
1332
- } else {
1333
- $template_css_class_suffix = $template;
1334
- }
1335
- $output .= " yarpp-template-$template_css_class_suffix";
1336
- } else {
1337
  // fallback to default template ("list")
1338
- $output .= " yarpp-template-list";
1339
- }
1340
 
1341
- $output .= "'>\n";
1342
 
1343
- // Be careful to avoid infinite recursion, because those templates might show each related posts' body or
1344
  // excerpt, which would trigger finding its related posts, which would show its related posts body or excerpt...
1345
- $this->rendering_related_content = true;
1346
 
1347
  // avoid any monkeying around where someone could trya custom template like a template name like
1348
  // "yarpp-template-;../../wp-config.php". YARPP custom templates are only supported in the theme's root folder.
1349
- $template = str_replace('/', '', $template);
1350
- if ($domain === 'metabox') {
1351
- include(YARPP_DIR.'/includes/template_metabox.php');
1352
- } else if ((bool) $template && $template === 'thumbnails') {
1353
- include(YARPP_DIR.'/includes/template_thumbnails.php');
1354
- } else if ((bool) $template && $template === 'list') {
1355
- include(YARPP_DIR.'/includes/template_builtin.php');
1356
- } else if ((bool) $template) {
1357
- $named_properly = strpos($template,'yarpp-template-') === 0;
1358
- $template_exists = file_exists(STYLESHEETPATH.'/'.$template);
1359
- if($named_properly && $template_exists){
1360
- global $post;
1361
- ob_start();
1362
- include(STYLESHEETPATH.'/'.$template);
1363
- $output .= ob_get_contents();
1364
- ob_end_clean();
1365
- } else {
1366
- error_log('YARPP Plugin: Could not load template "' . $template .'". ' . ($named_properly ? 'It is named properly.' : 'It is NOT named properly') . ' ' . ($template_exists ? 'It exists' : 'It does NOT exist') . '. Falling back to default template.');
1367
- include(YARPP_DIR.'/includes/template_builtin.php');
1368
- }
1369
-
1370
- } else if ($domain === 'widget') {
1371
- include(YARPP_DIR.'/includes/template_widget.php');
1372
- } else {
1373
- include(YARPP_DIR.'/includes/template_builtin.php');
1374
- }
1375
- $this->rendering_related_content = false;
1376
- $output = trim($output)."\n";
1377
-
1378
- if ($cache_status === YARPP_NO_RELATED) {
1379
- // Uh, do nothing. Stay very still.
1380
- } else {
1381
- $this->active_cache->end_yarpp_time();
1382
- }
1383
-
1384
- unset($related_query);
1385
- $this->restore_post_context();
1386
-
1387
- if ($related_count > 0 && $promote_yarpp && $domain != 'metabox') {
 
1388
  $output .=
1389
- '<p>'.
1390
- sprintf(
1391
- __(
1392
- "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.",
1393
- 'yarpp'
1394
- ),
1395
- 'https://yarpp.com'
1396
- ).
1397
- "</p>\n";
1398
- }
1399
-
1400
- $output .= "</div>\n";
1401
-
1402
- if ($echo) echo $output;
 
 
1403
  return $output;
1404
  }
1405
-
1406
- /*
1407
- * @param (int) $reference_ID
1408
- * @param (array) $args
1409
  */
1410
- public function get_related($reference_ID = null, $args = array()) {
1411
  // Avoid infinite recursion here.
1412
- if ( $this->do_not_query_for_related()) return false;
1413
-
 
1414
 
1415
- if (is_numeric($reference_ID)) {
1416
  $reference_ID = (int) $reference_ID;
1417
- } else {
1418
  $reference_ID = get_the_ID();
1419
- }
1420
 
1421
- /**
1422
  * @since 3.5.3: don't compute on revisions.
1423
- */
1424
- if ($the_post = wp_is_post_revision($reference_ID)) $reference_ID = $the_post;
1425
-
1426
- $this->setup_active_cache($args);
1427
 
1428
- $options = array('limit', 'order');
1429
- extract($this->parse_args($args, $options));
 
 
 
 
 
 
 
1430
 
1431
- $cache_status = $this->active_cache->enforce($reference_ID, false, $args);
1432
- if ( in_array($cache_status, array(YARPP_DONT_RUN, YARPP_NO_RELATED), true)) return array();
1433
-
1434
  /* Get ready for YARPP TIME! */
1435
- $this->active_cache->begin_yarpp_time($reference_ID, $args);
1436
-
1437
  $related_query = new WP_Query();
1438
- $orders = explode(' ',$order);
1439
- $related_query->query(array(
1440
- 'p' => $reference_ID,
1441
- 'orderby' => $orders[0],
1442
- 'order' => $orders[1],
1443
- 'showposts' => $limit,
1444
- 'post_type' => $this->get_query_post_types($reference_ID, $args)
1445
- ));
1446
-
 
 
1447
  $related_query->posts = apply_filters(
1448
- 'yarpp_results',
1449
- $related_query->posts, array(
1450
-
1451
- 'function' => 'get_related',
1452
- 'args' => $args,
1453
- 'related_ID' => $reference_ID
1454
- )
1455
- );
1456
-
1457
  $this->active_cache->end_yarpp_time();
1458
  return $related_query->posts;
1459
  }
1460
-
1461
- /*
1462
- * @param (int) $reference_ID
1463
- * @param (array) $args
1464
  */
1465
- public function related_exist($reference_ID = null, $args = array()) {
1466
  // Avoid infinite recursion here.
1467
- if ($this->do_not_query_for_related()) return false;
1468
-
1469
- if (is_numeric($reference_ID)) {
 
 
1470
  $reference_ID = (int) $reference_ID;
1471
- } else {
1472
  $reference_ID = get_the_ID();
1473
- }
1474
 
1475
  /** @since 3.5.3: don't compute on revisions */
1476
- if ($the_post = wp_is_post_revision($reference_ID)) $reference_ID = $the_post;
1477
-
1478
- $this->setup_active_cache($args);
1479
-
1480
- $cache_status = $this->active_cache->enforce($reference_ID, false, $args);
1481
 
1482
- if (in_array($cache_status, array(YARPP_DONT_RUN, YARPP_NO_RELATED), true)) return false;
1483
 
 
 
 
1484
 
1485
- /* Get ready for YARPP TIME! */
1486
- $this->active_cache->begin_yarpp_time($reference_ID, $args);
1487
  $related_query = new WP_Query();
1488
- $related_query->query(array(
1489
- 'p' => $reference_ID,
1490
- 'showposts' => 1,
1491
- 'post_type' => $this->get_query_post_types($reference_ID, $args)
1492
- ));
1493
-
 
 
1494
  $related_query->posts = apply_filters(
1495
- 'yarpp_results',
1496
- $related_query->posts,
1497
- array(
1498
- 'function' => 'related_exist',
1499
- 'args' => $args,
1500
- 'related_ID' => $reference_ID
1501
- )
1502
- );
1503
-
1504
  $return = $related_query->have_posts();
1505
- unset($related_query);
1506
 
1507
  $this->active_cache->end_yarpp_time();
1508
  return $return;
1509
  }
1510
-
1511
  /**
1512
  * @param array $args
1513
- * @param bool $echo
1514
- * @return string
1515
  */
1516
- public function display_demo_related($args = array(), $echo = true) {
1517
- // If YARPP cache is already finding the current post's content, don't ask it to do it again.
1518
  // Avoid infinite recursion here.
1519
- if ($this->cache_bypass->demo_time) return false;
1520
-
 
 
1521
  $options = array(
1522
- 'domain',
1523
- 'limit',
1524
- 'template',
1525
- 'order',
1526
- 'promote_yarpp'
1527
- );
1528
- extract($this->parse_args($args, $options));
1529
-
1530
- $this->cache_bypass->begin_demo_time($limit);
1531
-
1532
  $output = "<div class='";
1533
- if ($domain === 'website') {
1534
- $output .= "yarpp-related";
1535
- } else {
1536
  $output .= "yarpp-related yarpp-related-{$domain}";
1537
- }
1538
  $output .= "'>\n";
1539
 
1540
- global $wp_query; $wp_query = new WP_Query();
 
 
 
1541
 
1542
- $wp_query->query('');
1543
-
1544
- $this->prep_query($domain === 'rss');
1545
  $related_query = $wp_query; // backwards compatibility
1546
-
1547
- if ((bool) $template && $template === 'thumbnails') {
1548
- include(YARPP_DIR.'/includes/template_thumbnails.php');
1549
- } else if ((bool) $template && file_exists(STYLESHEETPATH.'/'.$template)) {
1550
  ob_start();
1551
- include(STYLESHEETPATH.'/'.$template);
1552
  $output .= ob_get_contents();
1553
  ob_end_clean();
1554
  } else {
1555
- include(YARPP_DIR.'/includes/template_builtin.php');
1556
  }
1557
- $output = trim($output)."\n";
1558
-
1559
  $this->cache_bypass->end_demo_time();
1560
-
1561
- if ($promote_yarpp) {
1562
  $output .=
1563
- '<p>'.
1564
- sprintf(
1565
- __(
1566
- "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.",
1567
- 'yarpp'
1568
- ),
1569
- 'https://yarpp.com'
1570
- ).
1571
- "</p>\n";
1572
- }
1573
- $output .= "</div>";
1574
-
1575
- if ($echo) echo $output;
 
 
1576
  return $output;
1577
  }
1578
-
1579
- public function parse_args($args, $options) {
1580
  $options_with_rss_variants = array(
1581
  'limit',
1582
- 'template',
1583
- 'excerpt_length',
1584
- 'before_title',
1585
  'after_title',
1586
- 'before_post',
1587
- 'after_post',
1588
- 'before_related',
1589
  'after_related',
1590
- 'no_results',
1591
- 'order',
1592
- 'promote_yarpp',
1593
  'thumbnails_heading',
1594
- 'thumbnails_default'
1595
- );
1596
 
1597
- if (!isset($args['domain'])) $args['domain'] = 'website';
 
 
1598
 
1599
  $r = array();
1600
- foreach ($options as $option) {
1601
- if ($args['domain'] === 'rss'
1602
- && in_array($option, $options_with_rss_variants)
1603
- ) {
1604
  $default = $this->get_option( 'rss_' . $option );
1605
- } else {
1606
  $default = $this->get_option( $option );
1607
- }
1608
-
1609
- if (isset($args[$option]) && $args[$option] !== $default) {
1610
- $r[$option] = $args[$option];
1611
  } else {
1612
- $r[$option] = $default;
 
 
 
 
1613
  }
1614
-
1615
- if ($option === 'weight' && !isset($r[$option]['tax'])) {
1616
- $r[$option]['tax'] = array();
1617
- }
1618
  }
1619
  return $r;
1620
  }
1621
-
1622
  private function setup_active_cache( $args ) {
1623
  /* the options which the main sql query cares about: */
1624
  $magic_options = array(
1625
- 'limit',
1626
- 'threshold',
1627
- 'show_pass_post',
1628
- 'past_only',
1629
- 'weight',
1630
- 'exclude',
1631
- 'require_tax',
1632
- 'recent'
1633
- );
1634
 
1635
  $defaults = $this->get_option();
1636
- foreach ($magic_options as $option) {
1637
- if (!isset($args[$option])) continue;
 
 
1638
 
1639
- /*
1640
  * limit is a little different... if it's less than what we cache, let it go.
1641
- */
1642
- if ($option === 'limit' && $args[$option] <= max($defaults['limit'], $defaults['rss_limit'])) continue;
1643
-
1644
- if ($args[$option] !== $defaults[$option]) {
 
 
1645
  $this->active_cache = $this->cache_bypass;
1646
  return;
1647
  }
@@ -1649,20 +1839,40 @@ class YARPP {
1649
 
1650
  $this->active_cache = $this->cache;
1651
  }
1652
-
1653
- private function prep_query($is_feed = false) {
1654
  global $wp_query;
1655
  $wp_query->in_the_loop = true;
1656
- $wp_query->is_feed = $is_feed;
1657
 
1658
- /*
1659
  * Make sure we get the right is_single value (see http://wordpress.org/support/topic/288230)
1660
- */
1661
  $wp_query->is_single = false;
1662
  }
1663
- /*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1664
  * Return true if user disabled the YARPP related post for the current post, false otherwise.
1665
- *
1666
  * @return bool
1667
  */
1668
  public function yarpp_disabled_for_this_post() {
@@ -1672,163 +1882,209 @@ class YARPP {
1672
  return true;
1673
  }
1674
  return false;
1675
- }
1676
- /*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1677
  * DEFAULT CONTENT FILTERS
1678
  */
1679
-
1680
- public function the_content($content) {
1681
  // Avoid infinite recursion.
1682
- if (is_feed() || $this->do_not_query_for_related()) return $content;
1683
- // If YARPP related post is disabled for this post then return original content.
1684
- if ( true === $this->yarpp_disabled_for_this_post() ) {
1685
  return $content;
1686
  }
1687
 
1688
- /* If the content includes <!--noyarpp-->, don't display */
1689
- if (!stristr($content, '<!--noyarpp-->')) {
1690
- $content .= $this->display_basic();
1691
- $content .= $this->display_pro('website');
1692
- }
 
 
1693
  return $content;
1694
  }
1695
 
1696
- public function the_content_feed($content) {
1697
- if (!$this->get_option('rss_display')) return $content;
 
 
1698
 
1699
- /* If the content includes <!--noyarpp-->, don't display */
1700
- if (stristr($content, '<!--noyarpp-->') !== false) return $content;
 
 
1701
 
1702
- return $content.$this->display_related(
1703
- null,
1704
- array(
1705
- 'domain' => 'rss'
1706
- ),
1707
- false
1708
- );
1709
  }
1710
-
1711
- public function the_excerpt_rss($content) {
1712
- if (!$this->get_option('rss_excerpt_display') || !$this->get_option('rss_display')) return $content;
1713
 
1714
- /* If the content includes <!--noyarpp-->, don't display */
1715
- if (stristr($content, '<!--noyarpp-->') !== false) return $content;
 
 
1716
 
 
 
 
 
1717
 
1718
- return $content . $this->clean_pre($this->display_related(null, array('domain' => 'rss'), false));
1719
  }
1720
-
1721
  /*
1722
  * UTILS
1723
  */
1724
 
1725
- /**
1726
  * @since 3.3 Use PHP serialized format instead of JSON.
1727
- */
1728
- public function version_info($enforce_cache = false) {
1729
- if (!$enforce_cache && false !== ($result = $this->get_transient('yarpp_version_info'))) return $result;
 
 
1730
 
1731
  $version = YARPP_VERSION;
1732
- $remote = wp_remote_post("https://yarpp.org/checkversion.php?format=php&version={$version}");
1733
 
1734
- if (is_wp_error($remote) || wp_remote_retrieve_response_code($remote) != 200 || !isset($remote['body']) || !is_array($remote['body'])){
1735
- $this->set_transient('yarpp_version_info', null, 60*60);
1736
  return false;
1737
- }
1738
-
1739
- if ($result = @unserialize($remote['body'])) $this->set_transient('yarpp_version_info', $result, 60*60*24);
 
 
1740
 
1741
  return $result;
1742
  }
1743
 
1744
- /**
1745
  * @since 4.0 Optional data collection (default off)
1746
- */
1747
  public function optin_ping() {
1748
- if ($this->get_transient('yarpp_optin')) return true;
 
 
1749
 
1750
- $remote = wp_remote_post('https://yarpp.org/optin/2/', array('body' => $this->optin_data()));
1751
 
1752
- if (is_wp_error($remote)
1753
- || wp_remote_retrieve_response_code($remote) != 200
1754
- || !isset($remote['body'])
1755
- || $remote['body'] !== 'ok'
1756
- ) {
1757
  /* try again later */
1758
- $this->set_transient('yarpp_optin', null, 60*60);
1759
  return false;
1760
  }
1761
 
1762
- $this->set_transient('yarpp_optin', null, 60*60*24*7);
1763
 
1764
  return true;
1765
  }
1766
 
1767
- /**
1768
  * A version of the transient functions which is unaffected by caching plugin behavior.
1769
  * We want to control the lifetime of data.
1770
- * @param int $transient
1771
- * @return bool
1772
- */
1773
- private function get_transient($transient) {
1774
- $transient_timeout = $transient.'_timeout';
 
1775
 
1776
- if (intval(get_option($transient_timeout)) < time()) {
1777
- delete_option($transient_timeout);
1778
- return false; // timed out
1779
  }
1780
 
1781
- return get_option($transient, true); // still ok
1782
  }
1783
 
1784
- private function set_transient($transient, $data = null, $expiration = 0) {
1785
- $transient_timeout = $transient.'_timeout';
1786
-
1787
- if (get_option($transient_timeout) === false) {
1788
 
1789
- add_option($transient_timeout, time()+$expiration, '', 'no');
1790
- if (!is_null($data)) add_option($transient, $data, '', 'no');
1791
 
1792
- } else {
1793
-
1794
- update_option($transient_timeout, time()+$expiration);
1795
- if (!is_null( $data )) update_option($transient, $data);
 
1796
 
 
 
 
 
1797
  }
1798
 
1799
  $this->kick_other_caches();
1800
  }
1801
-
1802
- private function delete_transient($transient) {
1803
- delete_option($transient);
1804
- delete_option($transient.'_timeout');
1805
  }
1806
 
1807
- /**
1808
  * @since 4.0.4 Helper function to force other caching systems which are too aggressive.
1809
  * <cough>DB Cache Reloaded (Fix)</cough> to flush when YARPP transients are set.
1810
- */
1811
  private function kick_other_caches() {
1812
- if (class_exists('DBCacheReloaded')) {
1813
  global $wp_db_cache_reloaded;
1814
- if (is_object($wp_db_cache_reloaded) && is_a($wp_db_cache_reloaded, 'DBCacheReloaded')) {
1815
  // if DBCR offered a more granualar way of just flushing options, I'd love that.
1816
  $wp_db_cache_reloaded->dbcr_clear();
1817
  }
1818
  }
1819
  }
1820
 
1821
- /**
1822
  * @since 3.5.2 Clean_pre is deprecated in WP 3.4, so implement here.
1823
- */
1824
- function clean_pre($text) {
1825
- $text = str_replace(array('<br />', '<br/>', '<br>'), array('', '', ''), $text);
1826
- $text = str_replace('<p>', "\n", $text);
1827
- $text = str_replace('</p>', '', $text);
1828
  return $text;
1829
  }
1830
 
1831
- /*
1832
  * Gets the list of valid interval units used by YARPP and MySQL interval statements.
1833
  *
1834
  * @return array keys are valid values for recent units, and for MySQL interval
@@ -1836,16 +2092,16 @@ class YARPP {
1836
  */
1837
  public function recent_units() {
1838
  return array(
1839
- 'day' => __('day(s)','yarpp'),
1840
- 'week' => __('week(s)','yarpp'),
1841
- 'month' => __('month(s)','yarpp')
1842
  );
1843
  }
1844
 
1845
  /**
1846
  * Adds YARPP's content to bbPress topics.
1847
  */
1848
- public function add_to_bbpress(){
1849
  echo $this->display_basic();
1850
  }
1851
 
@@ -1858,12 +2114,12 @@ class YARPP {
1858
  * would trigger adding related content to the post's body, which requires discovering its keywords, etc.
1859
  * 2. if YARPP is currently adding related content. Finding related posts at this time can cause infinite recursion
1860
  * because: the template file might show a posts't content or excerpt, which would cause adding related content
1861
- * to that post body or excerpt, which would start adding related content to it too, etc. *
1862
  *
1863
  * @return bool
1864
  */
1865
- protected function do_not_query_for_related(){
1866
  return $this->rendering_related_content ||
1867
- ($this->active_cache instanceof YARPP_Cache && $this->active_cache->discovering_keywords());
1868
  }
1869
  }
5
  */
6
  class YARPP {
7
 
8
+ /**
9
+ * Here's a list of all the options YARPP uses (except version), as well as their default values,
10
+ * sans the yarpp_ prefix, split up into binary options and value options. These arrays are used in updating
11
+ * settings (yarpp_options.php) and other tasks.
12
+ */
13
+ public $default_options = array();
14
+ public $pro_default_options = array();
15
+ public $default_hidden_metaboxes = array();
16
+ public $debug = false;
17
+ public $yarppPro = null;
18
  /**
19
  * @var YARPP_Cache_Bypass
20
  */
21
+ public $cache_bypass;
22
  /**
23
  * @var YARPP_Cache
24
  */
25
+ public $cache;
26
+ public $admin;
27
  /**
28
  * @var YARPP_DB_Schema
29
  */
30
+ public $db_schema;
31
 
32
  /**
33
  * @var YARPP_Cache
34
  */
35
+ private $active_cache;
36
+ private $storage_class;
37
+ private $default_dimensions = array(
38
+ 'width' => 120,
39
+ 'height' => 120,
40
+ 'crop' => false,
41
+ 'size' => '120x120',
42
+ '_default' => true,
43
+ );
44
  /**
45
  * @var bool Set to true while YARPP is rendering related posts (a very bad time to start looking for related
46
  * content, and start infintely recursing !)
47
  */
48
+ private $rendering_related_content;
49
 
50
  public function __construct() {
51
+ $this->is_custom_template = false;
52
  $this->load_default_options();
53
+ $this->yarppPro = $this->get_pro_options();
54
 
55
  /* Loads the plugin's translated strings. */
56
+ load_plugin_textdomain( 'yarpp', false, plugin_basename( YARPP_DIR ) . '/lang' );
57
 
58
  /* Load cache object. */
59
+ $this->storage_class = 'YARPP_Cache_' . ucfirst( YARPP_CACHE_TYPE );
60
+ $this->cache = new $this->storage_class( $this );
61
+ $this->cache_bypass = new YARPP_Cache_Bypass( $this );
62
  $this->db_schema = new YARPP_DB_Schema();
63
  $this->db_options = new YARPP_DB_Options();
64
 
65
+ register_activation_hook( __FILE__, array( $this, 'activate' ) );
66
 
67
+ /**
68
  * @since 3.2 Update cache on delete.
69
+ */
70
+ add_action( 'delete_post', array( $this->cache, 'delete_post' ), 10, 1 );
71
 
72
+ /**
73
+ * @since 3.5.3 Use transition_post_status instead of save_post hook.
74
  * @since 3.2.1 Handle post_status transitions.
75
+ */
76
+ add_action( 'transition_post_status', array( $this->cache, 'transition_post_status' ), 10, 3 );
77
 
78
  /**
79
  * Initializes yarpp rest routes
80
  */
81
+ if ( apply_filters( 'rest_enabled', true ) && class_exists( 'WP_REST_Controller' ) && class_exists( 'WP_REST_Posts_Controller' ) ) {
82
+ include_once YARPP_DIR . '/classes/YARPP_Rest_Api.php';
83
  new YARPP_Rest_Api();
84
  }
85
 
 
86
  /* Automatic display hooks: */
87
  /**
88
  * Allow filtering the priority of YARPP's placement.
89
  */
90
+ $content_priority = apply_filters( 'yarpp_content_priority', 1200 );
91
+ $feed_priority = apply_filters( 'yarpp_feed_priority', 600 );
92
+ $excerpt_rss_priority = apply_filters( 'yarpp_excerpt_rss_priority', 600 );
93
+
94
+ add_filter( 'the_content', array( $this, 'the_content' ), $content_priority );
95
+ add_action( 'bbp_template_after_single_topic', array( $this, 'add_to_bbpress' ) );
96
+ add_filter( 'the_content_feed', array( $this, 'the_content_feed' ), $feed_priority );
97
+ add_filter( 'the_excerpt_rss', array( $this, 'the_excerpt_rss' ), $excerpt_rss_priority );
98
+ add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue_thumbnails_stylesheet' ) );
99
  add_filter( 'is_protected_meta', array( $this, 'is_protected_meta' ), 10, 3 );
100
 
101
+ /**
102
  * If we're using thumbnails, register yarpp-thumbnail size, if theme has not already.
103
  * Note: see FAQ in the readme if you would like to change the YARPP thumbnail size.
104
  * If theme has already yarpp-thumbnail size registered and we also try to register yarpp-thumbnail then it will throw a fatal error. So it is necessary to check if yarpp-thumbnail size is not registered.
105
+ */
106
  global $add_image_size_by_yarpp;
107
+ if ( false === yarpp_get_image_sizes( 'yarpp-thumbnail' ) ) {
108
  $width = 120;
109
  $height = 120;
110
  $crop = true;
114
  $add_image_size_by_yarpp = false;
115
  }
116
 
117
+ if ( isset( $_REQUEST['yarpp_debug'] ) ) {
118
+ $this->debug = true;
119
+ }
120
 
121
+ if ( ! $this->db_options->plugin_version_in_db() ) {
122
+ $this->db_options->add_upgrade_flag();
123
+ }
124
+
125
+ /**
126
  * @since 3.4 Only load UI if we're in the admin.
127
+ */
128
+ if ( is_admin() ) {
129
+ require_once YARPP_DIR . '/classes/YARPP_Admin.php';
130
+ $this->admin = new YARPP_Admin( $this );
131
+ if ( ! defined( 'DOING_AJAX' ) ) {
132
  $this->enforce();
133
  }
134
  }
135
  $shortcode = new YARPP_Shortcode();
136
  $shortcode->register();
137
  }
138
+
139
  /**
140
  * Add yarpp_meta key to protected list.
141
+ *
142
+ * @since 5.19
143
  *
144
  * @param bool $protected Whether the key is considered protected.
145
  * @param string $meta_key Metadata key.
152
  }
153
  return $protected;
154
  }
155
+
156
+ /**
157
  * OPTIONS
158
  */
159
+ private function load_pro_default_options() {
160
+ return array(
161
+ 'active' => '0',
162
+ 'aid' => null,
163
+ 'st' => null,
164
+ 'v' => null,
165
+ 'dpid' => null,
166
+ 'optin' => false,
167
+ 'auto_display_post_types' => array( 'post' ),
168
+ );
169
+ }
 
170
 
171
  private function load_default_options() {
172
  $this->default_options = array(
173
+ 'threshold' => 1,
174
+ 'limit' => 4,
175
+ 'excerpt_length' => 10,
176
+ 'recent' => false,
177
+ 'before_title' => '<li>',
178
+ 'after_title' => '</li>',
179
+ 'before_post' => ' <small>',
180
+ 'after_post' => '</small>',
181
+ 'before_related' => '<h3>' . __( 'Related posts:', 'yarpp' ) . '</h3><ol>',
182
+ 'after_related' => '</ol>',
183
+ 'no_results' => '<p>' . __( 'No related posts.', 'yarpp' ) . '</p>',
184
+ 'order' => 'score DESC',
185
+ 'rss_limit' => 3,
186
+ 'rss_excerpt_length' => 10,
187
+ 'rss_before_title' => '<li>',
188
+ 'rss_after_title' => '</li>',
189
+ 'rss_before_post' => ' <small>',
190
+ 'rss_after_post' => '</small>',
191
+ 'rss_before_related' => '<h3>' . __( 'Related posts:', 'yarpp' ) . '</h3><ol>',
192
+ 'rss_after_related' => '</ol>',
193
+ 'rss_no_results' => '<p>' . __( 'No related posts.', 'yarpp' ) . '</p>',
194
+ 'rss_order' => 'score DESC',
195
+ 'past_only' => false,
196
+ 'show_excerpt' => false,
197
+ 'rss_show_excerpt' => false,
198
+ 'template' => false,
199
+ 'rss_template' => false,
200
+ 'show_pass_post' => false,
201
+ 'cross_relate' => false,
202
+ 'include_sticky_posts' => true,
203
+ 'generate_missing_thumbnails' => false,
204
+ 'rss_display' => false,
205
+ 'rss_excerpt_display' => true,
206
+ 'promote_yarpp' => false,
207
+ 'rss_promote_yarpp' => false,
208
+ 'myisam_override' => false,
209
+ 'exclude' => '',
210
+ 'include_post_type' => get_post_types( array() ),
211
+ 'weight' => array(
212
  'title' => 0,
213
+ 'body' => 0,
214
+ 'tax' => array(
215
  'category' => 1,
216
+ 'post_tag' => 1,
217
+ ),
218
  ),
219
+ 'require_tax' => array(),
220
+ 'optin' => false,
221
+ 'thumbnails_heading' => __( 'Related posts:', 'yarpp' ),
222
+ 'thumbnails_default' => plugins_url( 'images/default.png', dirname( __FILE__ ) ),
223
+ 'rss_thumbnails_heading' => __( 'Related posts:', 'yarpp' ),
224
+ 'rss_thumbnails_default' => plugins_url( 'images/default.png', dirname( __FILE__ ) ),
225
+ 'display_code' => false,
226
+ 'auto_display_archive' => false,
227
+ 'auto_display_post_types' => array( 'post' ),
228
+ 'pools' => array(),
229
+ 'manually_using_thumbnails' => false,
230
+ 'rest_api_display' => true,
231
+ 'thumbnail_size_display' => 0,
232
  'custom_theme_thumbnail_size_display' => 0,
233
+ 'thumbnail_size_feed_display' => 0,
234
+ 'rest_api_client_side_caching' => false,
235
+ 'yarpp_rest_api_cache_time' => 15,
236
  );
237
  }
238
+
239
+ public function set_option( $options, $value = null ) {
240
  $current_options = $this->get_option();
241
+
242
  /* We can call yarpp_set_option(key,value) if we like. */
243
+ if ( ! is_array( $options ) ) {
244
+ if ( isset( $value ) ) {
245
+ $options = array( $options => $value );
246
+ } else {
247
  return false;
248
+ }
249
  }
 
 
 
 
 
 
250
 
251
+ $new_options = array_merge( $current_options, $options );
252
+ $this->db_options->set_yarpp_options( $new_options );
 
253
 
254
+ // new in 3.1: clear cache when updating certain settings.
255
+ $clear_cache_options = array(
256
+ 'show_pass_post' => 1,
257
+ 'recent' => 1,
258
+ 'threshold' => 1,
259
+ 'past_only' => 1,
260
+ 'include_sticky_posts' => 1,
261
+ 'cross_relate' => 1,
262
+ );
263
+
264
+ $relevant_options = array_intersect_key( $options, $clear_cache_options );
265
+ $relevant_current_options = array_intersect_key( $current_options, $clear_cache_options );
266
+ $new_options_which_require_flush = array_diff_assoc( $relevant_options, $relevant_current_options );
267
+
268
+ if ( count( $new_options_which_require_flush )
269
+ || ( $new_options['limit'] > $current_options['limit'] )
270
+ || ( $new_options['weight'] != $current_options['weight'] )
271
+ || ( $new_options['exclude'] != $current_options['exclude'] )
272
+ || ( $new_options['require_tax'] != $current_options['require_tax'] )
273
+ || ( $new_options['include_post_type'] != $current_options['include_post_type'] )
274
+ ) {
275
+ $this->cache->flush();
276
+ }
277
  }
278
 
279
+ /**
280
  * @since 3.4b8 $option can be a path, of the query_str variety, i.e. "option[suboption][subsuboption]"
281
+ */
282
+ public function get_option( $option = null ) {
283
  $options = $this->db_options->get_yarpp_options();
284
 
285
  // ensure defaults if not set:
286
+ $options = array_merge( $this->default_options, $options );
287
+
288
+ if ( is_null( $option ) ) {
289
+ return $options;
290
+ }
291
+
292
+ $optionpath = array();
293
+ $parsed_option = array();
294
+ wp_parse_str( $option, $parsed_option );
295
+ $optionpath = $this->array_flatten( $parsed_option );
296
+
297
  $current = $options;
298
+ foreach ( $optionpath as $optionpart ) {
299
+ if ( ! is_array( $current ) || ! isset( $current[ $optionpart ] ) ) {
300
+ return null;
301
+ }
302
+ $current = $current[ $optionpart ];
303
  }
304
 
305
  return $current;
306
  }
307
 
308
+ private function get_pro_options() {
309
+ $current = get_option( 'yarpp_pro' );
310
+ $defaults = $this->load_pro_default_options();
311
+
312
+ if ( $current ) {
313
+ $out = array_merge( $defaults, $current );
314
+ update_option( 'yarpp_pro', $out );
315
+ } else {
316
+ $out = $defaults;
317
+ add_option( 'yarpp_pro', $out );
318
+ }
319
 
320
+ return $out;
321
+ }
 
 
 
 
 
322
 
323
+ private function array_flatten( $array, $given = array() ) {
324
+ foreach ( $array as $key => $val ) {
 
 
 
325
  $given[] = $key;
326
+ if ( is_array( $val ) ) {
327
+ $given = $this->array_flatten( $val, $given );
328
+ }
329
  }
330
  return $given;
331
  }
334
  * INFRASTRUCTURE
335
  */
336
 
337
+ /**
338
+ * @since 3.5.2 Function to enforce YARPP setup if not ready, activate; else upgrade.
339
+ */
340
+ public function enforce() {
341
+ if ( ! $this->enabled() ) {
342
+ $this->activate(); // activate calls upgrade later, so it's covered.
343
+ } else {
344
+ $this->upgrade();
345
+ }
346
+ if ( $this->get_option( 'optin' ) ) {
347
+ $this->optin_ping();
348
+ }
349
+ }
350
 
351
  public function enabled() {
352
  if ( ! (bool) $this->cache->is_enabled() ) {
355
  return $this->diagnostic_fulltext_indices();
356
  }
357
  }
358
+
359
  public function activate() {
360
+ if ( (bool) $this->cache->is_enabled() === false ) {
361
  $this->cache->setup();
362
  }
363
 
364
  /* If we're not enabled, give up. */
365
+ if ( ! $this->enabled() ) {
366
+ return false;
367
+ }
368
 
369
+ if ( ! $this->db_options->plugin_version_in_db() ) {
370
  $this->db_options->update_plugin_version_in_db();
371
+ $this->version_info( true );
372
  } else {
373
  $this->upgrade();
374
  }
375
+
376
  return true;
377
  }
378
 
379
  /**
380
  * DIAGNOSTICS
381
+ *
382
  * @since 4.0 Moved into separate functions. Note return value types can differ.
383
  * @since 5.2.0 consider using $this->db_schema->posta_table_database_engine() or
384
  * $this->db_schema->database_supports_fulltext_indexes() instead
385
  */
386
  public function diagnostic_myisam_posts() {
387
  $engine = $this->db_schema->posts_table_database_engine();
388
+ switch ( $engine ) {
389
  case 'MyISAM':
390
  return true;
391
  case null:
412
  * @return bool
413
  */
414
  public function enable_fulltext() {
415
+ _deprecated_function( 'YARPP::enable_fulltext', '5.15.0' );
416
+ if ( ! $this->db_supports_fulltext() ) {
417
+ return false;
418
+ }
419
+ if ( ! $this->enable_fulltext_titles() ) {
420
+ return false;
421
+ }
422
+ if ( ! $this->enable_fulltext_contents() ) {
423
+ return false;
424
+ }
425
+ return true;
426
+ }
427
+
428
+ protected function db_supports_fulltext() {
429
  /*
430
+ * If we haven't already re-attempted creating the database indexes and the database doesn't support adding
431
+ * those indexes, disable it.
432
+ */
433
+ if ( ! (bool) $this->get_option( YARPP_DB_Options::YARPP_MYISAM_OVERRIDE ) &&
434
+ ! $this->db_schema->database_supports_fulltext_indexes() ) {
435
  $this->disable_fulltext();
436
  return false;
437
  }
438
  return true;
439
  }
440
+ public function enable_fulltext_titles() {
441
+ if ( ! $this->db_schema->title_column_has_index() ) {
442
  if ( $this->db_schema->add_title_index() ) {
443
  $this->db_options->delete_fulltext_db_error_record();
444
  } else {
450
  return true;
451
  }
452
 
453
+ public function enable_fulltext_contents() {
454
+ if ( ! $this->db_schema->content_column_has_index() ) {
455
+ if ( $this->db_schema->add_content_index() ) {
456
  $this->db_options->delete_fulltext_db_error_record();
457
  } else {
458
  $this->disable_fulltext();
467
  * Stop considering post title and body in relatedness criteria.
468
  */
469
  public function disable_fulltext() {
470
+ if ( $this->db_options->is_fulltext_disabled() ) {
471
+ return;
472
+ }
473
+
474
  /* Remove title and body weights: */
475
+ $weight = $this->get_option( 'weight' );
476
+ unset( $weight['title'] );
477
+ unset( $weight['body'] );
478
+ $this->set_option( array( 'weight' => $weight ) );
479
 
480
  /* cut threshold by half: */
481
+ $threshold = (float) $this->get_option( 'threshold' );
482
+ $this->set_option( array( 'threshold' => round( $threshold / 2 ) ) );
483
  }
484
 
485
  /**
486
  * Returns true if we consider this to be a big database (based on posts records); false otherwise.
487
  * Uses the constants YARPP_BIG_DB
488
+ *
489
  * @return bool
490
  */
491
+ public function diagnostic_big_db() {
492
  global $wpdb;
493
+ if ( ! defined( 'YARPP_BIG_DB' ) ) {
494
+ define( 'YARPP_BIG_DB', 5000 );
495
  }
496
  $sql = 'SELECT count(*) FROM ' . $wpdb->posts;
497
+ // Note: count includes drafts, revisions, etc.
498
+ $posts_count = $wpdb->get_var( $sql );
499
+ return (int) $posts_count > YARPP_BIG_DB;
500
  }
501
 
502
+ /**
503
+ * Try to retrieve fulltext index from database.
504
+ *
505
+ * @return bool
506
+ */
507
  public function diagnostic_fulltext_indices() {
508
  return $this->db_schema->title_column_has_index() && $this->db_schema->content_column_has_index();
509
  }
511
  public function diagnostic_hidden_metaboxes() {
512
  global $wpdb;
513
  $raw = $wpdb->get_var(
514
+ "SELECT meta_value FROM $wpdb->usermeta " .
515
+ "WHERE meta_key = 'metaboxhidden_settings_page_yarpp' " .
516
+ 'ORDER BY length(meta_value) ASC LIMIT 1'
517
+ );
518
 
519
+ if ( ! $raw ) {
520
+ return $this->default_hidden_metaboxes;
521
+ }
522
 
523
+ $list = maybe_unserialize( $raw );
524
+ if ( ! is_array( $list ) ) {
525
+ return $this->default_hidden_metaboxes;
526
+ }
527
 
528
+ return implode( '|', $list );
529
  }
530
+
531
  public function diagnostic_post_thumbnails() {
532
+ return current_theme_supports( 'post-thumbnails', 'post' );
533
  }
534
+
535
  public function diagnostic_custom_templates() {
536
+ return count( $this->admin->get_templates() );
537
  }
538
+
539
  public function diagnostic_happy() {
540
  $stats = $this->cache->stats();
541
 
542
+ if ( ! ( array_sum( $stats ) > 0 ) ) {
543
+ return false;
544
+ }
545
+
546
+ $sum = array_sum( (array) array_map( 'array_product', array_map( null, array_values( $stats ), array_keys( $stats ) ) ) );
547
  $avg = $sum / array_sum( $stats );
548
 
549
+ return ( $this->cache->cache_status() > 0.1 && $avg > 2 );
550
  }
551
+
552
  public function diagnostic_generate_thumbnails() {
553
+ return ( defined( 'YARPP_GENERATE_THUMBNAILS' ) && YARPP_GENERATE_THUMBNAILS ) || (bool) $this->get_option( 'generate_missing_thumbnails' );
554
  }
555
 
556
  public function diagnostic_using_thumbnails() {
557
+ if ( $this->get_option( 'manually_using_thumbnails' ) ) {
558
+ return true;
559
+ }
560
+ if ( $this->get_option( 'template' ) === 'thumbnails' ) {
561
+ return true;
562
+ }
563
+ if ( $this->get_option( 'rss_template' ) === 'thumbnails' && $this->get_option( 'rss_display' ) ) {
564
+ return true;
565
+ }
566
  return false;
567
  }
568
  public function get_thumbnail_option_name() {
571
  }
572
  $chosen_template = yarpp_get_option( 'template' );
573
  // check if they're using a custom template
574
+ if ( 'thumbnails' === $chosen_template ) {
575
  return 'thumbnail_size_display';
576
  }
577
  return 'custom_theme_thumbnail_size_display';
578
  }
579
  public function thumbnail_dimensions() {
580
  global $_wp_additional_image_sizes;
581
+ if ( ! isset( $_wp_additional_image_sizes['yarpp-thumbnail'] ) ) {
582
+ return $this->default_dimensions;
583
+ }
584
 
585
  // get user selected thumbnail size.
586
+ $dimensions = yarpp_get_thumbnail_image_dimensions( $this->get_thumbnail_option_name() );
587
+ if ( empty( $dimensions ) ) {
588
+ $dimensions = $_wp_additional_image_sizes['yarpp-thumbnail'];
589
  $dimensions['size'] = 'yarpp-thumbnail';
590
+ }
591
+
592
  /* Ensure YARPP dimensions format: */
593
  $dimensions['width'] = (int) $dimensions['width'];
594
  $dimensions['height'] = (int) $dimensions['height'];
599
  * @deprecated 5.11.0
600
  * @see \YARPP::maybe_enqueue_thumbnails_stylesheet
601
  */
602
+ public function maybe_enqueue_thumbnails() {
603
+ _deprecated_function( 'YARPP::maybe_enqueue_thumbnails', '5.11.0', 'YARPP::maybe_enqueue_thumbnails_stylesheet' );
604
+ return $this->maybe_enqueue_thumbnails_stylesheet();
605
  }
606
 
607
  public function maybe_enqueue_thumbnails_stylesheet() {
608
+ if ( is_feed() ) {
609
+ return;
610
+ }
611
 
612
+ $auto_display_post_types = $this->get_option( 'auto_display_post_types' );
613
 
614
  /* If it's not an auto-display post type, return. */
615
+ if ( ! in_array( get_post_type(), $auto_display_post_types ) ) {
616
+ return;
617
+ }
618
 
619
+ if ( ! is_singular() && ! ( $this->get_option( 'auto_display_archive' ) && ( is_archive() || is_home() ) ) ) {
620
+ return;
621
+ }
622
 
623
+ if ( $this->get_option( 'template' ) !== 'thumbnails' ) {
624
+ return;
625
+ }
626
 
627
+ $this->enqueue_thumbnails_stylesheet( $this->thumbnail_dimensions() );
628
  }
629
 
630
  /**
632
  * @see YARPP::enqueue_thumbnails_stylesheet()
633
  * @param $dimensions
634
  */
635
+ public function enqueue_thumbnails( $dimensions ) {
636
+ _deprecated_function( 'YARPP::enqueue_thumbnails', '5.11.0', 'YARPP::enqueue_thumbnails_stylesheet' );
637
+ return $this->enqueue_thumbnails_stylesheet( $dimensions );
638
  }
639
 
640
  /**
641
  * @param $dimensions
642
  */
643
  public function enqueue_thumbnails_stylesheet( $dimensions ) {
644
+
645
+ wp_register_style( 'yarpp-thumbnails', plugins_url( '/style/styles_thumbnails.css', YARPP_MAIN_FILE ), array(), YARPP_VERSION );
646
  /**
647
  * Filter to allow dequeing of styles_thumbnails.css.
648
  *
650
  */
651
  $enqueue_yarpp_thumbnails = apply_filters( 'yarpp_enqueue_thumbnails_style', true );
652
  if ( true === $enqueue_yarpp_thumbnails ) {
653
+ $yarpp_custom_css = yarpp_thumbnail_inline_css( $dimensions );
654
  wp_enqueue_style( 'yarpp-thumbnails' );
655
  wp_add_inline_style( 'yarpp-thumbnails', $yarpp_custom_css );
656
+ }
657
  }
658
 
659
+ /**
660
  * Code based on Viper's Regenerate Thumbnails plugin '$dimensions' must be an array with size, crop, height, width attributes.
661
+ */
662
+ public function ensure_resized_post_thumbnail( $post_id, $dimensions ) {
663
 
664
+ $thumbnail_id = get_post_thumbnail_id( $post_id );
665
+ $downsized = image_downsize( $thumbnail_id, $dimensions['size'] );
666
 
667
+ if ( $dimensions['crop'] && $downsized[1] && $downsized[2]
668
+ && ( $downsized[1] != $dimensions['width'] || $downsized[2] != $dimensions['height'] )
669
+ ) {
670
+ /*
671
  * We want to trigger re-computation of the thumbnail here.
672
+ * (only if downsized width and height are specified, for Photon behavior)
673
+ */
674
+ $fullSizePath = get_attached_file( $thumbnail_id );
675
+ if ( $fullSizePath !== false && file_exists( $fullSizePath ) ) {
676
+ require_once ABSPATH . 'wp-admin/includes/image.php';
677
+ $metadata = wp_generate_attachment_metadata( $thumbnail_id, $fullSizePath );
678
+ if ( ! is_wp_error( $metadata ) ) {
679
+ wp_update_attachment_metadata( $thumbnail_id, $metadata );
680
  }
681
  }
682
  }
683
  }
684
+
685
  private $templates = null;
686
  public function get_templates() {
687
+ if ( is_null( $this->templates ) ) {
688
+ $this->templates = glob( STYLESHEETPATH . '/yarpp-template-*.php' );
689
 
690
  // if glob hits an error, it returns false.
691
+ if ( $this->templates === false ) {
692
+ $this->templates = array();
693
+ }
694
 
695
+ // get basenames only.
696
+ $this->templates = (array) array_map( array( $this, 'get_template_data' ), $this->templates );
697
  }
698
  return (array) $this->templates;
699
  }
700
+
701
+ public function get_template_data( $file ) {
702
+ $headers = array(
703
+ 'name' => 'YARPP Template',
704
+ 'description' => 'Description',
705
+ 'author' => 'Author',
706
+ 'uri' => 'Author URI',
707
  );
708
+ $data = get_file_data( $file, $headers );
709
+ $data['file'] = $file;
710
+ $data['basename'] = basename( $file );
711
 
712
+ if ( empty( $data['name'] ) ) {
713
+ $data['name'] = $data['basename'];
714
+ }
715
 
716
+ return $data;
717
  }
718
+
719
+ /**
720
  * UPGRADE ROUTINES
721
  */
722
+
723
  public function upgrade() {
724
  $last_version = $this->db_options->plugin_version_in_db();
725
 
726
+ if ( version_compare( YARPP_VERSION, $last_version ) === 0 ) {
727
+ return;
728
+ }
729
+ if ( $last_version && version_compare( '3.4b2', $last_version ) > 0 ) {
730
+ $this->upgrade_3_4b2();
731
+ }
732
+ if ( $last_version && version_compare( '3.4b5', $last_version ) > 0 ) {
733
+ $this->upgrade_3_4b5();
734
+ }
735
+ if ( $last_version && version_compare( '3.4b8', $last_version ) > 0 ) {
736
+ $this->upgrade_3_4b8();
737
+ }
738
+ if ( $last_version && version_compare( '3.4.4b2', $last_version ) > 0 ) {
739
+ $this->upgrade_3_4_4b2();
740
+ }
741
+ if ( $last_version && version_compare( '3.4.4b3', $last_version ) > 0 ) {
742
+ $this->upgrade_3_4_4b3();
743
+ }
744
+ if ( $last_version && version_compare( '3.4.4b4', $last_version ) > 0 ) {
745
+ $this->upgrade_3_4_4b4();
746
+ }
747
+ if ( $last_version && version_compare( '3.5.2b2', $last_version ) > 0 ) {
748
+ $this->upgrade_3_5_2b2();
749
+ }
750
+ if ( $last_version && version_compare( '3.6b7', $last_version ) > 0 ) {
751
+ $this->upgrade_3_6b7();
752
+ }
753
+ if ( $last_version && version_compare( '4.0.1', $last_version ) > 0 ) {
754
+ $this->upgrade_4_0_1();
755
+ }
756
+
757
+ $this->cache->upgrade( $last_version );
758
  /* flush cache in 3.4.1b5 as 3.4 messed up calculations. */
759
+ if ( $last_version && version_compare( '3.4.1b5', $last_version ) > 0 ) {
760
+ $this->cache->flush();
761
+ }
762
+
763
+ $this->version_info( true );
764
+
765
  $this->db_options->update_plugin_version_in_db();
766
  $this->db_options->add_upgrade_flag();
767
+ $this->delete_transient( 'yarpp_optin' );
768
  }
769
+
770
  public function upgrade_3_4b2() {
771
  global $wpdb;
772
+
773
  $yarpp_3_3_options = array(
774
+ 'threshold' => 4,
775
+ 'limit' => 4,
776
+ 'template_file' => '',
777
+ 'excerpt_length' => 10,
778
+ 'recent_number' => 12,
779
+ 'recent_units' => 'month',
780
+ 'before_title' => '<li>',
781
+ 'after_title' => '</li>',
782
+ 'before_post' => ' <small>',
783
+ 'after_post' => '</small>',
784
+ 'before_related' => '<h3>' . __( 'Related posts:', 'yarpp' ) . '</h3><ol>',
785
+ 'after_related' => '</ol>',
786
+ 'no_results' => '<p>' . __( 'No related posts.', 'yarpp' ) . '</p>',
787
+ 'order' => 'score DESC',
788
+ 'rss_limit' => 3,
789
+ 'rss_template_file' => '',
790
+ 'rss_excerpt_length' => 10,
791
+ 'rss_before_title' => '<li>',
792
+ 'rss_after_title' => '</li>',
793
+ 'rss_before_post' => ' <small>',
794
+ 'rss_after_post' => '</small>',
795
+ 'rss_before_related' => '<h3>' . __( 'Related posts:', 'yarpp' ) . '</h3><ol>',
796
+ 'rss_after_related' => '</ol>',
797
+ 'rss_no_results' => '<p>' . __( 'No related posts.', 'yarpp' ) . '</p>',
798
+ 'rss_order' => 'score DESC',
799
+ 'title' => '2',
800
+ 'body' => '2',
801
+ 'categories' => '1',
802
+ 'tags' => '2',
803
+ 'distags' => '',
804
+ 'discats' => '',
805
+ 'past_only' => false,
806
+ 'show_excerpt' => false,
807
+ 'recent_only' => false,
808
+ 'use_template' => false,
809
+ 'rss_show_excerpt' => false,
810
+ 'rss_use_template' => false,
811
+ 'show_pass_post' => false,
812
+ 'cross_relate' => false,
813
+ 'auto_display' => true,
814
+ 'rss_display' => false,
815
  'rss_excerpt_display' => true,
816
+ 'promote_yarpp' => false,
817
+ 'rss_promote_yarpp' => false,
818
+ );
819
+
820
  $yarpp_options = array();
821
+ foreach ( $yarpp_3_3_options as $key => $default ) {
822
+ $value = get_option( "yarpp_$key", null );
823
+ if ( is_null( $value ) ) {
824
+ continue;
825
+ }
826
 
827
+ if ( is_bool( $default ) ) {
828
+ $yarpp_options[ $key ] = (bool) $value;
829
  continue;
830
  }
831
 
832
  // value options used to be stored with a bajillion slashes...
833
+ $value = stripslashes( stripslashes( $value ) );
834
  // value options used to be stored with a blank space at the end... don't ask.
835
+ $value = rtrim( $value, ' ' );
836
+
837
+ if ( is_int( $default ) ) {
838
+ $yarpp_options[ $key ] = absint( $value );
839
+ } else {
840
+ $yarpp_options[ $key ] = $value;
841
+ }
842
+ }
843
+
844
  // add the options directly first, then call set_option which will ensure defaults,
845
  // in case any new options have been added.
846
+ update_option( 'yarpp', $yarpp_options );
847
+ $this->set_option( $yarpp_options );
848
+
849
+ $option_keys = array_keys( $yarpp_options );
850
  // append some keys for options which are long deprecated:
851
  $option_keys[] = 'ad_hoc_caching';
852
  $option_keys[] = 'excerpt_len';
853
  $option_keys[] = 'show_score';
854
+ if ( count( $option_keys ) ) {
855
  // This sanitization is sufficient because $option_keys are hardcoded above.
856
+ $in = "('yarpp_" . join( "', 'yarpp_", $option_keys ) . "')";
857
+ $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name IN {$in}" );
858
  }
859
  }
860
+
861
  public function upgrade_3_4b5() {
862
+ $options = $this->get_option();
863
  $options['exclude'] = array(
864
  'post_tag' => $options['distags'],
865
+ 'category' => $options['discats'],
866
  );
867
+ unset( $options['distags'] );
868
+ unset( $options['discats'] );
869
+ update_option( 'yarpp', $options );
870
  }
871
+
872
  public function upgrade_3_4b8() {
873
+ $options = $this->get_option();
874
  $options['weight'] = array(
875
  'title' => (int) @$options['title'],
876
  'body' => (int) @$options['body'],
877
  'tax' => array(
878
  'post_tag' => (int) @$options['tags'],
879
  'category' => (int) @$options['categories'],
880
+ ),
881
  );
882
+
883
+ // ensure that we consider something.
884
+ if ( $options['weight']['title'] < 2
885
+ && $options['weight']['body'] < 2
886
+ && $options['weight']['tax']['post_tag'] < 2
887
+ && $options['weight']['tax']['category'] < 2
888
+ ) {
889
  $options['weight'] = $this->default_options['weight'];
890
+ }
 
 
 
 
 
891
 
892
+ unset( $options['title'] );
893
+ unset( $options['body'] );
894
+ unset( $options['tags'] );
895
+ unset( $options['categories'] );
896
+
897
+ update_option( 'yarpp', $options );
898
  }
899
+
900
  public function upgrade_3_4_4b2() {
901
  $options = $this->get_option();
902
 
903
  // update weight values; split out tax weights into weight[tax] and require_tax
904
+ $weight_map = array(
905
+ 2 => 1,
906
+ 3 => YARPP_EXTRA_WEIGHT,
907
+ );
908
 
909
+ if ( (int) $options['weight']['title'] == 1 ) {
910
+ unset( $options['weight']['title'] );
911
+ } else {
912
+ $options['weight']['title'] = $weight_map[ (int) $options['weight']['title'] ];
913
+ }
914
 
915
+ if ( (int) $options['weight']['body'] == 1 ) {
916
  unset( $options['weight']['body'] );
917
+ } else {
918
+ $options['weight']['body'] = $weight_map[ (int) $options['weight']['body'] ];
919
+ }
920
+
921
  $options['require_tax'] = array();
922
+ foreach ( $options['weight']['tax'] as $tax => $value ) {
923
+ if ( $value == 3 ) {
924
+ $options['require_tax'][ $tax ] = 1;
925
+ }
926
+ if ( $value == 4 ) {
927
+ $options['require_tax'][ $tax ] = 2;
928
+ }
929
 
930
+ if ( $value > 1 ) {
931
+ $options['weight']['tax'][ $tax ] = 1;
932
+ } else {
933
+ unset( $options['weight']['tax'][ $tax ] );
934
+ }
935
  }
936
 
937
  // consolidate excludes, using tt_ids.
938
  $exclude_tt_ids = array();
939
+ if ( isset( $options['exclude'] ) && is_array( $options['exclude'] ) ) {
940
+ foreach ( $options['exclude'] as $tax => $term_ids ) {
941
+ if ( ! empty( $term_ids ) ) {
942
+ $lp_tmp = wp_list_pluck( get_terms( $tax, array( 'include' => $term_ids ) ), 'term_taxonomy_id' );
943
+ $exclude_tt_ids = array_merge( $lp_tmp, $exclude_tt_ids );
944
+ }
945
  }
946
  }
947
+ $options['exclude'] = join( ',', $exclude_tt_ids );
948
 
949
  update_option( 'yarpp', $options );
950
  }
951
+
952
  public function upgrade_3_4_4b3() {
953
  $options = $this->get_option();
954
 
955
+ $options['template'] = ( $options['use_template'] ) ? $options['template_file'] : false;
956
+ $options['rss_template'] = ( $options['rss_use_template'] ) ? $options['rss_template_file'] : false;
957
 
958
+ unset( $options['use_template'] );
959
+ unset( $options['template_file'] );
960
+ unset( $options['rss_use_template'] );
961
+ unset( $options['rss_template_file'] );
962
 
963
+ update_option( 'yarpp', $options );
964
  }
965
+
966
  public function upgrade_3_4_4b4() {
967
  $options = $this->get_option();
968
 
969
+ $options['recent'] = ( $options['recent_only'] ) ? $options['recent_number'] . ' ' . $options['recent_units'] : false;
970
 
971
+ unset( $options['recent_only'] );
972
+ unset( $options['recent_number'] );
973
+ unset( $options['recent_units'] );
974
 
975
+ update_option( 'yarpp', $options );
976
  }
977
+
978
  public function upgrade_3_5_2b2() {
979
  // fixing the effects of a previous bug affecting non-MyISAM users
980
+ if ( is_null( $this->get_option( 'weight' ) ) || ! is_array( $this->get_option( 'weight' ) ) ) {
981
  $weight = $this->default_options['weight'];
982
 
983
  // if we're still not using MyISAM
984
+ if ( ! $this->get_option( YARPP_DB_Options::YARPP_MYISAM_OVERRIDE ) &&
985
+ ! $this->db_schema->database_supports_fulltext_indexes() ) {
986
+ unset( $weight['title'] );
987
+ unset( $weight['body'] );
988
  }
989
 
990
+ $this->set_option( array( 'weight' => $weight ) );
991
  }
992
  }
993
 
995
  // migrate auto_display setting to auto_display_post_types
996
  $options = $this->get_option();
997
 
998
+ $options['auto_display_post_types'] = ( $options['auto_display'] ) ? array( 'post' ) : array();
999
 
1000
+ unset( $options['auto_display'] );
1001
 
1002
+ update_option( 'yarpp', $options );
1003
  }
1004
+
1005
  public function upgrade_4_0_1() {
1006
+ delete_transient( 'yarpp_version_info' );
1007
  }
1008
 
1009
+ public function upgrade_4_2() {
1010
+ $this->load_pro_default_options();
1011
+ $new = array_merge( $this->pro_default_options, $this->yarppPro );
1012
+ update_option( 'yarpp_pro', $new );
1013
+ }
1014
+
1015
+ /**
1016
  * UTILITIES
1017
  */
1018
  private $current_post;
1019
  private $current_query;
1020
  private $current_pagenow;
1021
+ // so we can return to normal later.
1022
  public function save_post_context() {
1023
  global $wp_query, $pagenow, $post;
1024
 
1025
+ $this->current_query = $wp_query;
1026
+ $this->current_pagenow = $pagenow;
1027
+ $this->current_post = $post;
1028
  }
1029
 
1030
  public function restore_post_context() {
1031
  global $wp_query, $pagenow, $post;
1032
 
1033
  $wp_query = $this->current_query;
1034
+ unset( $this->current_query );
1035
 
1036
  $pagenow = $this->current_pagenow;
1037
+ unset( $this->current_pagenow );
1038
 
1039
+ if ( isset( $this->current_post ) ) {
1040
  $post = $this->current_post;
1041
+ setup_postdata( $post );
1042
+ unset( $this->current_post );
1043
  }
1044
  }
1045
+
1046
  private $post_types = null;
1047
 
1048
  /**
1049
  * Gets all the post types YARPP can add related content to, and the post types YARPP can include in
1050
  * "the pool"
1051
+ *
1052
  * @param string $field 'objects', or any property on WP_Post_Type, like 'name'. Defaults to 'name'.
1053
  *
1054
  * @return array|null
1055
  */
1056
+ public function get_post_types( $field = 'name' ) {
1057
+ if ( is_null( $this->post_types ) ) {
1058
+ $this->post_types = get_post_types( array(), 'objects' );
1059
+ $this->post_types = array_filter( $this->post_types, array( $this, 'post_type_filter' ) );
1060
+ }
1061
+
1062
+ if ( $field === 'objects' ) {
1063
+ return $this->post_types;
1064
  }
 
 
1065
 
1066
  return wp_list_pluck( $this->post_types, $field );
1067
  }
1068
 
1069
  /**
1070
  * Gets the post types to use for the current YARPP query
1071
+ *
1072
  * @param string|WP_Post $reference_ID
1073
+ * @param array $args
1074
  * @return string[]
1075
  */
1076
+ public function get_query_post_types( $reference_ID = null, $args = array() ) {
1077
+ $include_post_type = yarpp_get_option( 'include_post_type' );
1078
  $include_post_type = wp_parse_list( $include_post_type );
1079
+ if ( isset( $args['post_type'] ) ) {
1080
+ $post_types = (array) $args['post_type'];
1081
+ } elseif ( ! $this->get_option( 'cross_relate' ) ) {
1082
  $current_post_type = get_post_type( $reference_ID );
1083
+ $post_types = array( $current_post_type );
1084
+ if ( ! in_array( $current_post_type, $include_post_type ) ) {
1085
+ $post_types = array( '' );
1086
  }
1087
+ } elseif ( ! empty( $include_post_type ) ) {
1088
  $post_types = $include_post_type;
1089
+ } elseif ( $this->get_option( 'cross_relate' ) ) {
1090
  $post_types = $this->get_post_types();
1091
  } else {
1092
+ $post_types = array( get_post_type( $reference_ID ) );
1093
  }
1094
  return apply_filters(
1095
  'yarpp_map_post_types',
1096
  $post_types,
1097
+ is_array( $args ) && isset( $args['domain'] ) ? $args['domain'] : null
1098
  );
1099
  }
1100
 
1101
+ private function post_type_filter( $post_type ) {
1102
  // Remove blacklisted post types.
1103
+ if ( class_exists( 'bbPress' ) && in_array(
1104
  $post_type->name,
1105
  array(
1106
  'forum', // bbPress forums (ie, group of topics).
1107
+ 'reply', // bbPress replies to topics
1108
  )
1109
+ ) ) {
1110
  return false;
1111
  }
1112
+ if ( $post_type->public ) {
1113
+ return true;
1114
+ }
1115
+ if ( isset( $post_type->yarpp_support ) ) {
1116
+ return $post_type->yarpp_support;
1117
+ }
1118
  return false;
1119
  }
1120
+
1121
  private $taxonomies = null;
1122
+ function get_taxonomies( $field = false ) {
1123
+ if ( is_null( $this->taxonomies ) ) {
1124
+ $this->taxonomies = get_taxonomies( array(), 'objects' );
1125
+ $this->taxonomies = array_filter( $this->taxonomies, array( $this, 'taxonomy_filter' ) );
1126
+ }
1127
+
1128
+ if ( $field ) {
1129
+ return wp_list_pluck( $this->taxonomies, $field );
1130
  }
 
 
1131
 
1132
  return $this->taxonomies;
1133
  }
 
 
 
1134
 
1135
+ private function taxonomy_filter( $taxonomy ) {
1136
+ if ( ! count( array_intersect( $taxonomy->object_type, $this->get_post_types() ) ) ) {
1137
+ return false;
1138
+ }
1139
+
1140
+ // if yarpp_support is set, follow that; otherwise include if show_ui is true.
1141
+ if ( isset( $taxonomy->yarpp_support ) ) {
1142
+ return $taxonomy->yarpp_support;
1143
+ }
1144
 
1145
  return $taxonomy->show_ui;
1146
  }
1147
 
1148
+ /**
1149
+ * Gather optin data.
1150
+ *
1151
+ * @return array
1152
+ */
1153
+ public function optin_data() {
1154
  global $wpdb;
1155
 
1156
+ $comments = wp_count_comments();
1157
+ $users = $wpdb->get_var( 'SELECT COUNT(ID) FROM ' . $wpdb->users ); // count_users();
1158
+ $posts = $wpdb->get_var( 'SELECT COUNT(ID) FROM ' . $wpdb->posts . " WHERE post_type = 'post' AND comment_count > 0" );
1159
+ $settings = $this->get_option();
1160
 
1161
+ $collect = array_flip(
1162
+ array(
1163
+ 'threshold',
1164
+ 'limit',
1165
+ 'excerpt_length',
1166
+ 'recent',
1167
+ 'rss_limit',
1168
+ 'rss_excerpt_length',
1169
+ 'past_only',
1170
+ 'show_excerpt',
1171
+ 'rss_show_excerpt',
1172
+ 'template',
1173
+ 'rss_template',
1174
+ 'show_pass_post',
1175
+ 'cross_relate',
1176
+ 'generate_missing_thumbnails',
1177
+ 'include_sticky_posts',
1178
+ 'rss_display',
1179
+ 'rss_excerpt_display',
1180
+ 'promote_yarpp',
1181
+ 'rss_promote_yarpp',
1182
+ 'myisam_override',
1183
+ 'weight',
1184
+ 'require_tax',
1185
+ 'auto_display_archive',
1186
+ 'exclude',
1187
+ 'include_post_type',
1188
+ )
1189
+ );
1190
 
1191
  $check_changed = array(
1192
+ 'before_title',
1193
+ 'after_title',
1194
+ 'before_post',
1195
+ 'after_post',
1196
+ 'after_related',
1197
+ 'no_results',
1198
+ 'order',
1199
+ 'rss_before_title',
1200
+ 'rss_after_title',
1201
+ 'rss_before_post',
1202
+ 'rss_after_post',
1203
+ 'rss_after_related',
1204
+ 'rss_no_results',
1205
+ 'rss_order',
1206
+ 'exclude',
1207
+ 'thumbnails_heading',
1208
+ 'thumbnails_default',
1209
+ 'rss_thumbnails_heading',
1210
+ 'rss_thumbnails_default',
1211
+ 'display_code',
1212
  );
1213
 
1214
  $data = array(
1215
+ 'versions' => array(
1216
  'yarpp' => YARPP_VERSION,
1217
+ 'wp' => get_bloginfo( 'version' ),
1218
+ 'php' => phpversion(),
1219
  ),
1220
+ 'yarpp' => array(
1221
+ 'settings' => array_intersect_key( $settings, $collect ),
1222
+ 'cache_engine' => YARPP_CACHE_TYPE,
1223
  ),
1224
  'diagnostics' => array(
1225
+ 'myisam_posts' => $this->diagnostic_myisam_posts(),
1226
+ 'fulltext_indices' => $this->diagnostic_fulltext_indices(),
1227
+ 'hidden_metaboxes' => $this->diagnostic_hidden_metaboxes(),
1228
+ 'post_thumbnails' => $this->diagnostic_post_thumbnails(),
1229
+ 'happy' => $this->diagnostic_happy(),
1230
+ 'using_thumbnails' => $this->diagnostic_using_thumbnails(),
1231
+ 'generate_thumbnails' => $this->diagnostic_generate_thumbnails(),
1232
  ),
1233
+ 'stats' => array(
1234
+ 'counts' => array(),
1235
+ 'terms' => array(),
1236
  'comments' => array(
1237
  'moderated' => $comments->moderated,
1238
  'approved' => $comments->approved,
1239
  'total' => $comments->total_comments,
1240
+ 'posts' => $posts,
1241
  ),
1242
+ 'users' => $users,
1243
  ),
1244
+ 'locale' => get_bloginfo( 'language' ),
1245
+ 'url' => get_bloginfo( 'url' ),
1246
+ 'plugins' => array(
1247
+ 'active' => implode( '|', get_option( 'active_plugins', array() ) ),
1248
+ 'sitewide' => implode( '|', array_keys( get_site_option( 'active_sitewide_plugins', array() ) ) ),
1249
  ),
1250
+ 'pools' => $settings['pools'],
1251
  );
1252
 
1253
+ $data['yarpp']['settings']['auto_display_post_types'] = implode( '|', $settings['auto_display_post_types'] );
1254
+
1255
  $changed = array();
1256
+ foreach ( $check_changed as $key ) {
1257
+ if ( $this->default_options[ $key ] !== $settings[ $key ] ) {
1258
+ $changed[] = $key;
1259
+ }
1260
  }
1261
 
1262
+ foreach ( array( 'before_related', 'rss_before_related' ) as $key ) {
1263
+ if ( $settings[ $key ] !== '<p>' . __( 'Related posts:', 'yarpp' ) . '</p><ol>'
1264
+ && $settings[ $key ] !== $this->default_options[ $key ]
1265
+ ) {
1266
  $changed[] = $key;
1267
+ }
1268
+ }
1269
+
1270
+ $data['yarpp']['changed_settings'] = implode( '|', $changed );
1271
+
1272
+ if ( method_exists( $this->cache, 'cache_status' ) ) {
1273
+ $data['yarpp']['cache_status'] = $this->cache->cache_status();
1274
  }
1275
 
1276
+ if ( method_exists( $this->cache, 'stats' ) ) {
1277
+ $stats = $this->cache->stats();
1278
+ $flattened = array();
1279
 
1280
+ foreach ( $stats as $key => $value ) {
1281
+ $flattened[] = "$key:$value";
1282
+ }
1283
+ $data['yarpp']['stats'] = implode( '|', $flattened );
1284
+ }
1285
 
1286
+ if ( method_exists( $wpdb, 'db_version' ) ) {
1287
+ $data['versions']['mysql'] = preg_replace( '/[^0-9.].*/', '', $wpdb->db_version() );
1288
  }
 
 
 
 
1289
 
1290
  $counts = array();
1291
+ foreach ( get_post_types( array( 'public' => true ) ) as $post_type ) {
1292
+ $counts[ $post_type ] = wp_count_posts( $post_type );
1293
  }
1294
 
1295
+ $data['stats']['counts'] = wp_list_pluck( $counts, 'publish' );
1296
 
1297
+ foreach ( get_taxonomies( array( 'public' => true ) ) as $taxonomy ) {
1298
+ $data['stats']['terms'][ $taxonomy ] = wp_count_terms( $taxonomy );
1299
  }
1300
+
1301
+ if ( is_multisite() ) {
1302
  $data['multisite'] = array(
1303
  'url' => network_site_url(),
1304
  'users' => get_user_count(),
1305
+ 'sites' => get_blog_count(),
1306
  );
1307
  }
1308
 
1309
  return $data;
1310
  }
1311
 
1312
+ public function pretty_echo( $data ) {
1313
+ echo '<pre>';
1314
+ $formatted = print_r( $data, true );
1315
+ $formatted = str_replace( array( 'Array', '(', ')', "\n " ), array( '', '', '', "\n" ), $formatted );
1316
+ echo preg_replace( "/\n\s*\n/u", "\n", $formatted );
1317
+ echo '</pre>';
1318
  }
1319
+
1320
+ /**
1321
  * CORE LOOKUP + DISPLAY FUNCTIONS
1322
  */
1323
+ protected function display_basic() {
1324
+ /* if it's not an auto-display post type, return */
1325
+ if ( ! in_array( get_post_type(), $this->get_option( 'auto_display_post_types' ) ) ) {
1326
+ return null;
1327
+ }
1328
+
1329
+ if ( ! is_singular() && ! ( $this->get_option( 'auto_display_archive' ) && ( is_archive() || is_home() ) ) ) {
1330
+ return null;
1331
+ }
1332
+ // If we're only viewing a single post with page breaks, only show YARPP its the last page.
1333
+ global $page, $pages;
1334
+ if ( is_singular() && is_int( $page ) && is_array( $pages ) && $page < count( $pages ) ) {
1335
+ return null;
1336
+ }
1337
+
1338
+ return $this->display_related(
1339
+ null,
1340
+ array(
1341
+ 'domain' => 'website',
1342
+ ),
1343
+ false
1344
+ );
1345
+ }
1346
+
1347
+ public function display_pro( $domain ) {
1348
+ if ( ( is_archive() || is_home() || $domain !== 'website' ) ) {
1349
  return null;
1350
+ }
1351
+ if ( ! in_array( get_post_type(), $this->yarppPro['auto_display_post_types'] ) ) {
1352
+ return null;
1353
+ }
1354
+ if ( ! ( isset( $this->yarppPro['active'] ) && $this->yarppPro['active'] ) ) {
1355
+ return null;
1356
+ }
1357
+ if ( ! ( isset( $this->yarppPro['aid'] ) && isset( $this->yarppPro['v'] ) ) ||
1358
+ ! ( $this->yarppPro['aid'] && $this->yarppPro['v'] ) ) {
1359
+ return null;
1360
+ }
1361
+
1362
+ $output = null;
1363
+ $aid = $this->yarppPro['aid'];
1364
+ $v = $this->yarppPro['v'];
1365
+ $dpid = ( isset( $this->yarppPro['dpid'] ) ) ? $this->yarppPro['dpid'] : null;
1366
+ $ru = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1367
+ $ssp = ( $dpid ) ? '_ssp' : null;
1368
+
1369
+ ob_start();
1370
+ include YARPP_DIR . '/includes/phtmls/yarpp_pro_tag' . $ssp . '.phtml';
1371
+ $output .= ob_get_contents();
1372
+ ob_end_clean();
1373
+
1374
+ return $output;
1375
+ }
1376
+
1377
+ /**
1378
+ * Display related posts
1379
+ *
 
 
 
 
 
1380
  * @since 2.1 The domain global refers to {website, widget, rss, metabox}
1381
  * @since 3.0 New query-based approach: EXTREMELY HACKY!
1382
  *
1383
  * @param integer $reference_ID
1384
+ * @param array $args see readme.txt's installation tab's "YARPP functions()" section
1385
+ * @param bool $echo
1386
+ * @return string
1387
  */
1388
+ public function display_related( $reference_ID = null, $args = array(), $echo = true ) {
1389
  // Avoid infinite recursion here.
1390
+ if ( $this->do_not_query_for_related() ) {
1391
+ return false;
1392
+ }
1393
+ wp_register_style( 'yarppRelatedCss', plugins_url( '/style/related.css', YARPP_MAIN_FILE ), array(), YARPP_VERSION );
1394
  /**
1395
  * Filter to allow dequeing of related.css.
1396
  *
1400
  if ( true === $enqueue_related_style ) {
1401
  wp_enqueue_style( 'yarppRelatedCss' );
1402
  }
1403
+ $output = null;
1404
+
1405
+ if ( is_numeric( $reference_ID ) ) {
1406
+ $reference_ID = (int) $reference_ID;
1407
+ } else {
1408
+ $reference_ID = get_the_ID();
1409
+ }
1410
+
1411
+ /**
1412
+ * @since 3.5.3 don't compute on revisions.
1413
+ */
1414
+ if ( $the_post = wp_is_post_revision( $reference_ID ) ) {
1415
+ $reference_ID = $the_post;
1416
+ }
1417
+
1418
+ $this->setup_active_cache( $args );
1419
+
1420
+ $options = array(
1421
+ 'domain',
1422
+ 'limit',
1423
+ 'template',
1424
+ 'order',
1425
+ 'promote_yarpp',
1426
+ 'optin',
1427
+ );
1428
+
1429
+ extract( $this->parse_args( $args, $options ) );
1430
+
1431
+ $cache_status = $this->active_cache->enforce( $reference_ID, false, $args );
1432
+ if ( $cache_status === YARPP_DONT_RUN ) {
1433
+ return;
1434
+ }
1435
+ if ( $cache_status !== YARPP_NO_RELATED ) {
1436
+ $this->active_cache->begin_yarpp_time( $reference_ID, $args );
1437
+ }
1438
+
1439
+ $this->save_post_context();
1440
+
1441
+ global $wp_query;
1442
+ $wp_query = new WP_Query();
1443
+
1444
+ if ( $cache_status !== YARPP_NO_RELATED ) {
1445
+ $orders = explode( ' ', $order );
1446
+ $wp_query->query(
1447
+ array(
1448
+ 'p' => $reference_ID,
1449
+ 'orderby' => $orders[0],
1450
+ 'order' => $orders[1],
1451
+ 'showposts' => $limit,
1452
+ 'post_type' => $this->get_query_post_types( $reference_ID, $args ),
1453
+ )
1454
+ );
1455
+ }
1456
+
1457
+ $this->prep_query( $this->current_query->is_feed );
1458
+
1459
+ $wp_query->posts = apply_filters(
1460
+ 'yarpp_results',
1461
+ $wp_query->posts,
1462
+ array(
1463
+ 'function' => 'display_related',
1464
+ 'args' => $args,
1465
+ 'related_ID' => $reference_ID,
1466
+ )
1467
+ );
1468
+
1469
+ $related_query = $wp_query; // backwards compatibility
1470
+ $related_count = $related_query->post_count;
1471
+
1472
+ // CSS class "yarpp-related" exists for backwards compatibility in-case older custom themes are dependent on it.
1473
+ $output .= "<div class='yarpp yarpp-related";
1474
+
1475
+ // Add CSS class to identify domain.
1476
+ if ( isset( $domain ) && $domain ) {
1477
+ $output .= " yarpp-related-{$domain}";
1478
+ }
1479
+
1480
+ // Add CSS class to identify no results.
1481
+ if ( $related_count < 1 ) {
1482
+ $output .= ' yarpp-related-none';
1483
+ }
1484
+
1485
+ // Add CSS class to identify template.
1486
+ if ( isset( $template ) && $template ) {
1487
  // Normalize "thumbnail" and "thumbnails" to reference the same inbuilt template
1488
+ if ( $template === 'thumbnail' ) {
1489
+ $template = 'thumbnails';
1490
+ }
1491
  // Sanitize template name; remove file extension if exists
1492
+ if ( strpos( $template, '.php' ) ) {
1493
+ $template_css_class_suffix = preg_replace( '/' . preg_quote( '.php', '/' ) . '$/', '', $template );
1494
+ } else {
1495
+ $template_css_class_suffix = $template;
1496
+ }
1497
+ $output .= " yarpp-template-$template_css_class_suffix";
1498
+ } else {
1499
  // fallback to default template ("list")
1500
+ $output .= ' yarpp-template-list';
1501
+ }
1502
 
1503
+ $output .= "'>\n";
1504
 
1505
+ // Be careful to avoid infinite recursion, because those templates might show each related posts' body or
1506
  // excerpt, which would trigger finding its related posts, which would show its related posts body or excerpt...
1507
+ $this->rendering_related_content = true;
1508
 
1509
  // avoid any monkeying around where someone could trya custom template like a template name like
1510
  // "yarpp-template-;../../wp-config.php". YARPP custom templates are only supported in the theme's root folder.
1511
+ $template = str_replace( '/', '', $template );
1512
+ if ( $domain === 'metabox' ) {
1513
+ include YARPP_DIR . '/includes/template_metabox.php';
1514
+ } elseif ( (bool) $template && $template === 'thumbnails' ) {
1515
+ include YARPP_DIR . '/includes/template_thumbnails.php';
1516
+ } elseif ( (bool) $template && $template === 'list' ) {
1517
+ include YARPP_DIR . '/includes/template_builtin.php';
1518
+ } elseif ( (bool) $template ) {
1519
+ $named_properly = strpos( $template, 'yarpp-template-' ) === 0;
1520
+ $template_exists = file_exists( STYLESHEETPATH . '/' . $template );
1521
+ if ( $named_properly && $template_exists ) {
1522
+ global $post;
1523
+ add_action( 'begin_fetch_post_thumbnail_html', array( $this, 'maybe_regenerate_thumbnails' ), 10, 3 );
1524
+ ob_start();
1525
+ include STYLESHEETPATH . '/' . $template;
1526
+ $output .= ob_get_contents();
1527
+ remove_action( 'begin_fetch_post_thumbnail_html', array( $this, 'maybe_regenerate_thumbnails' ), 10 );
1528
+ ob_end_clean();
1529
+ } else {
1530
+ error_log( 'YARPP Plugin: Could not load template "' . $template . '". ' . ( $named_properly ? 'It is named properly.' : 'It is NOT named properly' ) . ' ' . ( $template_exists ? 'It exists' : 'It does NOT exist' ) . '. Falling back to default template.' );
1531
+ include YARPP_DIR . '/includes/template_builtin.php';
1532
+ }
1533
+ } elseif ( $domain === 'widget' ) {
1534
+ include YARPP_DIR . '/includes/template_widget.php';
1535
+ } else {
1536
+ include YARPP_DIR . '/includes/template_builtin.php';
1537
+ }
1538
+ $this->rendering_related_content = false;
1539
+ $output = trim( $output ) . "\n";
1540
+
1541
+ if ( $cache_status === YARPP_NO_RELATED ) {
1542
+ // Uh, do nothing. Stay very still.
1543
+ } else {
1544
+ $this->active_cache->end_yarpp_time();
1545
+ }
1546
+
1547
+ unset( $related_query );
1548
+ $this->restore_post_context();
1549
+
1550
+ if ( $related_count > 0 && $promote_yarpp && $domain != 'metabox' ) {
1551
  $output .=
1552
+ '<p>' .
1553
+ sprintf(
1554
+ __(
1555
+ "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.",
1556
+ 'yarpp'
1557
+ ),
1558
+ 'https://yarpp.com'
1559
+ ) .
1560
+ "</p>\n";
1561
+ }
1562
+
1563
+ $output .= "</div>\n";
1564
+
1565
+ if ( $echo ) {
1566
+ echo $output;
1567
+ }
1568
  return $output;
1569
  }
1570
+
1571
+ /**
1572
+ * @param (int) $reference_ID
1573
+ * @param (array) $args see readme.txt installation tab's "YARPP functions()" section
1574
  */
1575
+ public function get_related( $reference_ID = null, $args = array() ) {
1576
  // Avoid infinite recursion here.
1577
+ if ( $this->do_not_query_for_related() ) {
1578
+ return false;
1579
+ }
1580
 
1581
+ if ( is_numeric( $reference_ID ) ) {
1582
  $reference_ID = (int) $reference_ID;
1583
+ } else {
1584
  $reference_ID = get_the_ID();
1585
+ }
1586
 
1587
+ /**
1588
  * @since 3.5.3: don't compute on revisions.
1589
+ */
1590
+ if ( $the_post = wp_is_post_revision( $reference_ID ) ) {
1591
+ $reference_ID = $the_post;
1592
+ }
1593
 
1594
+ $this->setup_active_cache( $args );
1595
+
1596
+ $options = array( 'limit', 'order' );
1597
+ extract( $this->parse_args( $args, $options ) );
1598
+
1599
+ $cache_status = $this->active_cache->enforce( $reference_ID, false, $args );
1600
+ if ( in_array( $cache_status, array( YARPP_DONT_RUN, YARPP_NO_RELATED ), true ) ) {
1601
+ return array();
1602
+ }
1603
 
 
 
 
1604
  /* Get ready for YARPP TIME! */
1605
+ $this->active_cache->begin_yarpp_time( $reference_ID, $args );
1606
+
1607
  $related_query = new WP_Query();
1608
+ $orders = explode( ' ', $order );
1609
+ $related_query->query(
1610
+ array(
1611
+ 'p' => $reference_ID,
1612
+ 'orderby' => $orders[0],
1613
+ 'order' => $orders[1],
1614
+ 'showposts' => $limit,
1615
+ 'post_type' => $this->get_query_post_types( $reference_ID, $args ),
1616
+ )
1617
+ );
1618
+
1619
  $related_query->posts = apply_filters(
1620
+ 'yarpp_results',
1621
+ $related_query->posts,
1622
+ array(
1623
+ 'function' => 'get_related',
1624
+ 'args' => $args,
1625
+ 'related_ID' => $reference_ID,
1626
+ )
1627
+ );
1628
+
1629
  $this->active_cache->end_yarpp_time();
1630
  return $related_query->posts;
1631
  }
1632
+
1633
+ /**
1634
+ * @param (int) $reference_ID
1635
+ * @param (array) $args see readme.txt installation tab's "YARPP functions()" section
1636
  */
1637
+ public function related_exist( $reference_ID = null, $args = array() ) {
1638
  // Avoid infinite recursion here.
1639
+ if ( $this->do_not_query_for_related() ) {
1640
+ return false;
1641
+ }
1642
+
1643
+ if ( is_numeric( $reference_ID ) ) {
1644
  $reference_ID = (int) $reference_ID;
1645
+ } else {
1646
  $reference_ID = get_the_ID();
1647
+ }
1648
 
1649
  /** @since 3.5.3: don't compute on revisions */
1650
+ if ( $the_post = wp_is_post_revision( $reference_ID ) ) {
1651
+ $reference_ID = $the_post;
1652
+ }
1653
+
1654
+ $this->setup_active_cache( $args );
1655
 
1656
+ $cache_status = $this->active_cache->enforce( $reference_ID, false, $args );
1657
 
1658
+ if ( in_array( $cache_status, array( YARPP_DONT_RUN, YARPP_NO_RELATED ), true ) ) {
1659
+ return false;
1660
+ }
1661
 
1662
+ /* Get ready for YARPP TIME! */
1663
+ $this->active_cache->begin_yarpp_time( $reference_ID, $args );
1664
  $related_query = new WP_Query();
1665
+ $related_query->query(
1666
+ array(
1667
+ 'p' => $reference_ID,
1668
+ 'showposts' => 1,
1669
+ 'post_type' => $this->get_query_post_types( $reference_ID, $args ),
1670
+ )
1671
+ );
1672
+
1673
  $related_query->posts = apply_filters(
1674
+ 'yarpp_results',
1675
+ $related_query->posts,
1676
+ array(
1677
+ 'function' => 'related_exist',
1678
+ 'args' => $args,
1679
+ 'related_ID' => $reference_ID,
1680
+ )
1681
+ );
1682
+
1683
  $return = $related_query->have_posts();
1684
+ unset( $related_query );
1685
 
1686
  $this->active_cache->end_yarpp_time();
1687
  return $return;
1688
  }
1689
+
1690
  /**
1691
  * @param array $args
1692
+ * @param bool $echo
1693
+ * @return string
1694
  */
1695
+ public function display_demo_related( $args = array(), $echo = true ) {
1696
+ // If YARPP cache is already finding the current post's content, don't ask it to do it again.
1697
  // Avoid infinite recursion here.
1698
+ if ( $this->cache_bypass->demo_time ) {
1699
+ return false;
1700
+ }
1701
+
1702
  $options = array(
1703
+ 'domain',
1704
+ 'limit',
1705
+ 'template',
1706
+ 'order',
1707
+ 'promote_yarpp',
1708
+ );
1709
+ extract( $this->parse_args( $args, $options ) );
1710
+
1711
+ $this->cache_bypass->begin_demo_time( $limit );
1712
+
1713
  $output = "<div class='";
1714
+ if ( $domain === 'website' ) {
1715
+ $output .= 'yarpp-related';
1716
+ } else {
1717
  $output .= "yarpp-related yarpp-related-{$domain}";
1718
+ }
1719
  $output .= "'>\n";
1720
 
1721
+ global $wp_query;
1722
+ $wp_query = new WP_Query();
1723
+
1724
+ $wp_query->query( '' );
1725
 
1726
+ $this->prep_query( $domain === 'rss' );
 
 
1727
  $related_query = $wp_query; // backwards compatibility
1728
+
1729
+ if ( (bool) $template && $template === 'thumbnails' ) {
1730
+ include YARPP_DIR . '/includes/template_thumbnails.php';
1731
+ } elseif ( (bool) $template && file_exists( STYLESHEETPATH . '/' . $template ) ) {
1732
  ob_start();
1733
+ include STYLESHEETPATH . '/' . $template;
1734
  $output .= ob_get_contents();
1735
  ob_end_clean();
1736
  } else {
1737
+ include YARPP_DIR . '/includes/template_builtin.php';
1738
  }
1739
+ $output = trim( $output ) . "\n";
1740
+
1741
  $this->cache_bypass->end_demo_time();
1742
+
1743
+ if ( $promote_yarpp ) {
1744
  $output .=
1745
+ '<p>' .
1746
+ sprintf(
1747
+ __(
1748
+ "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.",
1749
+ 'yarpp'
1750
+ ),
1751
+ 'https://yarpp.com'
1752
+ ) .
1753
+ "</p>\n";
1754
+ }
1755
+ $output .= '</div>';
1756
+
1757
+ if ( $echo ) {
1758
+ echo $output;
1759
+ }
1760
  return $output;
1761
  }
1762
+
1763
+ public function parse_args( $args, $options ) {
1764
  $options_with_rss_variants = array(
1765
  'limit',
1766
+ 'template',
1767
+ 'excerpt_length',
1768
+ 'before_title',
1769
  'after_title',
1770
+ 'before_post',
1771
+ 'after_post',
1772
+ 'before_related',
1773
  'after_related',
1774
+ 'no_results',
1775
+ 'order',
1776
+ 'promote_yarpp',
1777
  'thumbnails_heading',
1778
+ 'thumbnails_default',
1779
+ );
1780
 
1781
+ if ( ! isset( $args['domain'] ) ) {
1782
+ $args['domain'] = 'website';
1783
+ }
1784
 
1785
  $r = array();
1786
+ foreach ( $options as $option ) {
1787
+ if ( $args['domain'] === 'rss'
1788
+ && in_array( $option, $options_with_rss_variants )
1789
+ ) {
1790
  $default = $this->get_option( 'rss_' . $option );
1791
+ } else {
1792
  $default = $this->get_option( $option );
1793
+ }
1794
+
1795
+ if ( isset( $args[ $option ] ) && $args[ $option ] !== $default ) {
1796
+ $r[ $option ] = $args[ $option ];
1797
  } else {
1798
+ $r[ $option ] = $default;
1799
+ }
1800
+
1801
+ if ( $option === 'weight' && ! isset( $r[ $option ]['tax'] ) ) {
1802
+ $r[ $option ]['tax'] = array();
1803
  }
 
 
 
 
1804
  }
1805
  return $r;
1806
  }
1807
+
1808
  private function setup_active_cache( $args ) {
1809
  /* the options which the main sql query cares about: */
1810
  $magic_options = array(
1811
+ 'limit',
1812
+ 'threshold',
1813
+ 'show_pass_post',
1814
+ 'past_only',
1815
+ 'weight',
1816
+ 'exclude',
1817
+ 'require_tax',
1818
+ 'recent',
1819
+ );
1820
 
1821
  $defaults = $this->get_option();
1822
+ foreach ( $magic_options as $option ) {
1823
+ if ( ! isset( $args[ $option ] ) ) {
1824
+ continue;
1825
+ }
1826
 
1827
+ /*
1828
  * limit is a little different... if it's less than what we cache, let it go.
1829
+ */
1830
+ if ( $option === 'limit' && $args[ $option ] <= max( $defaults['limit'], $defaults['rss_limit'] ) ) {
1831
+ continue;
1832
+ }
1833
+
1834
+ if ( $args[ $option ] !== $defaults[ $option ] ) {
1835
  $this->active_cache = $this->cache_bypass;
1836
  return;
1837
  }
1839
 
1840
  $this->active_cache = $this->cache;
1841
  }
1842
+
1843
+ private function prep_query( $is_feed = false ) {
1844
  global $wp_query;
1845
  $wp_query->in_the_loop = true;
1846
+ $wp_query->is_feed = $is_feed;
1847
 
1848
+ /*
1849
  * Make sure we get the right is_single value (see http://wordpress.org/support/topic/288230)
1850
+ */
1851
  $wp_query->is_single = false;
1852
  }
1853
+
1854
+ /**
1855
+ * We're regenerating thumbnails when get_the_post_thumbnail is called
1856
+ * directly from one of our custom templates because many folks have already
1857
+ * coded their custom templates but may also want them to automatically regenerate thumbnails..
1858
+ *
1859
+ * @since 5.22.1
1860
+ *
1861
+ * @param int $post_id The post ID.
1862
+ * @param int $post_thumbnail_id The post thumbnail ID.
1863
+ * @param string|int[] $size Requested image size. Can be any registered image size name, or
1864
+ * an array of width and height values in pixels (in that order).
1865
+ */
1866
+ public function maybe_regenerate_thumbnails( $post_id, $post_thumbnail_id, $size ) {
1867
+ $dimensions = $this->thumbnail_dimensions();
1868
+ if ( $this->diagnostic_generate_thumbnails() ) {
1869
+ $this->ensure_resized_post_thumbnail( $post_id, $dimensions );
1870
+ }
1871
+ }
1872
+
1873
+ /**
1874
  * Return true if user disabled the YARPP related post for the current post, false otherwise.
1875
+ *
1876
  * @return bool
1877
  */
1878
  public function yarpp_disabled_for_this_post() {
1882
  return true;
1883
  }
1884
  return false;
1885
+ }
1886
+
1887
+ /**
1888
+ * Return true if Automatic Display should be disabled
1889
+ *
1890
+ * @return bool
1891
+ * @since 5.24.0
1892
+ */
1893
+ public function is_noyarpp( $content ) {
1894
+ /*
1895
+ * Before automatically adding YARPP's related content onto a post's content, checks the value of the
1896
+ * "yarpp_meta" postmeta's key "yarpp_display_for_this_post", and whether the post's content contains
1897
+ * the magic comment "<!--noyarpp-->"`. If either one of those is true `$noyarpp` will be true, otherwise false.
1898
+ */
1899
+ $noyarpp = $this->yarpp_disabled_for_this_post(); // post meta flag.
1900
+ if ( strpos( $content, '<!--noyarpp-->' ) !== false ) {
1901
+ $noyarpp = true; // content includes <!--noyarpp--> ?
1902
+ }
1903
+ /**
1904
+ * Filters whether or not to disable adding YARPP's related posts on the current post.
1905
+ *
1906
+ * Note: the global `$post` will be populated with the current post, if needed.
1907
+ *
1908
+ * @param bool $noyarpp true indicates that YARPP should be disabled on the post; false indicates it should be shown.
1909
+ * @param string $content post's content
1910
+ * @since 5.24.0
1911
+ */
1912
+ $noyarpp = apply_filters( 'noyarpp', $noyarpp, $content ); // noyarpp filter (since 5.24.0)
1913
+
1914
+ return $noyarpp;
1915
+ }
1916
+
1917
+ /**
1918
  * DEFAULT CONTENT FILTERS
1919
  */
1920
+ public function the_content( $content ) {
 
1921
  // Avoid infinite recursion.
1922
+ if ( is_feed() || $this->do_not_query_for_related() ) {
 
 
1923
  return $content;
1924
  }
1925
 
1926
+ // Disable Automatic Display?
1927
+ if ( true === $this->is_noyarpp( $content ) ) {
1928
+ return $content;
1929
+ }
1930
+
1931
+ $content .= $this->display_basic();
1932
+ $content .= $this->display_pro( 'website' );
1933
  return $content;
1934
  }
1935
 
1936
+ public function the_content_feed( $content ) {
1937
+ if ( ! $this->get_option( 'rss_display' ) ) {
1938
+ return $content;
1939
+ }
1940
 
1941
+ // Disable Automatic Display?
1942
+ if ( true === $this->is_noyarpp( $content ) ) {
1943
+ return $content;
1944
+ }
1945
 
1946
+ return $content . $this->display_related(
1947
+ null,
1948
+ array(
1949
+ 'domain' => 'rss',
1950
+ ),
1951
+ false
1952
+ );
1953
  }
 
 
 
1954
 
1955
+ public function the_excerpt_rss( $content ) {
1956
+ if ( ! $this->get_option( 'rss_excerpt_display' ) || ! $this->get_option( 'rss_display' ) ) {
1957
+ return $content;
1958
+ }
1959
 
1960
+ // Disable Automatic Display?
1961
+ if ( true === $this->is_noyarpp( $content ) ) {
1962
+ return $content;
1963
+ }
1964
 
1965
+ return $content . $this->clean_pre( $this->display_related( null, array( 'domain' => 'rss' ), false ) );
1966
  }
1967
+
1968
  /*
1969
  * UTILS
1970
  */
1971
 
1972
+ /**
1973
  * @since 3.3 Use PHP serialized format instead of JSON.
1974
+ */
1975
+ public function version_info( $enforce_cache = false ) {
1976
+ if ( ! $enforce_cache && false !== ( $result = $this->get_transient( 'yarpp_version_info' ) ) ) {
1977
+ return $result;
1978
+ }
1979
 
1980
  $version = YARPP_VERSION;
1981
+ $remote = wp_remote_post( "https://yarpp.org/checkversion.php?format=php&version={$version}" );
1982
 
1983
+ if ( is_wp_error( $remote ) || wp_remote_retrieve_response_code( $remote ) != 200 || ! isset( $remote['body'] ) || ! is_array( $remote['body'] ) ) {
1984
+ $this->set_transient( 'yarpp_version_info', null, 60 * 60 );
1985
  return false;
1986
+ }
1987
+
1988
+ if ( $result = @unserialize( $remote['body'] ) ) {
1989
+ $this->set_transient( 'yarpp_version_info', $result, 60 * 60 * 24 );
1990
+ }
1991
 
1992
  return $result;
1993
  }
1994
 
1995
+ /**
1996
  * @since 4.0 Optional data collection (default off)
1997
+ */
1998
  public function optin_ping() {
1999
+ if ( $this->get_transient( 'yarpp_optin' ) ) {
2000
+ return true;
2001
+ }
2002
 
2003
+ $remote = wp_remote_post( 'https://yarpp.org/optin/2/', array( 'body' => $this->optin_data() ) );
2004
 
2005
+ if ( is_wp_error( $remote )
2006
+ || wp_remote_retrieve_response_code( $remote ) != 200
2007
+ || ! isset( $remote['body'] )
2008
+ || $remote['body'] !== 'ok'
2009
+ ) {
2010
  /* try again later */
2011
+ $this->set_transient( 'yarpp_optin', null, 60 * 60 );
2012
  return false;
2013
  }
2014
 
2015
+ $this->set_transient( 'yarpp_optin', null, 60 * 60 * 24 * 7 );
2016
 
2017
  return true;
2018
  }
2019
 
2020
+ /**
2021
  * A version of the transient functions which is unaffected by caching plugin behavior.
2022
  * We want to control the lifetime of data.
2023
+ *
2024
+ * @param int $transient
2025
+ * @return bool
2026
+ */
2027
+ private function get_transient( $transient ) {
2028
+ $transient_timeout = $transient . '_timeout';
2029
 
2030
+ if ( intval( get_option( $transient_timeout ) ) < time() ) {
2031
+ delete_option( $transient_timeout );
2032
+ return false; // timed out.
2033
  }
2034
 
2035
+ return get_option( $transient, true ); // still ok.
2036
  }
2037
 
2038
+ private function set_transient( $transient, $data = null, $expiration = 0 ) {
2039
+ $transient_timeout = $transient . '_timeout';
 
 
2040
 
2041
+ if ( get_option( $transient_timeout ) === false ) {
 
2042
 
2043
+ add_option( $transient_timeout, time() + $expiration, '', 'no' );
2044
+ if ( ! is_null( $data ) ) {
2045
+ add_option( $transient, $data, '', 'no' );
2046
+ }
2047
+ } else {
2048
 
2049
+ update_option( $transient_timeout, time() + $expiration );
2050
+ if ( ! is_null( $data ) ) {
2051
+ update_option( $transient, $data );
2052
+ }
2053
  }
2054
 
2055
  $this->kick_other_caches();
2056
  }
2057
+
2058
+ private function delete_transient( $transient ) {
2059
+ delete_option( $transient );
2060
+ delete_option( $transient . '_timeout' );
2061
  }
2062
 
2063
+ /**
2064
  * @since 4.0.4 Helper function to force other caching systems which are too aggressive.
2065
  * <cough>DB Cache Reloaded (Fix)</cough> to flush when YARPP transients are set.
2066
+ */
2067
  private function kick_other_caches() {
2068
+ if ( class_exists( 'DBCacheReloaded' ) ) {
2069
  global $wp_db_cache_reloaded;
2070
+ if ( is_object( $wp_db_cache_reloaded ) && is_a( $wp_db_cache_reloaded, 'DBCacheReloaded' ) ) {
2071
  // if DBCR offered a more granualar way of just flushing options, I'd love that.
2072
  $wp_db_cache_reloaded->dbcr_clear();
2073
  }
2074
  }
2075
  }
2076
 
2077
+ /**
2078
  * @since 3.5.2 Clean_pre is deprecated in WP 3.4, so implement here.
2079
+ */
2080
+ function clean_pre( $text ) {
2081
+ $text = str_replace( array( '<br />', '<br/>', '<br>' ), array( '', '', '' ), $text );
2082
+ $text = str_replace( '<p>', "\n", $text );
2083
+ $text = str_replace( '</p>', '', $text );
2084
  return $text;
2085
  }
2086
 
2087
+ /**
2088
  * Gets the list of valid interval units used by YARPP and MySQL interval statements.
2089
  *
2090
  * @return array keys are valid values for recent units, and for MySQL interval
2092
  */
2093
  public function recent_units() {
2094
  return array(
2095
+ 'day' => __( 'day(s)', 'yarpp' ),
2096
+ 'week' => __( 'week(s)', 'yarpp' ),
2097
+ 'month' => __( 'month(s)', 'yarpp' ),
2098
  );
2099
  }
2100
 
2101
  /**
2102
  * Adds YARPP's content to bbPress topics.
2103
  */
2104
+ public function add_to_bbpress() {
2105
  echo $this->display_basic();
2106
  }
2107
 
2114
  * would trigger adding related content to the post's body, which requires discovering its keywords, etc.
2115
  * 2. if YARPP is currently adding related content. Finding related posts at this time can cause infinite recursion
2116
  * because: the template file might show a posts't content or excerpt, which would cause adding related content
2117
+ * to that post body or excerpt, which would start adding related content to it too, etc. *
2118
  *
2119
  * @return bool
2120
  */
2121
+ protected function do_not_query_for_related() {
2122
  return $this->rendering_related_content ||
2123
+ ( $this->active_cache instanceof YARPP_Cache && $this->active_cache->discovering_keywords() );
2124
  }
2125
  }
classes/YARPP_DB_Options.php CHANGED
@@ -43,11 +43,12 @@ class YARPP_DB_Options {
43
  * @return bool success
44
  */
45
  public function set_yarpp_options( $options ) {
46
- return update_option( 'yarpp', (array)$options );
47
  }
48
 
49
  /**
50
  * Gets whether fulltext indexes were not found to be supported.
 
51
  * @deprecated in 5.14.0 because we just always try to use fulltext indexes
52
  * @return bool
53
  */
@@ -63,7 +64,7 @@ class YARPP_DB_Options {
63
  * @return bool indicating success
64
  */
65
  public function set_fulltext_disabled( $new_value ) {
66
- return update_option( 'yarpp_fulltext_disabled', (bool)$new_value );
67
  }
68
 
69
  /**
@@ -138,15 +139,16 @@ class YARPP_DB_Options {
138
  */
139
  public function update_fulltext_db_record() {
140
  global $wpdb;
141
- return update_option(self::FULLTEXT_DB_ERROR, $wpdb->last_error . '(' . current_time('mysql') . ')');
142
  }
143
 
144
  /**
145
  * Deletes the option that indicates there was an error adding the fulltext index.
 
146
  * @return bool success
147
  */
148
  public function delete_fulltext_db_error_record() {
149
- return delete_option(self::FULLTEXT_DB_ERROR);
150
  }
151
 
152
  /**
@@ -156,13 +158,13 @@ class YARPP_DB_Options {
156
  * @return string
157
  */
158
  public function get_fulltext_db_error() {
159
- return (string)get_option(self::FULLTEXT_DB_ERROR, esc_html__( 'No error recorded.', 'yarpp' ));
160
  }
161
 
162
  /**
163
  * @return bool
164
  */
165
  public function has_fulltext_db_error() {
166
- return (bool)get_option(self::FULLTEXT_DB_ERROR, false);
167
  }
168
  }
43
  * @return bool success
44
  */
45
  public function set_yarpp_options( $options ) {
46
+ return update_option( 'yarpp', (array) $options );
47
  }
48
 
49
  /**
50
  * Gets whether fulltext indexes were not found to be supported.
51
+ *
52
  * @deprecated in 5.14.0 because we just always try to use fulltext indexes
53
  * @return bool
54
  */
64
  * @return bool indicating success
65
  */
66
  public function set_fulltext_disabled( $new_value ) {
67
+ return update_option( 'yarpp_fulltext_disabled', (bool) $new_value );
68
  }
69
 
70
  /**
139
  */
140
  public function update_fulltext_db_record() {
141
  global $wpdb;
142
+ return update_option( self::FULLTEXT_DB_ERROR, $wpdb->last_error . '(' . current_time( 'mysql' ) . ')' );
143
  }
144
 
145
  /**
146
  * Deletes the option that indicates there was an error adding the fulltext index.
147
+ *
148
  * @return bool success
149
  */
150
  public function delete_fulltext_db_error_record() {
151
+ return delete_option( self::FULLTEXT_DB_ERROR );
152
  }
153
 
154
  /**
158
  * @return string
159
  */
160
  public function get_fulltext_db_error() {
161
+ return (string) get_option( self::FULLTEXT_DB_ERROR, esc_html__( 'No error recorded.', 'yarpp' ) );
162
  }
163
 
164
  /**
165
  * @return bool
166
  */
167
  public function has_fulltext_db_error() {
168
+ return (bool) get_option( self::FULLTEXT_DB_ERROR, false );
169
  }
170
  }
classes/YARPP_DB_Schema.php CHANGED
@@ -130,19 +130,21 @@ class YARPP_DB_Schema {
130
 
131
  /**
132
  * Finds out if the YARPP cache table was created or not
 
133
  * @return bool
134
  */
135
- public function cache_table_exists(){
136
- $exists = wp_cache_get(self::CACHE_KEY_TABLE_EXISTS, self::CACHE_GROUP, false, $found);
137
- if( ! $found ){
138
  global $wpdb;
139
  // now check for the cache tables
140
- $tabledata = $wpdb->get_col('SHOW TABLES LIKE "'. $wpdb->prefix . YARPP_TABLES_RELATED_TABLE . '"');
141
- if (in_array($wpdb->prefix . YARPP_TABLES_RELATED_TABLE,$tabledata) !== false)
142
  $exists = true;
143
- else
144
  $exists = false;
145
- wp_cache_set(self::CACHE_KEY_TABLE_EXISTS, $exists, self::CACHE_GROUP);
 
146
  }
147
  return $exists;
148
  }
@@ -150,15 +152,19 @@ class YARPP_DB_Schema {
150
  /**
151
  * Create the YARPP cache table
152
  */
153
- public function create_cache_table(){
154
  global $wpdb;
155
 
156
  $charset_collate = '';
157
- if (!empty($wpdb->charset)) $charset_collate = "DEFAULT CHARACTER SET ".$wpdb->charset;
158
- if (!empty($wpdb->collate)) $charset_collate .= " COLLATE ".$wpdb->collate;
 
 
 
 
159
 
160
  $wpdb->query(
161
- "CREATE TABLE IF NOT EXISTS `".$wpdb->prefix.YARPP_TABLES_RELATED_TABLE."` (
162
  `reference_ID` bigint(20) unsigned NOT NULL default '0',
163
  `ID` bigint(20) unsigned NOT NULL default '0',
164
  `score` float unsigned NOT NULL default '0',
@@ -168,6 +174,6 @@ class YARPP_DB_Schema {
168
  INDEX (`ID`)
169
  )$charset_collate;"
170
  );
171
- wp_cache_delete(self::CACHE_KEY_TABLE_EXISTS, self::CACHE_GROUP);
172
  }
173
  }
130
 
131
  /**
132
  * Finds out if the YARPP cache table was created or not
133
+ *
134
  * @return bool
135
  */
136
+ public function cache_table_exists() {
137
+ $exists = wp_cache_get( self::CACHE_KEY_TABLE_EXISTS, self::CACHE_GROUP, false, $found );
138
+ if ( ! $found ) {
139
  global $wpdb;
140
  // now check for the cache tables
141
+ $tabledata = $wpdb->get_col( 'SHOW TABLES LIKE "' . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE . '"' );
142
+ if ( in_array( $wpdb->prefix . YARPP_TABLES_RELATED_TABLE, $tabledata ) !== false ) {
143
  $exists = true;
144
+ } else {
145
  $exists = false;
146
+ }
147
+ wp_cache_set( self::CACHE_KEY_TABLE_EXISTS, $exists, self::CACHE_GROUP );
148
  }
149
  return $exists;
150
  }
152
  /**
153
  * Create the YARPP cache table
154
  */
155
+ public function create_cache_table() {
156
  global $wpdb;
157
 
158
  $charset_collate = '';
159
+ if ( ! empty( $wpdb->charset ) ) {
160
+ $charset_collate = 'DEFAULT CHARACTER SET ' . $wpdb->charset;
161
+ }
162
+ if ( ! empty( $wpdb->collate ) ) {
163
+ $charset_collate .= ' COLLATE ' . $wpdb->collate;
164
+ }
165
 
166
  $wpdb->query(
167
+ 'CREATE TABLE IF NOT EXISTS `' . $wpdb->prefix . YARPP_TABLES_RELATED_TABLE . "` (
168
  `reference_ID` bigint(20) unsigned NOT NULL default '0',
169
  `ID` bigint(20) unsigned NOT NULL default '0',
170
  `score` float unsigned NOT NULL default '0',
174
  INDEX (`ID`)
175
  )$charset_collate;"
176
  );
177
+ wp_cache_delete( self::CACHE_KEY_TABLE_EXISTS, self::CACHE_GROUP );
178
  }
179
  }
classes/YARPP_Meta_Box.php CHANGED
@@ -1,105 +1,105 @@
1
  <?php
2
 
3
  class YARPP_Meta_Box {
4
- protected $template_text = null;
5
  /**
6
  * @var YARPP
7
  */
8
- protected $yarpp = null;
9
-
10
- public function __construct() {
11
- global $yarpp;
12
- $this->yarpp = $yarpp;
13
- $this->template_text =
14
- __(
15
- "This advanced option gives you full power to customize how your related posts are displayed.&nbsp;".
16
- "Templates are written in PHP and saved in your active theme's folder.",
17
- 'yarpp'
18
- );
19
- }
20
-
21
- private function offer_copy_templates() {
22
- return (!$this->yarpp->diagnostic_custom_templates() && $this->yarpp->admin->can_copy_templates());
23
- }
24
-
25
- public function checkbox($option, $desc, $class = null, $yarpp_args = array()) {
26
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_checkbox.phtml');
27
- }
28
-
29
- public function radio($option, $desc, $class = null, $value = null) {
30
- include( YARPP_DIR . '/includes/phtmls/yarpp_meta_box_radio.phtml' );
31
- }
32
-
33
- public function template_checkbox($rss=false, $class = null) {
34
- $pre = ($rss) ? 'rss_' : '';
35
- $chosen_template = yarpp_get_option($pre."template");
36
- $choice = ($chosen_template === false)
37
- ? 'builtin' : (($chosen_template === 'thumbnails') ? 'thumbnails' : 'custom');
38
-
39
- $builtIn = ($choice === 'builtin') ? 'active' : null;
40
-
41
- $thumbnails = ($choice === 'thumbnails') ? 'active' : null;
42
- $diagPostThumbs = (!$this->yarpp->diagnostic_post_thumbnails()) ? 'disabled' : null;
43
-
44
- $custom = ($choice === 'custom') ? 'active' : null;
45
- $diagCustTemplt = (!$this->yarpp->diagnostic_custom_templates()) ? 'disabled' : null;
46
-
47
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_template_checkbox.phtml');
48
- }
49
-
50
- public function template_file($rss=false, $class=null) {
51
- $pre = ($rss) ? 'rss_' : '';
52
- $chosen_template = yarpp_get_option($pre.'template');
53
-
54
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_template_file.phtml');
55
- }
56
-
57
- public function textbox($option, $desc, $size = 2, $class = null, $note = null) {
58
- $value = esc_attr(yarpp_get_option($option));
59
-
60
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_textbox.phtml');
61
- }
62
-
63
- public function beforeafter($options, $desc, $size = 10, $class = null, $note = null) {
64
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_beforeafter.phtml');
65
- }
66
-
67
- /* MARK: Last cleaning spot */
68
- public function tax_weight($taxonomy) {
69
- $weight = (int) yarpp_get_option("weight[tax][{$taxonomy->name}]");
70
- $require = (int) yarpp_get_option("require_tax[{$taxonomy->name}]");
71
-
72
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_tax_weight.phtml');
73
- }
74
-
75
- /* MARK: Last cleaning spot */
76
- public function weight($option, $desc) {
77
- $weight = (int) yarpp_get_option("weight[$option]");
78
-
79
- /* Both require MyISAM fulltext indexing: */
80
- $fulltext = $this->yarpp->db_schema->database_supports_fulltext_indexes() ? '' : ' readonly="readonly" disabled="disabled"';
81
-
82
- echo "<div class='yarpp_form_row yarpp_form_select'><div class='yarpp_form_label'>{$desc}</div><div>";
83
- echo "<select name='weight[{$option}]'>";
84
- echo "<option {$fulltext} value='no'".((!$weight) ? ' selected="selected"': '')." >".__("do not consider", 'yarpp')."</option>";
85
- echo "<option {$fulltext} value='consider'".(($weight == 1) ? ' selected="selected"': '')." > ".__("consider", 'yarpp')."</option>";
86
- echo "<option {$fulltext} value='consider_extra'".(($weight > 1) ? ' selected="selected"': '')." > ".__("consider with extra weight", 'yarpp')."</option>";
87
- echo "</select></div></div>";
88
- }
89
-
90
- public function displayorder($option, $class=null) {
91
- echo "<div class='yarpp_form_row yarpp_form_select $class'><div class='yarpp_form_label'>";
92
- _e( "Order results:", 'yarpp' );
93
- echo "</div><div><select name='$option' id='<?php echo $option; ?>'>";
94
- $order = yarpp_get_option( $option );
95
- ?>
96
- <option value="score DESC" <?php echo ( $order == 'score DESC'?' selected="selected"':'' )?>><?php _e( "score (high relevance to low)", 'yarpp' ); ?></option>
97
- <option value="score ASC" <?php echo ( $order == 'score ASC'?' selected="selected"':'' )?>><?php _e( "score (low relevance to high)", 'yarpp' ); ?></option>
98
- <option value="post_date DESC" <?php echo ( $order == 'post_date DESC'?' selected="selected"':'' )?>><?php _e( "date (new to old)", 'yarpp' ); ?></option>
99
- <option value="post_date ASC" <?php echo ( $order == 'post_date ASC'?' selected="selected"':'' )?>><?php _e( "date (old to new)", 'yarpp' ); ?></option>
100
- <option value="post_title ASC" <?php echo ( $order == 'post_title ASC'?' selected="selected"':'' )?>><?php _e( "title (alphabetical)", 'yarpp' ); ?></option>
101
- <option value="post_title DESC" <?php echo ( $order == 'post_title DESC'?' selected="selected"':'' )?>><?php _e( "title (reverse alphabetical)", 'yarpp' ); ?></option>
102
- <?php
103
- echo "</select></div></div>";
104
- }
105
- }
1
  <?php
2
 
3
  class YARPP_Meta_Box {
4
+ protected $template_text = null;
5
  /**
6
  * @var YARPP
7
  */
8
+ protected $yarpp = null;
9
+
10
+ public function __construct() {
11
+ global $yarpp;
12
+ $this->yarpp = $yarpp;
13
+ $this->template_text =
14
+ __(
15
+ 'This advanced option gives you full power to customize how your related posts are displayed.&nbsp;' .
16
+ "Templates are written in PHP and saved in your active theme's folder.",
17
+ 'yarpp'
18
+ );
19
+ }
20
+
21
+ private function offer_copy_templates() {
22
+ return ( ! $this->yarpp->diagnostic_custom_templates() && $this->yarpp->admin->can_copy_templates() );
23
+ }
24
+
25
+ public function checkbox( $option, $desc, $class = null, $yarpp_args = array() ) {
26
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_checkbox.phtml';
27
+ }
28
+
29
+ public function radio( $option, $desc, $class = null, $value = null ) {
30
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_radio.phtml';
31
+ }
32
+
33
+ public function template_checkbox( $rss = false, $class = null ) {
34
+ $pre = ( $rss ) ? 'rss_' : '';
35
+ $chosen_template = yarpp_get_option( $pre . 'template' );
36
+ $choice = ( $chosen_template === false )
37
+ ? 'builtin' : ( ( $chosen_template === 'thumbnails' ) ? 'thumbnails' : 'custom' );
38
+
39
+ $builtIn = ( $choice === 'builtin' ) ? 'active' : null;
40
+
41
+ $thumbnails = ( $choice === 'thumbnails' ) ? 'active' : null;
42
+ $diagPostThumbs = ( ! $this->yarpp->diagnostic_post_thumbnails() ) ? 'disabled' : null;
43
+
44
+ $custom = ( $choice === 'custom' ) ? 'active' : null;
45
+ $diagCustTemplt = ( ! $this->yarpp->diagnostic_custom_templates() ) ? 'disabled' : null;
46
+
47
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_template_checkbox.phtml';
48
+ }
49
+
50
+ public function template_file( $rss = false, $class = null ) {
51
+ $pre = ( $rss ) ? 'rss_' : '';
52
+ $chosen_template = yarpp_get_option( $pre . 'template' );
53
+
54
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_template_file.phtml';
55
+ }
56
+
57
+ public function textbox( $option, $desc, $size = 2, $class = null, $note = null ) {
58
+ $value = esc_attr( yarpp_get_option( $option ) );
59
+
60
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_textbox.phtml';
61
+ }
62
+
63
+ public function beforeafter( $options, $desc, $size = 10, $class = null, $note = null ) {
64
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_beforeafter.phtml';
65
+ }
66
+
67
+ /* MARK: Last cleaning spot */
68
+ public function tax_weight( $taxonomy ) {
69
+ $weight = (int) yarpp_get_option( "weight[tax][{$taxonomy->name}]" );
70
+ $require = (int) yarpp_get_option( "require_tax[{$taxonomy->name}]" );
71
+
72
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_tax_weight.phtml';
73
+ }
74
+
75
+ /* MARK: Last cleaning spot */
76
+ public function weight( $option, $desc ) {
77
+ $weight = (int) yarpp_get_option( "weight[$option]" );
78
+
79
+ /* Both require MyISAM fulltext indexing: */
80
+ $fulltext = $this->yarpp->db_schema->database_supports_fulltext_indexes() ? '' : ' readonly="readonly" disabled="disabled"';
81
+
82
+ echo "<div class='yarpp_form_row yarpp_form_select'><div class='yarpp_form_label'>{$desc}</div><div>";
83
+ echo "<select name='weight[{$option}]'>";
84
+ echo "<option {$fulltext} value='no'" . ( ( ! $weight ) ? ' selected="selected"' : '' ) . ' >' . __( 'do not consider', 'yarpp' ) . '</option>';
85
+ echo "<option {$fulltext} value='consider'" . ( ( $weight == 1 ) ? ' selected="selected"' : '' ) . ' > ' . __( 'consider', 'yarpp' ) . '</option>';
86
+ echo "<option {$fulltext} value='consider_extra'" . ( ( $weight > 1 ) ? ' selected="selected"' : '' ) . ' > ' . __( 'consider with extra weight', 'yarpp' ) . '</option>';
87
+ echo '</select></div></div>';
88
+ }
89
+
90
+ public function displayorder( $option, $class = null ) {
91
+ echo "<div class='yarpp_form_row yarpp_form_select $class'><div class='yarpp_form_label'>";
92
+ _e( 'Order results:', 'yarpp' );
93
+ echo "</div><div><select name='$option' id='<?php echo $option; ?>'>";
94
+ $order = yarpp_get_option( $option );
95
+ ?>
96
+ <option value="score DESC" <?php echo ( $order == 'score DESC' ? ' selected="selected"' : '' ); ?>><?php _e( 'score (high relevance to low)', 'yarpp' ); ?></option>
97
+ <option value="score ASC" <?php echo ( $order == 'score ASC' ? ' selected="selected"' : '' ); ?>><?php _e( 'score (low relevance to high)', 'yarpp' ); ?></option>
98
+ <option value="post_date DESC" <?php echo ( $order == 'post_date DESC' ? ' selected="selected"' : '' ); ?>><?php _e( 'date (new to old)', 'yarpp' ); ?></option>
99
+ <option value="post_date ASC" <?php echo ( $order == 'post_date ASC' ? ' selected="selected"' : '' ); ?>><?php _e( 'date (old to new)', 'yarpp' ); ?></option>
100
+ <option value="post_title ASC" <?php echo ( $order == 'post_title ASC' ? ' selected="selected"' : '' ); ?>><?php _e( 'title (alphabetical)', 'yarpp' ); ?></option>
101
+ <option value="post_title DESC" <?php echo ( $order == 'post_title DESC' ? ' selected="selected"' : '' ); ?>><?php _e( 'title (reverse alphabetical)', 'yarpp' ); ?></option>
102
+ <?php
103
+ echo '</select></div></div>';
104
+ }
105
+ }
classes/YARPP_Meta_Box_Contact.php CHANGED
@@ -1,35 +1,35 @@
1
  <?php
2
 
3
  class YARPP_Meta_Box_Contact extends YARPP_Meta_Box {
4
- public function display() {
5
  global $yarpp;
6
 
7
- $happy = ($yarpp->diagnostic_happy()) ? 'spin' : null;
8
 
9
  $out =
10
- '<ul class="yarpp_contacts">'.
11
- '<li>'.
12
- '<a href="https://wordpress.org/support/plugin/yet-another-related-posts-plugin/" target="_blank">'.
13
- '<span class="icon icon-wordpress"></span> '.__('YARPP Forum', 'yarpp').
14
- '</a>'.
15
- '</li>'.
16
- '<li>'.
17
- '<a href="https://twitter.com/yarpp" target="_blank">'.
18
- '<span class="icon icon-twitter"></span> '.__('YARPP on Twitter', 'yarpp').
19
- '</a>'.
20
- '</li>'.
21
- '<li>'.
22
- '<a href="https://www.facebook.com/groups/357562101611506/" target="_blank">'.
23
- '<span class="icon icon-facebook"></span> YARPP User Group on Facebook'.
24
- '</a>'.
25
- '</li>'.
26
- '<li>'.
27
- '<a href="https://wordpress.org/support/plugin/yet-another-related-posts-plugin/reviews/?rate=5#new-post" target="_blank">'.
28
- '<span class="icon icon-star '.$happy.'"></span> '.__('Review YARPP on WordPress.org', 'yarpp').
29
- '</a>'.
30
- '</li>'.
31
- '</ul>';
32
 
33
- echo $out;
34
  }
35
- }
1
  <?php
2
 
3
  class YARPP_Meta_Box_Contact extends YARPP_Meta_Box {
4
+ public function display() {
5
  global $yarpp;
6
 
7
+ $happy = ( $yarpp->diagnostic_happy() ) ? 'spin' : null;
8
 
9
  $out =
10
+ '<ul class="yarpp_contacts">' .
11
+ '<li>' .
12
+ '<a href="https://wordpress.org/support/plugin/yet-another-related-posts-plugin/" target="_blank">' .
13
+ '<span class="icon icon-wordpress"></span> ' . __( 'YARPP Forum', 'yarpp' ) .
14
+ '</a>' .
15
+ '</li>' .
16
+ '<li>' .
17
+ '<a href="https://twitter.com/yarpp" target="_blank">' .
18
+ '<span class="icon icon-twitter"></span> ' . __( 'YARPP on Twitter', 'yarpp' ) .
19
+ '</a>' .
20
+ '</li>' .
21
+ '<li>' .
22
+ '<a href="https://www.facebook.com/groups/357562101611506/" target="_blank">' .
23
+ '<span class="icon icon-facebook"></span> YARPP User Group on Facebook' .
24
+ '</a>' .
25
+ '</li>' .
26
+ '<li>' .
27
+ '<a href="https://wordpress.org/support/plugin/yet-another-related-posts-plugin/reviews/?rate=5#new-post" target="_blank">' .
28
+ '<span class="icon icon-star ' . $happy . '"></span> ' . __( 'Review YARPP on WordPress.org', 'yarpp' ) .
29
+ '</a>' .
30
+ '</li>' .
31
+ '</ul>';
32
 
33
+ echo $out;
34
  }
35
+ }
classes/YARPP_Meta_Box_Display_Feed.php CHANGED
@@ -1,76 +1,79 @@
1
  <?php
2
 
3
  class YARPP_Meta_Box_Display_Feed extends YARPP_Meta_Box {
4
- public function display() {
5
- global $yarpp;
6
 
7
- echo "<div>";
8
- echo '<div class="rss_displayed yarpp_code_display"';
9
- if ( !$yarpp->get_option('code_display') )
10
- echo ' style="display: none;"';
11
- echo '><b>' . __( "RSS display code example", 'yarpp' ) . '</b><br /><small>' . __( "(Update options to reload.)", 'yarpp' ) . "</small><br/><div id='display_demo_rss'></div></div>";
 
12
 
13
- $this->checkbox( 'rss_display', __( "Display related posts in feeds?", 'yarpp' )." <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( "This option displays related posts at the end of each item in your RSS and Atom feeds. No template changes are needed.", 'yarpp' ) ) . "'>&nbsp;</span>", '' );
14
- $this->checkbox( 'rss_excerpt_display', __( "Display related posts in the descriptions?", 'yarpp' )." <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( "This option displays the related posts in the RSS description fields, not just the content. If your feeds are set up to only display excerpts, however, only the description field is used, so this option is required for any display at all.", 'yarpp' ) ) . "'>&nbsp;</span>", 'rss_displayed' );
15
 
16
- $this->textbox( 'rss_limit', __( 'Maximum number of posts:', 'yarpp' ), 2, 'rss_displayed' );
17
- $this->template_checkbox( true, 'rss_displayed' );
18
- echo "</div>";
19
 
20
- $chosen_template = yarpp_get_option( "rss_template" );
21
- $choice = false === $chosen_template ? 'builtin' :
22
- ( $chosen_template == 'thumbnails' ? 'thumbnails' : 'custom' );
23
 
24
- // Wrap all the options in a div with a gray border
25
- echo '<div class="postbox rss_displayed">';
26
- echo "<div class='yarpp_subbox template_options_custom'";
27
- if ( $choice != 'custom' )
28
- echo ' style="display: none;"';
29
- echo ">";
30
- echo '<div class="yarpp_form_row"><div>' . $this->template_text . '</div></div>';
31
- $this->template_file( true );
32
- echo "</div>";
 
33
 
34
- echo "<div class='yarpp_subbox template_options_thumbnails'";
35
- if ( $choice != 'thumbnails' )
36
- echo ' style="display: none;"';
37
- echo ">";
38
- $this->textbox( 'rss_thumbnails_heading', __( 'Heading:', 'yarpp' ), 40 );
39
- $this->textbox( 'rss_thumbnails_default', __( 'Default image (URL):', 'yarpp' ), 40 );
40
- $get_image_sizes = yarpp_get_image_sizes();
41
- echo '<div class="yarpp_form_row yarpp_form_radio_label">';
 
42
  echo '<div class="yarpp_form_label">' . esc_html( 'Thumbnail Size', 'yarpp' ) . '</div><div>';
43
- foreach ( $get_image_sizes as $key => $_size ) {
44
- /* translators: %s: thumbnail key's name */
45
- $name = sprintf( __( '%1$s (%2$s X %3$s)', 'yarpp' ), $key, $_size['width'], $_size['height'] );
46
- $this->radio( 'thumbnail_size_feed_display', $name, '', $key );
47
- }
48
- echo '</div></div>';
49
- echo "</div>";
50
-
51
- echo "<div class='yarpp_subbox template_options_builtin'";
52
- if ( $choice != 'builtin' )
53
- echo ' style="display: none;"';
54
- echo ">";
55
- $this->beforeafter( array( 'rss_before_related', 'rss_after_related' ), __( "Before / after related entries:", 'yarpp' ), 15, '', __( "For example:", 'yarpp' ) . ' &lt;ol&gt;&lt;/ol&gt;' . __( ' or ', 'yarpp' ) . '&lt;div&gt;&lt;/div&gt;' );
56
- $this->beforeafter( array( 'rss_before_title', 'rss_after_title' ), __( "Before / after each related entry:", 'yarpp' ), 15, '', __( "For example:", 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
57
 
58
- $this->checkbox( 'rss_show_excerpt', __( "Show excerpt?", 'yarpp' ), 'show_excerpt' );
59
- $this->textbox( 'rss_excerpt_length', __( 'Excerpt length (No. of words):', 'yarpp' ), 10, 'excerpted' );
 
 
 
 
 
60
 
61
- $this->beforeafter( array( 'rss_before_post', 'rss_after_post' ), __( "Before / after (excerpt):", 'yarpp' ), 10, 'excerpted', __( "For example:", 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
62
- echo "</div>";
63
 
64
- echo '<div class="yarpp_no_results">';
65
- $this->textbox( 'rss_no_results', __( 'Default display if no results:', 'yarpp' ), 40, 'sync_rss_no_results' );
66
- echo '</div>';
67
 
68
- // Close the div that wraps all the options
69
- echo '</div>';
 
70
 
 
 
71
 
72
- $this->displayorder( 'rss_order', 'rss_displayed' );
73
 
74
- $this->checkbox( 'rss_promote_yarpp', __( "Link to YARPP?", 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( sprintf( __( "This option will add the code %s These links are greatly appreciated and keeps us motivated.", 'yarpp' ), "<code>" . htmlspecialchars( sprintf( __( "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.", 'yarpp' ), 'https://yarpp.com' ) )."</code>" ) ) . "'>&nbsp;</span>", 'rss_displayed' );
75
- }
76
- }
1
  <?php
2
 
3
  class YARPP_Meta_Box_Display_Feed extends YARPP_Meta_Box {
4
+ public function display() {
5
+ global $yarpp;
6
 
7
+ echo '<div>';
8
+ echo '<div class="rss_displayed yarpp_code_display"';
9
+ if ( ! $yarpp->get_option( 'code_display' ) ) {
10
+ echo ' style="display: none;"';
11
+ }
12
+ echo '><b>' . __( 'RSS display code example', 'yarpp' ) . '</b><br /><small>' . __( '(Update options to reload.)', 'yarpp' ) . "</small><br/><div id='display_demo_rss'></div></div>";
13
 
14
+ $this->checkbox( 'rss_display', __( 'Display related posts in feeds?', 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( 'This option displays related posts at the end of each item in your RSS and Atom feeds. No template changes are needed.', 'yarpp' ) ) . "'>&nbsp;</span>", '' );
15
+ $this->checkbox( 'rss_excerpt_display', __( 'Display related posts in the descriptions?', 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( 'This option displays the related posts in the RSS description fields, not just the content. If your feeds are set up to only display excerpts, however, only the description field is used, so this option is required for any display at all.', 'yarpp' ) ) . "'>&nbsp;</span>", 'rss_displayed' );
16
 
17
+ $this->textbox( 'rss_limit', __( 'Maximum number of posts:', 'yarpp' ), 2, 'rss_displayed' );
18
+ $this->template_checkbox( true, 'rss_displayed' );
19
+ echo '</div>';
20
 
21
+ $chosen_template = yarpp_get_option( 'rss_template' );
22
+ $choice = false === $chosen_template ? 'builtin' :
23
+ ( $chosen_template == 'thumbnails' ? 'thumbnails' : 'custom' );
24
 
25
+ // Wrap all the options in a div with a gray border
26
+ echo '<div class="postbox rss_displayed">';
27
+ echo "<div class='yarpp_subbox template_options_custom'";
28
+ if ( $choice != 'custom' ) {
29
+ echo ' style="display: none;"';
30
+ }
31
+ echo '>';
32
+ echo '<div class="yarpp_form_row"><div>' . $this->template_text . '</div></div>';
33
+ $this->template_file( true );
34
+ echo '</div>';
35
 
36
+ echo "<div class='yarpp_subbox template_options_thumbnails'";
37
+ if ( $choice != 'thumbnails' ) {
38
+ echo ' style="display: none;"';
39
+ }
40
+ echo '>';
41
+ $this->textbox( 'rss_thumbnails_heading', __( 'Heading:', 'yarpp' ), 40 );
42
+ $this->textbox( 'rss_thumbnails_default', __( 'Default image (URL):', 'yarpp' ), 40 );
43
+ $get_image_sizes = yarpp_get_image_sizes();
44
+ echo '<div class="yarpp_form_row yarpp_form_radio_label">';
45
  echo '<div class="yarpp_form_label">' . esc_html( 'Thumbnail Size', 'yarpp' ) . '</div><div>';
46
+ foreach ( $get_image_sizes as $key => $_size ) {
47
+ /* translators: %s: thumbnail key's name */
48
+ $name = sprintf( __( '%1$s (%2$s X %3$s)', 'yarpp' ), $key, $_size['width'], $_size['height'] );
49
+ $this->radio( 'thumbnail_size_feed_display', $name, '', $key );
50
+ }
51
+ echo '</div></div>';
52
+ echo '</div>';
 
 
 
 
 
 
 
53
 
54
+ echo "<div class='yarpp_subbox template_options_builtin'";
55
+ if ( $choice != 'builtin' ) {
56
+ echo ' style="display: none;"';
57
+ }
58
+ echo '>';
59
+ $this->beforeafter( array( 'rss_before_related', 'rss_after_related' ), __( 'Before / after related entries:', 'yarpp' ), 15, '', __( 'For example:', 'yarpp' ) . ' &lt;ol&gt;&lt;/ol&gt;' . __( ' or ', 'yarpp' ) . '&lt;div&gt;&lt;/div&gt;' );
60
+ $this->beforeafter( array( 'rss_before_title', 'rss_after_title' ), __( 'Before / after each related entry:', 'yarpp' ), 15, '', __( 'For example:', 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
61
 
62
+ $this->checkbox( 'rss_show_excerpt', __( 'Show excerpt?', 'yarpp' ), 'show_excerpt' );
63
+ $this->textbox( 'rss_excerpt_length', __( 'Excerpt length (No. of words):', 'yarpp' ), 10, 'excerpted' );
64
 
65
+ $this->beforeafter( array( 'rss_before_post', 'rss_after_post' ), __( 'Before / after (excerpt):', 'yarpp' ), 10, 'excerpted', __( 'For example:', 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
66
+ echo '</div>';
 
67
 
68
+ echo '<div class="yarpp_no_results">';
69
+ $this->textbox( 'rss_no_results', __( 'Default display if no results:', 'yarpp' ), 40, 'sync_rss_no_results' );
70
+ echo '</div>';
71
 
72
+ // Close the div that wraps all the options
73
+ echo '</div>';
74
 
75
+ $this->displayorder( 'rss_order', 'rss_displayed' );
76
 
77
+ $this->checkbox( 'rss_promote_yarpp', __( 'Link to YARPP?', 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( sprintf( __( 'This option will add the code %s These links are greatly appreciated and keeps us motivated.', 'yarpp' ), '<code>' . htmlspecialchars( sprintf( __( "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.", 'yarpp' ), 'https://yarpp.com' ) ) . '</code>' ) ) . "'>&nbsp;</span>", 'rss_displayed' );
78
+ }
79
+ }
classes/YARPP_Meta_Box_Display_Rest_Api.php CHANGED
@@ -7,11 +7,11 @@ class YARPP_Meta_Box_Display_Rest_Api extends YARPP_Meta_Box {
7
  echo "<div class='yarpp_rest_displayed'>";
8
  $this->checkbox( 'rest_api_client_side_caching', __( 'Enable in-browser caching?', 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( 'Web browsers will be instructed to cache YARPP REST API results. This can dramatically increase the speed of subsequent YARPP REST API requests, but it also means stale content might be served for the length of the cache time.', 'yarpp' ) ) . "'>&nbsp;</span>", '' );
9
  echo '<div class="yarpp_rest_browser_cache_displayed">';
10
- $this->textbox('yarpp_rest_api_cache_time', __('Cache time (in minutes)', 'yarpp'));
11
  echo '</div>';
12
 
13
  echo '<a href="https://support.shareaholic.com/hc/en-us/articles/360046456752">';
14
- esc_html_e('YARPP REST API documentation →', 'yarpp');
15
  echo '</a>';
16
 
17
  echo '</div>';
7
  echo "<div class='yarpp_rest_displayed'>";
8
  $this->checkbox( 'rest_api_client_side_caching', __( 'Enable in-browser caching?', 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( 'Web browsers will be instructed to cache YARPP REST API results. This can dramatically increase the speed of subsequent YARPP REST API requests, but it also means stale content might be served for the length of the cache time.', 'yarpp' ) ) . "'>&nbsp;</span>", '' );
9
  echo '<div class="yarpp_rest_browser_cache_displayed">';
10
+ $this->textbox( 'yarpp_rest_api_cache_time', __( 'Cache time (in minutes)', 'yarpp' ) );
11
  echo '</div>';
12
 
13
  echo '<a href="https://support.shareaholic.com/hc/en-us/articles/360046456752">';
14
+ esc_html_e( 'YARPP REST API documentation →', 'yarpp' );
15
  echo '</a>';
16
 
17
  echo '</div>';
classes/YARPP_Meta_Box_Display_Web.php CHANGED
@@ -1,120 +1,129 @@
1
  <?php
2
 
3
  class YARPP_Meta_Box_Display_Web extends YARPP_Meta_Box {
4
- public function display() {
5
- global $yarpp;
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- echo "<div>";
8
- echo '<div class="yarpp_code_display"';
9
- if ( !$yarpp->get_option('code_display') )
10
- echo ' style="display: none;"';
11
- echo '><strong>' . __( "Website display code example", 'yarpp' ) . '</strong><br /><small>' . __( "(Update options to reload.)", 'yarpp' ) . "</small><br/><div id='display_demo_web'></div></div>";
 
12
 
13
- echo "<div class='yarpp_form_row yarpp_form_post_types'><div>";
14
- echo __( "Automatically display related content on: ", 'yarpp' );
15
- echo " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( "This option automatically displays YARPP right after the content on single entry pages. If this option is off, you will need to manually insert the <code>[yarpp]</code> shortcode, block or <code>yarpp_related()</code> PHP function into your theme files.", 'yarpp' ) ) . "'>&nbsp;</span>&nbsp;&nbsp;";
16
- echo "</div><div>";
17
- $post_types = yarpp_get_option( 'auto_display_post_types' );
18
- $include_post_type = yarpp_get_option( 'include_post_type' );
19
- $include_post_type = wp_parse_list( $include_post_type );
20
- foreach ($yarpp->get_post_types('objects') as $post_type) {
21
- $post_type_title = $post_type->labels->name;
22
- $disabled_checkbox = '';
23
- $hide_help_text = 'style="display: none;"';
24
- if ( ! yarpp_get_option( 'cross_relate' ) && ! in_array( $post_type->name, $include_post_type, true ) ) {
25
- $disabled_checkbox = 'disabled';
26
- $hide_help_text = '';
27
- }
28
- $help_text = "<span {$hide_help_text} style='color: #d63638;' class='yarpp_help dashicons dashicons-warning' data-help='" . "<p>" . esc_attr( __( "This option is disabled because 'The Pool':", 'yarpp' ) ) . "</p><p>" . esc_attr( __("1. does not include this post type", 'yarpp' ) ) . "</p><p>" . esc_attr( __("2. limits results to the same post type as the current post", 'yarpp' ) ) . "</p><p>" . esc_attr( __("This combination will always result in no posts displaying on this post type. To enable, in The Pool either include this post type or do not limit results to the same post type.", 'yarpp' ) ) . "</p>" . "'>&nbsp;</span>&nbsp;&nbsp;";
29
- // Clarify "topics" are from bbPress plugin
30
- if($post_type->name == 'topic' && class_exists('bbPress')){
31
- $post_type_title = sprintf(
32
- __('BuddyPress %s', 'yarpp'),
33
- $post_type_title
34
- );
35
- }
36
- echo "<label for='yarpp_post_type_{$post_type->name}'><input id='yarpp_post_type_{$post_type->name}' name='auto_display_post_types[{$post_type->name}]' type='checkbox' ";
37
- checked( in_array( $post_type->name, $post_types ) );
38
- echo $disabled_checkbox;
39
- echo "/> {$post_type_title}{$help_text}</label> ";
40
- }
41
- echo "</div></div>";
42
 
43
- $this->checkbox( 'auto_display_archive', __( "Display on the front page, category and archive pages", 'yarpp' ) );
44
 
45
- $this->textbox( 'limit', __( 'Maximum number of posts:', 'yarpp' ) );
46
-
47
- $this->template_checkbox( false );
48
- echo "</div>";
49
- $get_image_sizes = yarpp_get_image_sizes();
50
- $chosen_template = yarpp_get_option( "template" );
51
- $choice = false === $chosen_template ? 'builtin' :
52
- ( $chosen_template == 'thumbnails' ? 'thumbnails' : 'custom' );
53
 
54
- // Wrap all the options in a div with a gray border
55
- echo '<div class="postbox">';
 
 
 
 
56
 
57
- echo "<div class='yarpp_subbox template_options_custom'";
58
- if ( $choice != 'custom' )
59
- echo ' style="display: none;"';
60
- echo ">";
61
- echo '<div class="yarpp_form_row"><div>' . $this->template_text . '</div></div>';
62
- $this->template_file( false );
63
- echo '<div class="yarpp_form_row yarpp_form_radio_label">';
64
- echo '<div class="yarpp_form_label">' . esc_html( 'Thumbnail Size', 'yarpp' ) . '</div><div>';
65
- foreach ( $get_image_sizes as $key => $_size ) {
66
- /* translators: %s: thumbnail key's name */
67
- $name = sprintf( __( '%1$s (%2$sx%3$s)', 'yarpp' ), $key, $_size['width'], $_size['height'] );
68
- $this->radio( 'custom_theme_thumbnail_size_display', $name, '', $key );
69
- }
70
- echo '</div></div>';
71
- echo "</div>";
72
 
73
- echo "<div class='yarpp_subbox template_options_thumbnails'";
74
- if ( $choice != 'thumbnails' )
75
- echo ' style="display: none;"';
76
- echo ">";
77
- $this->textbox( 'thumbnails_heading', __( 'Heading:', 'yarpp' ), 40 );
78
- $this->textbox( 'thumbnails_default', __( 'Default image (URL):', 'yarpp' ), 40 );
79
- echo '<div class="yarpp_form_row yarpp_form_radio_label">';
80
- echo '<div class="yarpp_form_label">' . esc_html( 'Thumbnail Size', 'yarpp' ) . '</div><div>';
81
- foreach ( $get_image_sizes as $key => $_size ) {
82
- /* translators: %s: thumbnail key's name */
83
- $name = sprintf( __( '%1$s (%2$sx%3$s)', 'yarpp' ), $key, $_size['width'], $_size['height'] );
84
- $this->radio( 'thumbnail_size_display', $name, '', $key );
85
- }
86
- echo '</div></div>';
87
- $disabled_checkbox = '';
88
- $generate_missing_thumbnails = yarpp_get_option( 'generate_missing_thumbnails' );
89
- if ( defined( 'YARPP_GENERATE_THUMBNAILS' ) ) {
90
- $disabled_checkbox = 'disabled';
91
- $generate_missing_thumbnails = YARPP_GENERATE_THUMBNAILS;
92
- }
93
- $yarpp_args = array( 'template_type' => 'right-aligned-checkbox', 'disabled_checkbox' => $disabled_checkbox, 'option_value' => $generate_missing_thumbnails );
94
- $this->checkbox( 'generate_missing_thumbnails', __( "Generate missing thumbnail sizes: ", 'yarpp' ) . "<span class='yarpp_help dashicons dashicons-editor-help' data-help='" . "<p>" . esc_attr( __( "When enabled, missing thumbnail sizes will be automatically generated on the fly. Doing this type of processing on the fly may not scale well for larger sites.", 'yarpp' ) ) . "</p><p>" . sprintf( __( 'For larger sites, we recommend the %1$s or %2$s to generate missing thumbnail sizes in a batch process.', 'yarpp' ), '<a href="https://wordpress.org/plugins/regenerate-thumbnails/" target="_blank">Regenerate Thumbnails plugin</a>', '<a href="https://developer.wordpress.org/cli/commands/media/regenerate/" target="_blank">WP-CLI</a>' ) . "</p><p>" . esc_attr( __( "New images should continue to automatically get all active thumbnail sizes generated when they are uploaded.", 'yarpp' ) ) . "</p>" . "'>&nbsp;</span>&nbsp;&nbsp;", 'yarpp', $yarpp_args );
95
- echo "</div>";
96
-
97
- echo "<div class='yarpp_subbox template_options_builtin'";
98
- if ( $choice != 'builtin' )
99
- echo ' style="display: none;"';
100
- echo ">";
101
- $this->beforeafter( array( 'before_related', 'after_related' ), __( "Before / after related entries:", 'yarpp' ), 15, '', __( "For example:", 'yarpp' ) . ' &lt;ol&gt;&lt;/ol&gt;' . __( ' or ', 'yarpp' ) . '&lt;div&gt;&lt;/div&gt;' );
102
- $this->beforeafter( array( 'before_title', 'after_title' ), __( "Before / after each related entry:", 'yarpp' ), 15, '', __( "For example:", 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
103
 
104
- $this->checkbox( 'show_excerpt', __( "Show excerpt?", 'yarpp' ), 'show_excerpt' );
105
- $this->textbox( 'excerpt_length', __( 'Excerpt length (No. of words):', 'yarpp' ), 10, 'excerpted' );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- $this->beforeafter( array( 'before_post', 'after_post' ), __( "Before / after (excerpt):", 'yarpp' ), 10, 'excerpted', __( "For example:", 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
108
- echo "</div>";
109
 
110
- echo '<div class="yarpp_no_results">';
111
- $this->textbox( 'no_results', __( 'Default display if no results:', 'yarpp' ), 40, 'sync_no_results' );
112
- echo '</div>';
113
 
114
- // Close the div that wraps all the options
115
- echo '</div>';
 
116
 
117
- $this->displayorder( 'order' );
118
- $this->checkbox( 'promote_yarpp', __( "Link to YARPP?", 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( sprintf( __( "This option will add the code %s These links are greatly appreciated and keeps us motivated.", 'yarpp' ), "<code>" . htmlspecialchars( sprintf( __( "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.", 'yarpp' ), 'https://yarpp.com' ) )."</code>" ) ) . "'>&nbsp;</span>", 'yarpp' );
119
- }
120
- }
 
 
 
1
  <?php
2
 
3
  class YARPP_Meta_Box_Display_Web extends YARPP_Meta_Box {
4
+ public function display() {
5
+ global $yarpp;
6
+ $disabled_checkbox = '';
7
+ $generate_missing_thumbnails = yarpp_get_option( 'generate_missing_thumbnails' );
8
+ if ( defined( 'YARPP_GENERATE_THUMBNAILS' ) ) {
9
+ $disabled_checkbox = 'disabled';
10
+ $generate_missing_thumbnails = YARPP_GENERATE_THUMBNAILS;
11
+ }
12
+ $yarpp_args = array(
13
+ 'template_type' => 'right-aligned-checkbox',
14
+ 'disabled_checkbox' => $disabled_checkbox,
15
+ 'option_value' => $generate_missing_thumbnails,
16
+ );
17
 
18
+ echo '<div>';
19
+ echo '<div class="yarpp_code_display"';
20
+ if ( ! $yarpp->get_option( 'code_display' ) ) {
21
+ echo ' style="display: none;"';
22
+ }
23
+ echo '><strong>' . __( 'Website display code example', 'yarpp' ) . '</strong><br /><small>' . __( '(Update options to reload.)', 'yarpp' ) . "</small><br/><div id='display_demo_web'></div></div>";
24
 
25
+ echo "<div class='yarpp_form_row yarpp_form_post_types'><div>";
26
+ echo __( 'Automatically display related content on: ', 'yarpp' );
27
+ echo " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( __( 'This option automatically displays YARPP right after the content on single entry pages. If this option is off, you will need to manually insert the <code>[yarpp]</code> shortcode, block or <code>yarpp_related()</code> PHP function into your theme files.', 'yarpp' ) ) . "'>&nbsp;</span>&nbsp;&nbsp;";
28
+ echo '</div><div>';
29
+ $post_types = yarpp_get_option( 'auto_display_post_types' );
30
+ $include_post_type = yarpp_get_option( 'include_post_type' );
31
+ $include_post_type = wp_parse_list( $include_post_type );
32
+ foreach ( $yarpp->get_post_types( 'objects' ) as $post_type ) {
33
+ $post_type_title = $post_type->labels->name;
34
+ $disabled_checkbox = '';
35
+ $hide_help_text = 'style="display: none;"';
36
+ if ( ! yarpp_get_option( 'cross_relate' ) && ! in_array( $post_type->name, $include_post_type, true ) ) {
37
+ $disabled_checkbox = 'disabled';
38
+ $hide_help_text = '';
39
+ }
40
+ $help_text = "<span {$hide_help_text} style='color: #d63638;' class='yarpp_help dashicons dashicons-warning' data-help='" . '<p>' . esc_attr( __( "This option is disabled because 'The Pool':", 'yarpp' ) ) . '</p><p>' . esc_attr( __( '1. does not include this post type', 'yarpp' ) ) . '</p><p>' . esc_attr( __( '2. limits results to the same post type as the current post', 'yarpp' ) ) . '</p><p>' . esc_attr( __( 'This combination will always result in no posts displaying on this post type. To enable, in The Pool either include this post type or do not limit results to the same post type.', 'yarpp' ) ) . '</p>' . "'>&nbsp;</span>&nbsp;&nbsp;";
41
+ // Clarify "topics" are from bbPress plugin
42
+ if ( $post_type->name == 'topic' && class_exists( 'bbPress' ) ) {
43
+ $post_type_title = sprintf(
44
+ __( 'BuddyPress %s', 'yarpp' ),
45
+ $post_type_title
46
+ );
47
+ }
48
+ echo "<label for='yarpp_post_type_{$post_type->name}'><input id='yarpp_post_type_{$post_type->name}' name='auto_display_post_types[{$post_type->name}]' type='checkbox' ";
49
+ checked( in_array( $post_type->name, $post_types ) );
50
+ echo $disabled_checkbox;
51
+ echo "/> {$post_type_title}{$help_text}</label> ";
52
+ }
53
+ echo '</div></div>';
54
 
55
+ $this->checkbox( 'auto_display_archive', __( 'Display on the front page, category and archive pages', 'yarpp' ) );
56
 
57
+ $this->textbox( 'limit', __( 'Maximum number of posts:', 'yarpp' ) );
 
 
 
 
 
 
 
58
 
59
+ $this->template_checkbox( false );
60
+ echo '</div>';
61
+ $get_image_sizes = yarpp_get_image_sizes();
62
+ $chosen_template = yarpp_get_option( 'template' );
63
+ $choice = false === $chosen_template ? 'builtin' :
64
+ ( $chosen_template == 'thumbnails' ? 'thumbnails' : 'custom' );
65
 
66
+ // Wrap all the options in a div with a gray border
67
+ echo '<div class="postbox">';
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ echo "<div class='yarpp_subbox template_options_custom'";
70
+ if ( $choice != 'custom' ) {
71
+ echo ' style="display: none;"';
72
+ }
73
+ echo '>';
74
+ echo '<div class="yarpp_form_row"><div>' . $this->template_text . '</div></div>';
75
+ $this->template_file( false );
76
+ echo '<div class="yarpp_form_row yarpp_form_radio_label">';
77
+ echo '<div class="yarpp_form_label">' . esc_html( 'Thumbnail Size', 'yarpp' ) . '</div><div>';
78
+ foreach ( $get_image_sizes as $key => $_size ) {
79
+ /* translators: %s: thumbnail key's name */
80
+ $name = sprintf( __( '%1$s (%2$sx%3$s)', 'yarpp' ), $key, $_size['width'], $_size['height'] );
81
+ $this->radio( 'custom_theme_thumbnail_size_display', $name, '', $key );
82
+ }
83
+ echo '</div></div>';
84
+ echo '</div>';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ echo "<div class='yarpp_subbox template_options_thumbnails'";
87
+ if ( $choice != 'thumbnails' ) {
88
+ echo ' style="display: none;"';
89
+ }
90
+ echo '>';
91
+ $this->textbox( 'thumbnails_heading', __( 'Heading:', 'yarpp' ), 40 );
92
+ $this->textbox( 'thumbnails_default', __( 'Default image (URL):', 'yarpp' ), 40 );
93
+ echo '<div class="yarpp_form_row yarpp_form_radio_label">';
94
+ echo '<div class="yarpp_form_label">' . esc_html( 'Thumbnail Size', 'yarpp' ) . '</div><div>';
95
+ foreach ( $get_image_sizes as $key => $_size ) {
96
+ /* translators: %s: thumbnail key's name */
97
+ $name = sprintf( __( '%1$s (%2$sx%3$s)', 'yarpp' ), $key, $_size['width'], $_size['height'] );
98
+ $this->radio( 'thumbnail_size_display', $name, '', $key );
99
+ }
100
+ echo '</div></div>';
101
+ echo '</div>';
102
+ echo '<div class="generate_missing_thumbnails">';
103
+ $this->checkbox( 'generate_missing_thumbnails', __( 'Generate missing thumbnail sizes: ', 'yarpp' ) . "<span class='yarpp_help dashicons dashicons-editor-help' data-help='" . '<p>' . esc_attr( __( 'When enabled, missing thumbnail sizes will be automatically generated on the fly. Doing this type of processing on the fly may not scale well for larger sites.', 'yarpp' ) ) . '</p><p>' . sprintf( __( 'For larger sites, we recommend the %1$s or %2$s to generate missing thumbnail sizes in a batch process.', 'yarpp' ), '<a href="https://wordpress.org/plugins/regenerate-thumbnails/" target="_blank">Regenerate Thumbnails plugin</a>', '<a href="https://developer.wordpress.org/cli/commands/media/regenerate/" target="_blank">WP-CLI</a>' ) . '</p><p>' . esc_attr( __( 'New images should continue to automatically get all active thumbnail sizes generated when they are uploaded.', 'yarpp' ) ) . '</p>' . "'>&nbsp;</span>&nbsp;&nbsp;", 'yarpp', $yarpp_args );
104
+ echo '</div>';
105
+ echo "<div class='yarpp_subbox template_options_builtin'";
106
+ if ( $choice != 'builtin' ) {
107
+ echo ' style="display: none;"';
108
+ }
109
+ echo '>';
110
+ $this->beforeafter( array( 'before_related', 'after_related' ), __( 'Before / after related entries:', 'yarpp' ), 15, '', __( 'For example:', 'yarpp' ) . ' &lt;ol&gt;&lt;/ol&gt;' . __( ' or ', 'yarpp' ) . '&lt;div&gt;&lt;/div&gt;' );
111
+ $this->beforeafter( array( 'before_title', 'after_title' ), __( 'Before / after each related entry:', 'yarpp' ), 15, '', __( 'For example:', 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
112
 
113
+ $this->checkbox( 'show_excerpt', __( 'Show excerpt?', 'yarpp' ), 'show_excerpt' );
114
+ $this->textbox( 'excerpt_length', __( 'Excerpt length (No. of words):', 'yarpp' ), 10, 'excerpted' );
115
 
116
+ $this->beforeafter( array( 'before_post', 'after_post' ), __( 'Before / after (excerpt):', 'yarpp' ), 10, 'excerpted', __( 'For example:', 'yarpp' ) . ' &lt;li&gt;&lt;/li&gt;' . __( ' or ', 'yarpp' ) . '&lt;dl&gt;&lt;/dl&gt;' );
117
+ echo '</div>';
 
118
 
119
+ echo '<div class="yarpp_no_results">';
120
+ $this->textbox( 'no_results', __( 'Default display if no results:', 'yarpp' ), 40, 'sync_no_results' );
121
+ echo '</div>';
122
 
123
+ // Close the div that wraps all the options
124
+ echo '</div>';
125
+
126
+ $this->displayorder( 'order' );
127
+ $this->checkbox( 'promote_yarpp', __( 'Link to YARPP?', 'yarpp' ) . " <span class='yarpp_help dashicons dashicons-editor-help' data-help='" . esc_attr( sprintf( __( 'This option will add the code %s These links are greatly appreciated and keeps us motivated.', 'yarpp' ), '<code>' . htmlspecialchars( sprintf( __( "Powered by <a href='%s' title='WordPress Related Posts Plugin' target='_blank'>YARPP</a>.", 'yarpp' ), 'https://yarpp.com' ) ) . '</code>' ) ) . "'>&nbsp;</span>", 'yarpp' );
128
+ }
129
+ }
classes/YARPP_Meta_Box_Optin.php CHANGED
@@ -1,30 +1,29 @@
1
  <?php
2
 
3
  class YARPP_Meta_Box_Optin extends YARPP_Meta_Box {
4
- public function display() {
5
- $output =
6
- '<p>'.
7
- 'Enable the free <a href="https://yarpp.com" target="_blank">YARPP Pro enhancements</a> to add even '.
8
- 'more power to your blog or website!'.
9
- '<br/><br/>'.
10
- '<a class="yarpp_switch_button button" data-go="pro">Turn them on now</a>&nbsp;&nbsp;'.
11
- '<a href="https://yarpp.com" target="_blank" style="float:right;text-decoration:underline">Learn more</a>'.
12
- '</p>'.
13
- '<p>'.
14
- 'We can continue to improve the YARPP product for you if we know how it&#39;s used. Please help us by '.
15
- 'allowing usage data to be sent back.'.
16
- '<br/>'.
17
- '</p>'.
18
- '<input
19
  type="checkbox"
20
  id="yarpp-optin"
21
  name="optin"
22
- value="true" '.
23
- checked(yarpp_get_option('optin') == 1 ,true, false).' '.
24
- '/>'.
25
- '<label for="yarpp-optin">Send usage data back.</label>'.
26
- '<a href="#" id="yarpp-optin-learnmore" style="float:right;text-decoration:underline">Learn More</a>'
27
- ;
28
- echo $output;
29
- }
30
- }
1
  <?php
2
 
3
  class YARPP_Meta_Box_Optin extends YARPP_Meta_Box {
4
+ public function display() {
5
+ $output =
6
+ '<p>' .
7
+ 'Enable the free <a href="https://yarpp.com" target="_blank">YARPP Pro enhancements</a> to add even ' .
8
+ 'more power to your blog or website!' .
9
+ '<br/><br/>' .
10
+ '<a class="yarpp_switch_button button" data-go="pro">Turn them on now</a>&nbsp;&nbsp;' .
11
+ '<a href="https://yarpp.com" target="_blank" style="float:right;text-decoration:underline">Learn more</a>' .
12
+ '</p>' .
13
+ '<p>' .
14
+ 'We can continue to improve the YARPP product for you if we know how it&#39;s used. Please help us by ' .
15
+ 'allowing usage data to be sent back.' .
16
+ '<br/>' .
17
+ '</p>' .
18
+ '<input
19
  type="checkbox"
20
  id="yarpp-optin"
21
  name="optin"
22
+ value="true" ' .
23
+ checked( yarpp_get_option( 'optin' ) == 1, true, false ) . ' ' .
24
+ '/>' .
25
+ '<label for="yarpp-optin">Send usage data back.</label>' .
26
+ '<a href="#" id="yarpp-optin-learnmore" style="float:right;text-decoration:underline">Learn More</a>';
27
+ echo $output;
28
+ }
29
+ }
 
classes/YARPP_Meta_Box_Pool.php CHANGED
@@ -1,32 +1,32 @@
1
  <?php
2
 
3
  class YARPP_Meta_Box_Pool extends YARPP_Meta_Box {
4
- public function exclude($taxonomy, $string, $_builtin = true) {
5
  global $yarpp;
6
 
7
  echo "<div class='yarpp_form_row yarpp_form_exclude'><div class='yarpp_form_label'>";
8
  echo $string;
9
- if ($_builtin == false) {
10
- echo " <span class='yarpp_help dashicons dashicons-info' data-help='" . esc_attr( __( "This belongs to a custom taxonomy", 'yarpp' ) ) . "'></span>";
11
  }
12
  echo "</div><div class='yarpp_scroll_wrapper'><div class='exclude_terms' id='exclude_{$taxonomy}'>";
13
 
14
- $exclude_tt_ids = wp_parse_id_list( yarpp_get_option( 'exclude' ) );
15
- $exclude_term_ids = $yarpp->admin->get_term_ids_from_tt_ids($taxonomy, $exclude_tt_ids);
16
  if ( count( $exclude_term_ids ) ) {
17
  $terms = get_terms(
18
  array(
19
- 'taxonomy' => $taxonomy,
20
- 'include' => $exclude_term_ids,
21
- 'hide_empty' => false
22
  )
23
  );
24
  foreach ( $terms as $term ) {
25
- echo "<input type='checkbox' name='exclude[{$term->term_taxonomy_id}]' id='exclude_{$term->term_taxonomy_id}' value='true' checked='checked' /> <label for='exclude_{$term->term_taxonomy_id}'>" . esc_html( $term->name ) . "</label> ";
26
  }
27
  }
28
 
29
- echo "</div></div></div>";
30
  }
31
  /**
32
  * Displays the "include post type" input's HTML.
@@ -46,25 +46,25 @@ class YARPP_Meta_Box_Pool extends YARPP_Meta_Box {
46
  $post_types = $yarpp->get_post_types( 'objects' );
47
  foreach ( $post_types as $post_type ) {
48
  $post_type_title = $post_type->labels->name;
49
- // Clarify "topics" are from bbPress plugin
50
- if( $post_type->name == 'topic' && class_exists( 'bbPress' ) ) {
51
- $post_type_title = sprintf(
52
- __('BuddyPress %s', 'yarpp'),
53
- $post_type_title
54
- );
55
- }
56
- echo "<input data-post-type='{$post_type->name}' type='checkbox' " . checked( in_array( $post_type->name, $include_post_type_array, true ), 1, false ) . " name='include_post_type[{$post_type->name}]' id='include_post_type_{$post_type->name}' value='true' /> <label for='include_post_type_{$post_type->name}'>" . esc_html( $post_type_title ) . "</label> ";
57
  }
58
- echo "</div></div></div>";
59
  }
60
  public function display() {
61
  global $yarpp;
62
- $postTypeHelpMsg =
63
- 'If you don&#39;t want one of these post types to display as related content, '.
64
- 'uncheck the appropriate box in the &ldquo;Display Options&rdquo; panel below. Make sure you '.
65
- 'click the &ldquo;Save Changes button&rdquo; at the bottom of this page.';
66
 
67
- include(YARPP_DIR.'/includes/phtmls/yarpp_meta_box_pool.phtml');
68
  }
69
 
70
- }
1
  <?php
2
 
3
  class YARPP_Meta_Box_Pool extends YARPP_Meta_Box {
4
+ public function exclude( $taxonomy, $string, $_builtin = true ) {
5
  global $yarpp;
6
 
7
  echo "<div class='yarpp_form_row yarpp_form_exclude'><div class='yarpp_form_label'>";
8
  echo $string;
9
+ if ( $_builtin == false ) {
10
+ echo " <span class='yarpp_help dashicons dashicons-info' data-help='" . esc_attr( __( 'This belongs to a custom taxonomy', 'yarpp' ) ) . "'></span>";
11
  }
12
  echo "</div><div class='yarpp_scroll_wrapper'><div class='exclude_terms' id='exclude_{$taxonomy}'>";
13
 
14
+ $exclude_tt_ids = wp_parse_id_list( yarpp_get_option( 'exclude' ) );
15
+ $exclude_term_ids = $yarpp->admin->get_term_ids_from_tt_ids( $taxonomy, $exclude_tt_ids );
16
  if ( count( $exclude_term_ids ) ) {
17
  $terms = get_terms(
18
  array(
19
+ 'taxonomy' => $taxonomy,
20
+ 'include' => $exclude_term_ids,
21
+ 'hide_empty' => false,
22
  )
23
  );
24
  foreach ( $terms as $term ) {
25
+ echo "<input type='checkbox' name='exclude[{$term->term_taxonomy_id}]' id='exclude_{$term->term_taxonomy_id}' value='true' checked='checked' /> <label for='exclude_{$term->term_taxonomy_id}'>" . esc_html( $term->name ) . '</label> ';
26
  }
27
  }
28
 
29
+ echo '</div></div></div>';
30
  }
31
  /**
32
  * Displays the "include post type" input's HTML.
46
  $post_types = $yarpp->get_post_types( 'objects' );
47
  foreach ( $post_types as $post_type ) {
48
  $post_type_title = $post_type->labels->name;
49
+ // Clarify "topics" are from bbPress plugin
50
+ if ( $post_type->name == 'topic' && class_exists( 'bbPress' ) ) {
51
+ $post_type_title = sprintf(
52
+ __( 'BuddyPress %s', 'yarpp' ),
53
+ $post_type_title
54
+ );
55
+ }
56
+ echo "<input data-post-type='{$post_type->name}' type='checkbox' " . checked( in_array( $post_type->name, $include_post_type_array, true ), 1, false ) . " name='include_post_type[{$post_type->name}]' id='include_post_type_{$post_type->name}' value='true' /> <label for='include_post_type_{$post_type->name}'>" . esc_html( $post_type_title ) . '</label> ';
57
  }
58
+ echo '</div></div></div>';
59
  }
60
  public function display() {
61
  global $yarpp;
62
+ $postTypeHelpMsg =
63
+ 'If you don&#39;t want one of these post types to display as related content, ' .
64
+ 'uncheck the appropriate box in the &ldquo;Display Options&rdquo; panel below. Make sure you ' .
65
+ 'click the &ldquo;Save Changes button&rdquo; at the bottom of this page.';
66
 
67
+ include YARPP_DIR . '/includes/phtmls/yarpp_meta_box_pool.phtml';
68
  }
69
 
70
+ }
classes/YARPP_Meta_Box_Relatedness.php CHANGED
@@ -29,13 +29,13 @@ class YARPP_Meta_Box_Relatedness extends YARPP_Meta_Box {
29
  <div class='yarpp-callout yarpp-notice'>
30
  <p>
31
  <?php
32
- esc_html_e('Comparing posts based on Titles or Bodies is currently disabled', 'yarpp');
33
  ?>
34
  &nbsp;&nbsp;<a href="#" id="yarpp_fulltext_expand">
35
  <?php
36
  printf(
37
  // translators: icon to expand
38
- __('Show Details %s', 'yarpp'),
39
  '[+]'
40
  );
41
  ?>
@@ -45,7 +45,7 @@ class YARPP_Meta_Box_Relatedness extends YARPP_Meta_Box {
45
  <p>
46
  <?php
47
  printf(
48
- esc_html__('Because full-text indexing is not supported by your current table engine, "%1$s", YARPP cannot compare posts based on their Titles or Bodies.', 'yarpp'),
49
  'InnoDB',
50
  '5.6.4',
51
  '<code>' . $wpdb->posts . '</code>',
@@ -56,7 +56,7 @@ class YARPP_Meta_Box_Relatedness extends YARPP_Meta_Box {
56
  <p>
57
  <?php
58
  printf(
59
- esc_html__('Please contact your host about updating MySQL to at latest version %1$s, or run the following SQL code on your MySQL client (eg PHPMyAdmin) or terminal:', 'yarpp'),
60
  '5.6.4'
61
  );
62
  ?>
@@ -64,7 +64,7 @@ class YARPP_Meta_Box_Relatedness extends YARPP_Meta_Box {
64
  <p>
65
  <?php
66
  printf(
67
- esc_html__('See MySQL %1$sstorage engines%2$s documentation for details on MySQL engines.', 'yarpp'),
68
  '<a href="https://dev.mysql.com/doc/refman/8.0/en/storage-engines.html" target="_blank">',
69
  '</a>'
70
  );
@@ -73,32 +73,32 @@ class YARPP_Meta_Box_Relatedness extends YARPP_Meta_Box {
73
  </div>
74
  </div>
75
  <?php
76
- } elseif ($yarpp->diagnostic_big_db() && ( ! $yarpp->db_schema->title_column_has_index() || ! $yarpp->db_schema->content_column_has_index() )) {
77
  // it's a big database. So while we *can* automatically add indexes, we need to warn the site owner.
78
  ?>
79
  <div class='yarpp-callout yarpp-notice'>
80
- <p><strong><?php esc_html_e('Enabling comparisons using Titles or Bodies requires adding "fulltext indexes" to the posts table.', 'yarpp'); ?></strong>
81
  <a href="#" id="yarpp_fulltext_expand">
82
  <?php
83
  printf(
84
  // translators: icon to expand
85
- __('Show Details %s', 'yarpp'),
86
  '[+]'
87
  );
88
  ?>
89
  </a>
90
  </p>
91
  <div id="yarpp_fulltext_details" class="hidden">
92
- <p><?php esc_html_e('"Fulltext indexes" will improve YARPP’s algorithm but may affect performance.', 'yarpp'); ?></p>
93
- <p><?php esc_html_e('You have a large database and so adding them may take several minutes and cause the website to become unresponsive during this time. We recommend performing this action during off-peak hours.', 'yarpp'); ?></p>
94
- <p><?php esc_html_e('Please make a database backup before attempting this, and consider adding the indexes manually by running the following queries:', 'yarpp'); ?></p>
95
  <p>
96
- <span class="dashicons <?php echo ( $yarpp->db_schema->content_column_has_index() === true ) ? 'dashicons-yes': 'dashicons-clock'; ?>"></span>
97
  <code>
98
  ALTER TABLE <?php echo $wpdb->posts; ?> ADD FULLTEXT `yarpp_content` (`post_content`);
99
  </code>
100
  <br/>
101
- <span class="dashicons <?php echo ( $yarpp->db_schema->title_column_has_index() === true ) ? 'dashicons-yes': 'dashicons-clock'; ?>"></span>
102
  <code>
103
  ALTER TABLE <?php echo $wpdb->posts; ?> ADD FULLTEXT `yarpp_title` (`post_title`);
104
  </code>
29
  <div class='yarpp-callout yarpp-notice'>
30
  <p>
31
  <?php
32
+ esc_html_e( 'Comparing posts based on Titles or Bodies is currently disabled', 'yarpp' );
33
  ?>
34
  &nbsp;&nbsp;<a href="#" id="yarpp_fulltext_expand">
35
  <?php
36
  printf(
37
  // translators: icon to expand
38
+ __( 'Show Details %s', 'yarpp' ),
39
  '[+]'
40
  );
41
  ?>
45
  <p>
46
  <?php
47
  printf(
48
+ esc_html__( 'Because full-text indexing is not supported by your current table engine, "%1$s", YARPP cannot compare posts based on their Titles or Bodies.', 'yarpp' ),
49
  'InnoDB',
50
  '5.6.4',
51
  '<code>' . $wpdb->posts . '</code>',
56
  <p>
57
  <?php
58
  printf(
59
+ esc_html__( 'Please contact your host about updating MySQL to at latest version %1$s, or run the following SQL code on your MySQL client (eg PHPMyAdmin) or terminal:', 'yarpp' ),
60
  '5.6.4'
61
  );
62
  ?>
64
  <p>
65
  <?php
66
  printf(
67
+ esc_html__( 'See MySQL %1$sstorage engines%2$s documentation for details on MySQL engines.', 'yarpp' ),
68
  '<a href="https://dev.mysql.com/doc/refman/8.0/en/storage-engines.html" target="_blank">',
69
  '</a>'
70
  );
73
  </div>
74
  </div>
75
  <?php
76
+ } elseif ( $yarpp->diagnostic_big_db() && ( ! $yarpp->db_schema->title_column_has_index() || ! $yarpp->db_schema->content_column_has_index() ) ) {
77
  // it's a big database. So while we *can* automatically add indexes, we need to warn the site owner.
78
  ?>
79
  <div class='yarpp-callout yarpp-notice'>
80
+ <p><strong><?php esc_html_e( 'Enabling comparisons using Titles or Bodies requires adding "fulltext indexes" to the posts table.', 'yarpp' ); ?></strong>
81
  <a href="#" id="yarpp_fulltext_expand">
82
  <?php
83
  printf(
84
  // translators: icon to expand
85
+ __( 'Show Details %s', 'yarpp' ),
86
  '[+]'
87
  );
88
  ?>
89
  </a>
90
  </p>
91
  <div id="yarpp_fulltext_details" class="hidden">
92
+ <p><?php esc_html_e( '"Fulltext indexes" will improve YARPP’s algorithm but may affect performance.', 'yarpp' ); ?></p>
93
+ <p><?php esc_html_e( 'You have a large database and so adding them may take several minutes and cause the website to become unresponsive during this time. We recommend performing this action during off-peak hours.', 'yarpp' ); ?></p>
94
+ <p><?php esc_html_e( 'Please make a database backup before attempting this, and consider adding the indexes manually by running the following queries:', 'yarpp' ); ?></p>
95
  <p>
96
+ <span class="dashicons <?php echo ( $yarpp->db_schema->content_column_has_index() === true ) ? 'dashicons-yes' : 'dashicons-clock'; ?>"></span>
97
  <code>
98
  ALTER TABLE <?php echo $wpdb->posts; ?> ADD FULLTEXT `yarpp_content` (`post_content`);
99
  </code>
100
  <br/>
101
+ <span class="dashicons <?php echo ( $yarpp->db_schema->title_column_has_index() === true ) ? 'dashicons-yes' : 'dashicons-clock'; ?>"></span>
102
  <code>
103
  ALTER TABLE <?php echo $wpdb->posts; ?> ADD FULLTEXT `yarpp_title` (`post_title`);
104
  </code>
classes/YARPP_Rest_Api.php CHANGED
@@ -6,8 +6,8 @@
6
  class YARPP_Rest_Api extends WP_REST_Controller {
7
 
8
  public function __construct() {
9
- add_action('rest_api_init', array($this, 'register_api_routes'));
10
- add_filter('wp_rest_cache/allowed_endpoints', array($this,'cache_endpoints'), 10, 1);
11
  }
12
 
13
  /**
@@ -21,25 +21,29 @@ class YARPP_Rest_Api extends WP_REST_Controller {
21
  function register_api_routes() {
22
  global $yarpp;
23
 
24
- if ($yarpp->get_option('rest_api_display')) {
25
  $NAMESPACE = 'yarpp/v1';
26
-
27
  /* Register the yarpp rest route */
28
- register_rest_route( $NAMESPACE, '/related/(?P<id>[\w-]+)', array(
 
 
29
  array(
30
- 'methods' => WP_REST_Server::READABLE,
31
- 'callback' => array($this,'get_related_posts'),
32
- 'permission_callback' => array( $this, 'get_item_permissions_check' ),
33
- 'args' => $this->get_related_posts_args()
34
- ),
35
- 'args' => array(
36
- 'id' => array(
37
- 'description' => __( 'Unique identifier for the object.' ),
38
- 'type' => 'integer',
39
  ),
40
- ),
41
- 'schema' => array( $this, 'get_public_item_schema' ),
42
- ));
 
 
 
 
 
 
43
  }
44
  }
45
 
@@ -49,12 +53,12 @@ class YARPP_Rest_Api extends WP_REST_Controller {
49
  * @return array
50
  */
51
  public function get_public_item_schema() {
52
- $posts_schema = $this->get_posts_controller('post')->get_public_item_schema();
53
  $posts_schema['properties']['score'] = array(
54
- 'description' => __('YARPP relatedness score', 'yarpp'),
55
- 'type' => 'number',
56
- 'context' => array('view', 'edit', 'embed'),
57
- 'readonly' => true,
58
  );
59
  return $posts_schema;
60
  }
@@ -64,23 +68,23 @@ class YARPP_Rest_Api extends WP_REST_Controller {
64
  *
65
  * @return WP_Error
66
  */
67
- public function get_item_permissions_check( $request) {
68
  $error_response = new WP_Error(
69
  'rest_forbidden_context',
70
  __( 'Sorry, you are not allowed to read this post.', 'yarpp' ),
71
  array( 'status' => rest_authorization_required_code() )
72
  );
73
- $post_obj = get_post($request->get_param('id'));
74
- if (! $this->get_posts_controller($post_obj->post_type)->check_read_permission($post_obj)) {
75
  return $error_response;
76
  }
77
 
78
- $core_permissions_check = $this->get_posts_controller()->get_items_permissions_check($request);
79
- if ($core_permissions_check instanceof WP_Error) {
80
  return $core_permissions_check;
81
  }
82
  // Check for password-protected posts.
83
- if ( !empty($post_obj->post_password) && ! $this->get_posts_controller()->can_access_password_content( $post_obj, $request ) ) {
84
  return $error_response;
85
  }
86
  return true;
@@ -99,38 +103,38 @@ class YARPP_Rest_Api extends WP_REST_Controller {
99
  global $yarpp;
100
 
101
  return array(
102
- 'limit' => array(
103
- 'description' => esc_html('Number of posts to display', 'yarpp'),
104
- 'type' => 'integer',
105
- 'default' => $yarpp->get_option('limit'),
106
  'validate_callback' => 'rest_validate_request_arg',
107
  'sanitize_callback' => 'absint',
108
- 'minimum' => 1,
109
- 'maximum' => apply_filters(
110
  'yarpp_rest_api_get_related_posts_args_limit_maximum',
111
  20
112
- )
113
  ),
114
- 'context' => array_replace_recursive(
115
  $this->get_context_param(),
116
  array(
117
- 'default' => 'embed'
118
  )
119
  ),
120
  'password' => array(
121
  'description' => __( 'The password for the post if it is password protected.' ),
122
  'type' => 'string',
123
- )
124
  );
125
  }
126
-
127
  /**
128
  * Gets related posts provided a id param exists.
129
  *
130
  * @param WP_REST_REQUEST $request Incoming HTTP request data.
131
  * @return WP_Error|WP_HTTP_Response
132
  */
133
- public function get_related_posts( $request) {
134
  /**
135
  * @var $yarpp YARPP
136
  */
@@ -139,16 +143,16 @@ class YARPP_Rest_Api extends WP_REST_Controller {
139
  $query_params = $request->get_params();
140
  $id = $query_params['id'];
141
 
142
- $post_obj = get_post($id);
143
- if (! $post_obj instanceof WP_Post) {
144
- return new WP_Error('rest_invalid_id', esc_html__( 'Invalid Id', 'yarpp' ), array('status' => 404));
145
  }
146
- $allowed_args = array('limit');
147
 
148
  $args = array_filter(
149
  $query_params,
150
- function( $key) use ( $allowed_args) {
151
- return in_array($key, $allowed_args);
152
  },
153
  ARRAY_FILTER_USE_KEY
154
  );
@@ -160,47 +164,47 @@ class YARPP_Rest_Api extends WP_REST_Controller {
160
  // Great, we have the posts we want. But they're formatted totally differently than the WP REST API endpoints
161
  // So we use the core WP_RESTS_Posts_Controller to get the response in exactly the same format.
162
  $ids = wp_list_pluck( $related_posts, 'ID' );
163
- $read_controller = $this->get_posts_controller($post_obj->post_type);
164
  $simulated_request = clone $request;
165
- $simulated_request->set_route('wp/v1/posts');
166
 
167
  $simulated_params = array(
168
- 'include' => $ids,
169
- 'per_page' =>$query_params['limit'],
170
  // we only get one page at a time. WP page numbering starts at 1.
171
- 'page' => 1
172
  );
173
- if (isset($query_params['context'])) {
174
  $simulated_params['context'] = $query_params['context'];
175
  }
176
 
177
- $simulated_request->set_query_params($simulated_params);
178
 
179
  // Hack the WordPress Posts controller to return posts of all types, so long as they have the IDs we want.
180
- add_action( 'rest_' . $post_obj->post_type . '_query', array($this, 'ignore_post_type_filter_callback'), 10, 2 );
181
- $read_controller_response = $read_controller->get_items($simulated_request);
182
- remove_action( 'rest_' . $post_obj->post_type . '_query', array($this, 'ignore_post_type_filter_callback'), 10, 2 );
183
 
184
- if (is_wp_error($read_controller_response)) {
185
  return $read_controller_response;
186
  }
187
  $read_controller_posts = $read_controller_response->get_data();
188
  $ordered_rest_results = array();
189
  // Reorder the posts in the response according to what they were in the YARPP response.
190
- foreach ($related_posts as $related_post) {
191
- foreach ($read_controller_posts as $read_controller_post) {
192
- if ($related_post->ID === $read_controller_post['id']) {
193
  // Add score, but before _links.
194
  $links = $read_controller_post['_links'];
195
- unset($read_controller_post['_links']);
196
  $read_controller_post['score'] = (float) $related_post->score;
197
  $read_controller_post['_links'] = $links;
198
  $ordered_rest_results[] = $read_controller_post;
199
  }
200
  }
201
  }
202
- $read_controller_response->set_data($ordered_rest_results);
203
- $this->maybe_set_caching_headers($read_controller_response);
204
  return $read_controller_response;
205
  }
206
 
@@ -209,14 +213,14 @@ class YARPP_Rest_Api extends WP_REST_Controller {
209
  *
210
  * @param WP_Rest_Response $response
211
  */
212
- protected function maybe_set_caching_headers( WP_Rest_Response $response) {
213
  global $yarpp;
214
- if ($yarpp->get_option('rest_api_client_side_caching')) {
215
- $seconds_to_cache = (int) $yarpp->get_option('yarpp_rest_api_cache_time') * MINUTE_IN_SECONDS;
216
- $seconds_to_cache = max($seconds_to_cache, 0); // ensure non-negative values
217
- $ts = gmdate('D, d M Y H:i:s', time() + $seconds_to_cache) . ' GMT';
218
- $response->header('Expires', $ts);
219
- $response->header('Cache-Control', "public, max-age=$seconds_to_cache");
220
  }
221
  }
222
 
@@ -225,9 +229,9 @@ class YARPP_Rest_Api extends WP_REST_Controller {
225
  *
226
  * @return WP_REST_Posts_Controller
227
  */
228
- protected function get_posts_controller( $post_type = null) {
229
- if ( ! $this->posts_controller instanceof WP_REST_Posts_Controller) {
230
- $this->posts_controller = new WP_REST_Posts_Controller($post_type);
231
  }
232
  return $this->posts_controller;
233
  }
@@ -236,8 +240,8 @@ class YARPP_Rest_Api extends WP_REST_Controller {
236
  * Register the /wp-json/yarpp/v1/related for caching with https://wordpress.org/plugins/wp-rest-cache/
237
  */
238
  function cache_endpoints( $allowed_endpoints ) {
239
- if ( ! isset( $allowed_endpoints[ 'yarpp/v1' ] ) || ! in_array( 'related', $allowed_endpoints[ 'yarpp/v1' ] ) ) {
240
- $allowed_endpoints[ 'yarpp/v1' ][] = 'related';
241
  }
242
  return $allowed_endpoints;
243
  }
6
  class YARPP_Rest_Api extends WP_REST_Controller {
7
 
8
  public function __construct() {
9
+ add_action( 'rest_api_init', array( $this, 'register_api_routes' ) );
10
+ add_filter( 'wp_rest_cache/allowed_endpoints', array( $this, 'cache_endpoints' ), 10, 1 );
11
  }
12
 
13
  /**
21
  function register_api_routes() {
22
  global $yarpp;
23
 
24
+ if ( $yarpp->get_option( 'rest_api_display' ) ) {
25
  $NAMESPACE = 'yarpp/v1';
26
+
27
  /* Register the yarpp rest route */
28
+ register_rest_route(
29
+ $NAMESPACE,
30
+ '/related/(?P<id>[\w-]+)',
31
  array(
32
+ array(
33
+ 'methods' => WP_REST_Server::READABLE,
34
+ 'callback' => array( $this, 'get_related_posts' ),
35
+ 'permission_callback' => array( $this, 'get_item_permissions_check' ),
36
+ 'args' => $this->get_related_posts_args(),
 
 
 
 
37
  ),
38
+ 'args' => array(
39
+ 'id' => array(
40
+ 'description' => __( 'Unique identifier for the object.' ),
41
+ 'type' => 'integer',
42
+ ),
43
+ ),
44
+ 'schema' => array( $this, 'get_public_item_schema' ),
45
+ )
46
+ );
47
  }
48
  }
49
 
53
  * @return array
54
  */
55
  public function get_public_item_schema() {
56
+ $posts_schema = $this->get_posts_controller( 'post' )->get_public_item_schema();
57
  $posts_schema['properties']['score'] = array(
58
+ 'description' => __( 'YARPP relatedness score', 'yarpp' ),
59
+ 'type' => 'number',
60
+ 'context' => array( 'view', 'edit', 'embed' ),
61
+ 'readonly' => true,
62
  );
63
  return $posts_schema;
64
  }
68
  *
69
  * @return WP_Error
70
  */
71
+ public function get_item_permissions_check( $request ) {
72
  $error_response = new WP_Error(
73
  'rest_forbidden_context',
74
  __( 'Sorry, you are not allowed to read this post.', 'yarpp' ),
75
  array( 'status' => rest_authorization_required_code() )
76
  );
77
+ $post_obj = get_post( $request->get_param( 'id' ) );
78
+ if ( ! $this->get_posts_controller( $post_obj->post_type )->check_read_permission( $post_obj ) ) {
79
  return $error_response;
80
  }
81
 
82
+ $core_permissions_check = $this->get_posts_controller()->get_items_permissions_check( $request );
83
+ if ( $core_permissions_check instanceof WP_Error ) {
84
  return $core_permissions_check;
85
  }
86
  // Check for password-protected posts.
87
+ if ( ! empty( $post_obj->post_password ) && ! $this->get_posts_controller()->can_access_password_content( $post_obj, $request ) ) {
88
  return $error_response;
89
  }
90
  return true;
103
  global $yarpp;
104
 
105
  return array(
106
+ 'limit' => array(
107
+ 'description' => esc_html( 'Number of posts to display', 'yarpp' ),
108
+ 'type' => 'integer',
109
+ 'default' => $yarpp->get_option( 'limit' ),
110
  'validate_callback' => 'rest_validate_request_arg',
111
  'sanitize_callback' => 'absint',
112
+ 'minimum' => 1,
113
+ 'maximum' => apply_filters(
114
  'yarpp_rest_api_get_related_posts_args_limit_maximum',
115
  20
116
+ ),
117
  ),
118
+ 'context' => array_replace_recursive(
119
  $this->get_context_param(),
120
  array(
121
+ 'default' => 'embed',
122
  )
123
  ),
124
  'password' => array(
125
  'description' => __( 'The password for the post if it is password protected.' ),
126
  'type' => 'string',
127
+ ),
128
  );
129
  }
130
+
131
  /**
132
  * Gets related posts provided a id param exists.
133
  *
134
  * @param WP_REST_REQUEST $request Incoming HTTP request data.
135
  * @return WP_Error|WP_HTTP_Response
136
  */
137
+ public function get_related_posts( $request ) {
138
  /**
139
  * @var $yarpp YARPP
140
  */
143
  $query_params = $request->get_params();
144
  $id = $query_params['id'];
145
 
146
+ $post_obj = get_post( $id );
147
+ if ( ! $post_obj instanceof WP_Post ) {
148
+ return new WP_Error( 'rest_invalid_id', esc_html__( 'Invalid Id', 'yarpp' ), array( 'status' => 404 ) );
149
  }
150
+ $allowed_args = array( 'limit' );
151
 
152
  $args = array_filter(
153
  $query_params,
154
+ function( $key ) use ( $allowed_args ) {
155
+ return in_array( $key, $allowed_args );
156
  },
157
  ARRAY_FILTER_USE_KEY
158
  );
164
  // Great, we have the posts we want. But they're formatted totally differently than the WP REST API endpoints
165
  // So we use the core WP_RESTS_Posts_Controller to get the response in exactly the same format.
166
  $ids = wp_list_pluck( $related_posts, 'ID' );
167
+ $read_controller = $this->get_posts_controller( $post_obj->post_type );
168
  $simulated_request = clone $request;
169
+ $simulated_request->set_route( 'wp/v1/posts' );
170
 
171
  $simulated_params = array(
172
+ 'include' => $ids,
173
+ 'per_page' => $query_params['limit'],
174
  // we only get one page at a time. WP page numbering starts at 1.
175
+ 'page' => 1,
176
  );
177
+ if ( isset( $query_params['context'] ) ) {
178
  $simulated_params['context'] = $query_params['context'];
179
  }
180
 
181
+ $simulated_request->set_query_params( $simulated_params );
182
 
183
  // Hack the WordPress Posts controller to return posts of all types, so long as they have the IDs we want.
184
+ add_action( 'rest_' . $post_obj->post_type . '_query', array( $this, 'ignore_post_type_filter_callback' ), 10, 2 );
185
+ $read_controller_response = $read_controller->get_items( $simulated_request );
186
+ remove_action( 'rest_' . $post_obj->post_type . '_query', array( $this, 'ignore_post_type_filter_callback' ), 10, 2 );
187
 
188
+ if ( is_wp_error( $read_controller_response ) ) {
189
  return $read_controller_response;
190
  }
191
  $read_controller_posts = $read_controller_response->get_data();
192
  $ordered_rest_results = array();
193
  // Reorder the posts in the response according to what they were in the YARPP response.
194
+ foreach ( $related_posts as $related_post ) {
195
+ foreach ( $read_controller_posts as $read_controller_post ) {
196
+ if ( $related_post->ID === $read_controller_post['id'] ) {
197
  // Add score, but before _links.
198
  $links = $read_controller_post['_links'];
199
+ unset( $read_controller_post['_links'] );
200
  $read_controller_post['score'] = (float) $related_post->score;
201
  $read_controller_post['_links'] = $links;
202
  $ordered_rest_results[] = $read_controller_post;
203
  }
204
  }
205
  }
206
+ $read_controller_response->set_data( $ordered_rest_results );
207
+ $this->maybe_set_caching_headers( $read_controller_response );
208
  return $read_controller_response;
209
  }
210
 
213
  *
214
  * @param WP_Rest_Response $response
215
  */
216
+ protected function maybe_set_caching_headers( WP_Rest_Response $response ) {
217
  global $yarpp;
218
+ if ( $yarpp->get_option( 'rest_api_client_side_caching' ) ) {
219
+ $seconds_to_cache = (int) $yarpp->get_option( 'yarpp_rest_api_cache_time' ) * MINUTE_IN_SECONDS;
220
+ $seconds_to_cache = max( $seconds_to_cache, 0 ); // ensure non-negative values.
221
+ $ts = gmdate( 'D, d M Y H:i:s', time() + $seconds_to_cache ) . ' GMT';
222
+ $response->header( 'Expires', $ts );
223
+ $response->header( 'Cache-Control', "public, max-age=$seconds_to_cache" );
224
  }
225
  }
226
 
229
  *
230
  * @return WP_REST_Posts_Controller
231
  */
232
+ protected function get_posts_controller( $post_type = null ) {
233
+ if ( ! $this->posts_controller instanceof WP_REST_Posts_Controller ) {
234
+ $this->posts_controller = new WP_REST_Posts_Controller( $post_type );
235
  }
236
  return $this->posts_controller;
237
  }
240
  * Register the /wp-json/yarpp/v1/related for caching with https://wordpress.org/plugins/wp-rest-cache/
241
  */
242
  function cache_endpoints( $allowed_endpoints ) {
243
+ if ( ! isset( $allowed_endpoints['yarpp/v1'] ) || ! in_array( 'related', $allowed_endpoints['yarpp/v1'] ) ) {
244
+ $allowed_endpoints['yarpp/v1'][] = 'related';
245
  }
246
  return $allowed_endpoints;
247
  }
classes/YARPP_Shortcode.php CHANGED
@@ -13,7 +13,7 @@ class YARPP_Shortcode {
13
  public function register() {
14
  add_shortcode(
15
  'yarpp',
16
- array($this,'render')
17
  );
18
  }
19
 
@@ -22,46 +22,47 @@ class YARPP_Shortcode {
22
  *
23
  * @return string
24
  */
25
- public function render( $atts) {
26
  $atts = shortcode_atts(
27
  array(
28
  'reference_id' => null,
29
- 'template' => null,
30
- 'limit' => null
31
  ),
32
  $atts
33
  );
34
  /** @global $yarpp YARPP */
35
  global $yarpp;
36
- $post = get_post((int) $atts['reference_id']);
37
  $yarpp_args = array(
38
- 'domain' => 'shortcode'
39
  );
40
-
41
- // Custom templates require .php extension
42
- if (isset($atts['template']) && $atts['template']) {
43
- // Normalize parameter
44
- $yarpp_args['template'] = trim($atts['template']);
45
- if (( strpos($yarpp_args['template'], 'yarpp-template-') === 0 ) && ( strpos($yarpp_args['template'], '.php') === false )) {
46
  $yarpp_args['template'] .= '.php';
47
  }
48
  }
49
-
50
- if (isset($atts['limit']) && $atts['limit']) {
51
- // Normalize parameter
52
- $atts['limit'] = trim($atts['limit']);
53
-
54
- // Use only if numeric value is passed
55
- if (is_numeric($atts['limit'])) {
56
  $yarpp_args['limit'] = (int) $atts['limit'];
57
  }
58
  }
59
-
60
- if ($post instanceof WP_Post) {
61
  return $yarpp->display_related(
62
  $post->ID,
63
  $yarpp_args,
64
- false);
 
65
  } else {
66
  return '<!-- YARPP shortcode called but no reference post found. It was probably called outside "the loop" or the reference_id provided was invalid.-->';
67
  }
13
  public function register() {
14
  add_shortcode(
15
  'yarpp',
16
+ array( $this, 'render' )
17
  );
18
  }
19
 
22
  *
23
  * @return string
24
  */
25
+ public function render( $atts ) {
26
  $atts = shortcode_atts(
27
  array(
28
  'reference_id' => null,
29
+ 'template' => null,
30
+ 'limit' => null,
31
  ),
32
  $atts
33
  );
34
  /** @global $yarpp YARPP */
35
  global $yarpp;
36
+ $post = get_post( (int) $atts['reference_id'] );
37
  $yarpp_args = array(
38
+ 'domain' => 'shortcode',
39
  );
40
+
41
+ // Custom templates require .php extension.
42
+ if ( isset( $atts['template'] ) && $atts['template'] ) {
43
+ // Normalize parameter.
44
+ $yarpp_args['template'] = trim( $atts['template'] );
45
+ if ( ( strpos( $yarpp_args['template'], 'yarpp-template-' ) === 0 ) && ( strpos( $yarpp_args['template'], '.php' ) === false ) ) {
46
  $yarpp_args['template'] .= '.php';
47
  }
48
  }
49
+
50
+ if ( isset( $atts['limit'] ) && $atts['limit'] ) {
51
+ // Normalize parameter.
52
+ $atts['limit'] = trim( $atts['limit'] );
53
+
54
+ // Use only if numeric value is passed.
55
+ if ( is_numeric( $atts['limit'] ) ) {
56
  $yarpp_args['limit'] = (int) $atts['limit'];
57
  }
58
  }
59
+
60
+ if ( $post instanceof WP_Post ) {
61
  return $yarpp->display_related(
62
  $post->ID,
63
  $yarpp_args,
64
+ false
65
+ );
66
  } else {
67
  return '<!-- YARPP shortcode called but no reference post found. It was probably called outside "the loop" or the reference_id provided was invalid.-->';
68
  }
classes/YARPP_Widget.php CHANGED
@@ -1,82 +1,92 @@
1
  <?php
2
- /*
3
  * Vaguely based on code by MK Safi
4
  * http://msafi.com/fix-yet-another-related-posts-plugin-yarpp-widget-and-add-it-to-the-sidebar/
5
  */
6
  class YARPP_Widget extends WP_Widget {
7
 
8
  public function __construct() {
9
- parent::__construct(false, 'Related Posts (YARPP)', array('description' => 'Related Posts and/or Sponsored Content'));
10
  }
11
 
12
- public function widget($args, $instance) {
13
- if (!is_singular()) return;
 
 
14
 
15
  global $yarpp;
16
- extract($args);
17
 
18
  /* Compatibility with pre-3.5 settings: */
19
- if (isset($instance['use_template'])) {
20
- $instance['template'] = ($instance['use_template']) ? ($instance['template_file']) : false;
21
- }
22
-
23
- $title = apply_filters('widget_title', $instance['title']);
24
- $output = $before_widget;
25
- if (!$instance['template']) {
26
- $output .= $before_title;
27
- $output .= $title;
28
- $output .= $after_title;
29
- }
30
- $instance['domain'] = 'widget';
31
- $output .= $yarpp->display_related(null, $instance, false);
32
- $output .= $after_widget;
33
- echo $output;
34
  }
35
 
36
- public function update($new_instance, $old_instance) {
37
- $instance = array(
38
- 'template' => false,
39
- 'title' => $new_instance['title'],
40
- 'thumbnails_heading' => $new_instance['thumbnails_heading'],
41
- 'use_pro' => false,
42
- 'pro_dpid' => null,
43
- 'promote_yarpp' => false,
44
- );
45
-
46
- if ($new_instance['use_template'] === 'thumbnails') $instance['template'] = 'thumbnails';
47
- else if ($new_instance['use_template'] === 'custom' ) $instance['template'] = $new_instance['template_file'];
48
-
 
 
 
49
  return $instance;
50
  }
51
 
52
- public function form($instance) {
53
  global $yarpp;
54
- $id = rtrim($this->get_field_id(null), '-');
55
  $instance = wp_parse_args(
56
- $instance,
57
- array(
58
- 'title' => 'Related Posts (YARPP)',
59
- 'thumbnails_heading' => $yarpp->get_option('thumbnails_heading'),
60
- 'template' => false,
61
- 'use_pro' => false,
62
- 'pro_dpid' => null,
63
- 'promote_yarpp' => false,
64
- )
65
- );
66
-
67
- /* TODO: Deprecate
 
68
  * Compatibility with pre-3.5 settings
69
  */
70
- if (isset($instance['use_template'])) $instance['template'] = $instance['template_file'];
71
-
72
- $choice = ($instance['template']) ? (($instance['template'] === 'thumbnails') ? 'thumbnails' : 'custom') : 'builtin';
 
 
73
 
74
  /* Check if YARPP templates are installed */
75
  $templates = $yarpp->get_templates();
76
 
77
- if (!$yarpp->diagnostic_custom_templates() && $choice === 'custom') $choice = 'builtin';
 
 
78
 
79
- include(YARPP_DIR.'/includes/phtmls/yarpp_widget_form.phtml');
80
  }
81
  }
82
 
@@ -84,7 +94,7 @@ class YARPP_Widget extends WP_Widget {
84
  * @since 2.0 Add as a widget
85
  */
86
  function yarpp_widget_init() {
87
- register_widget('YARPP_Widget');
88
  }
89
 
90
- add_action('widgets_init', 'yarpp_widget_init');
1
  <?php
2
+ /**
3
  * Vaguely based on code by MK Safi
4
  * http://msafi.com/fix-yet-another-related-posts-plugin-yarpp-widget-and-add-it-to-the-sidebar/
5
  */
6
  class YARPP_Widget extends WP_Widget {
7
 
8
  public function __construct() {
9
+ parent::__construct( false, 'Related Posts (YARPP)', array( 'description' => 'Related Posts and/or Sponsored Content' ) );
10
  }
11
 
12
+ public function widget( $args, $instance ) {
13
+ if ( ! is_singular() ) {
14
+ return;
15
+ }
16
 
17
  global $yarpp;
18
+ extract( $args );
19
 
20
  /* Compatibility with pre-3.5 settings: */
21
+ if ( isset( $instance['use_template'] ) ) {
22
+ $instance['template'] = ( $instance['use_template'] ) ? ( $instance['template_file'] ) : false;
23
+ }
24
+
25
+ $title = apply_filters( 'widget_title', $instance['title'] );
26
+ $output = $before_widget;
27
+ if ( ! $instance['template'] ) {
28
+ $output .= $before_title;
29
+ $output .= $title;
30
+ $output .= $after_title;
31
+ }
32
+ $instance['domain'] = 'widget';
33
+ $output .= $yarpp->display_related( null, $instance, false );
34
+ $output .= $after_widget;
35
+ echo $output;
36
  }
37
 
38
+ public function update( $new_instance, $old_instance ) {
39
+ $instance = array(
40
+ 'template' => false,
41
+ 'title' => $new_instance['title'],
42
+ 'thumbnails_heading' => $new_instance['thumbnails_heading'],
43
+ 'use_pro' => false,
44
+ 'pro_dpid' => null,
45
+ 'promote_yarpp' => false,
46
+ );
47
+
48
+ if ( $new_instance['use_template'] === 'thumbnails' ) {
49
+ $instance['template'] = 'thumbnails';
50
+ } elseif ( $new_instance['use_template'] === 'custom' ) {
51
+ $instance['template'] = $new_instance['template_file'];
52
+ }
53
+
54
  return $instance;
55
  }
56
 
57
+ public function form( $instance ) {
58
  global $yarpp;
59
+ $id = rtrim( $this->get_field_id( null ), '-' );
60
  $instance = wp_parse_args(
61
+ $instance,
62
+ array(
63
+ 'title' => 'Related Posts (YARPP)',
64
+ 'thumbnails_heading' => $yarpp->get_option( 'thumbnails_heading' ),
65
+ 'template' => false,
66
+ 'use_pro' => false,
67
+ 'pro_dpid' => null,
68
+ 'promote_yarpp' => false,
69
+ )
70
+ );
71
+
72
+ /*
73
+ * TODO: Deprecate
74
  * Compatibility with pre-3.5 settings
75
  */
76
+ if ( isset( $instance['use_template'] ) ) {
77
+ $instance['template'] = $instance['template_file'];
78
+ }
79
+
80
+ $choice = ( $instance['template'] ) ? ( ( $instance['template'] === 'thumbnails' ) ? 'thumbnails' : 'custom' ) : 'builtin';
81
 
82
  /* Check if YARPP templates are installed */
83
  $templates = $yarpp->get_templates();
84
 
85
+ if ( ! $yarpp->diagnostic_custom_templates() && $choice === 'custom' ) {
86
+ $choice = 'builtin';
87
+ }
88
 
89
+ include YARPP_DIR . '/includes/phtmls/yarpp_widget_form.phtml';
90
  }
91
  }
92
 
94
  * @since 2.0 Add as a widget
95
  */
96
  function yarpp_widget_init() {
97
+ register_widget( 'YARPP_Widget' );
98
  }
99
 
100
+ add_action( 'widgets_init', 'yarpp_widget_init' );
includes/init_functions.php CHANGED
@@ -2,21 +2,21 @@
2
 
3
  function yarpp_init() {
4
  global $yarpp;
5
- $yarpp = new YARPP;
6
  }
7
 
8
- function yarpp_plugin_activate($network_wide) {
9
- update_option('yarpp_activated', true);
10
  }
11
 
12
- function yarpp_set_option($options, $value = null) {
13
  global $yarpp;
14
- $yarpp->set_option($options, $value);
15
  }
16
 
17
- function yarpp_get_option($option = null) {
18
  global $yarpp;
19
- return $yarpp->get_option($option);
20
  }
21
  /**
22
  * Get user selected thumbnail size.
@@ -86,7 +86,7 @@ function yarpp_get_image_sizes( $size = '' ) {
86
  $sizes[ $_size ] = array(
87
  'width' => $wp_additional_image_sizes[ $_size ]['width'],
88
  'height' => $wp_additional_image_sizes[ $_size ]['height'],
89
- 'crop' => $wp_additional_image_sizes[ $_size ]['crop']
90
  );
91
  }
92
  }
2
 
3
  function yarpp_init() {
4
  global $yarpp;
5
+ $yarpp = new YARPP();
6
  }
7
 
8
+ function yarpp_plugin_activate( $network_wide ) {
9
+ update_option( 'yarpp_activated', true );
10
  }
11
 
12
+ function yarpp_set_option( $options, $value = null ) {
13
  global $yarpp;
14
+ $yarpp->set_option( $options, $value );
15
  }
16
 
17
+ function yarpp_get_option( $option = null ) {
18
  global $yarpp;
19
+ return $yarpp->get_option( $option );
20
  }
21
  /**
22
  * Get user selected thumbnail size.
86
  $sizes[ $_size ] = array(
87
  'width' => $wp_additional_image_sizes[ $_size ]['width'],
88
  'height' => $wp_additional_image_sizes[ $_size ]['height'],
89
+ 'crop' => $wp_additional_image_sizes[ $_size ]['crop'],
90
  );
91
  }
92
  }
includes/optin_notice.js.php CHANGED
@@ -1,23 +1,23 @@
1
  <script type='text/javascript'>
2
- jQuery(function($){
3
- $(document.body).on('click', '#yarpp-optin-button', function(){
4
- $(this).closest('p').find('.button').attr('disabled',true);
5
- $('#yarpp-optin').attr('checked', true);
6
- $.ajax({
7
- type:'POST',
8
- url : ajaxurl,
9
- data: {
10
- action: 'yarpp_optin_<?php echo $optinAction?>',
11
- '_ajax_nonce': $('#yarpp_optin-nonce').val()
12
- },
13
- success: yarppRedirectAdmin
14
- });
15
- });
16
- });
17
 
18
- function yarppRedirectAdmin(resp){
19
- if (resp === 'ok'){
20
- window.location.href = 'options-general.php?page=yarpp';
21
- }
22
- }
23
- </script>
1
  <script type='text/javascript'>
2
+ jQuery(function($){
3
+ $(document.body).on('click', '#yarpp-optin-button', function(){
4
+ $(this).closest('p').find('.button').attr('disabled',true);
5
+ $('#yarpp-optin').attr('checked', true);
6
+ $.ajax({
7
+ type:'POST',
8
+ url : ajaxurl,
9
+ data: {
10
+ action: 'yarpp_optin_<?php echo $optinAction; ?>',
11
+ '_ajax_nonce': $('#yarpp_optin-nonce').val()
12
+ },
13
+ success: yarppRedirectAdmin
14
+ });
15
+ });
16
+ });
17
 
18
+ function yarppRedirectAdmin(resp){
19
+ if (resp === 'ok'){
20
+ window.location.href = 'options-general.php?page=yarpp';
21
+ }
22
+ }
23
+ </script>
includes/related_functions.php CHANGED
@@ -1,182 +1,185 @@
1
  <?php
2
- /*---------------------------------------------------------------------------------------------------------------------
 
3
  Here are the related_WHATEVER functions, as introduced in 1.1.
4
  Since YARPP 2.1, these functions receive (optionally) one array argument.
5
  ----------------------------------------------------------------------------------------------------------------------*/
6
 
7
  /**
8
  * Gets the HTML for displaying related posts.
9
- * @param array $args
10
- * @param int $reference_ID the post ID to search against. If used from within "the loop", defaults to the
11
- * $current_post
12
- * @param bool $echo if false only returns the HTML string
 
13
  * @return string HTML output
14
  */
15
- function yarpp_related($args = array(), $reference_ID = false, $echo = true) {
16
  global $yarpp;
17
 
18
- if (is_array($reference_ID)){
19
- _doing_it_wrong( __FUNCTION__, "This YARPP function now takes \$args first and \$reference_ID second.", '3.5');
20
  return;
21
  }
22
-
23
- return $yarpp->display_related($reference_ID, $args, $echo);
24
  }
25
 
26
  /**
27
  * Whether there are any related posts.
28
- * @param array $args
29
- * @param int $reference_ID the post ID to search against. If used from within "the loop", defaults to the
30
- * $current_post
 
31
  * @return bool
32
  */
33
- function yarpp_related_exist($args = array(), $reference_ID = false) {
34
  global $yarpp;
35
 
36
- if (is_array($reference_ID)) {
37
- _doing_it_wrong( __FUNCTION__, "This YARPP function now takes \$args first and \$reference_ID second.", '3.5');
38
  return;
39
  }
40
-
41
- return $yarpp->related_exist($reference_ID, $args);
42
  }
43
 
44
  /**
45
  * Gets an array of related posts.
46
  *
47
- * @param array $args
48
- * @param int $reference_ID the post ID to search against. If used from within "the loop", defaults to the
49
- * $current_post
50
  *
51
  * @return WP_Post[]
52
  */
53
- function yarpp_get_related($args = array(), $reference_ID = false) {
54
  global $yarpp;
55
- return $yarpp->get_related($reference_ID, $args);
56
  }
57
 
58
  /**
59
  * @deprecated 5.12.0 use yarpp_related instead
60
  *
61
  * @param array $args
62
- * @param bool $reference_ID
63
- * @param bool $echo
64
  */
65
- function related_posts($args = array(), $reference_ID = false, $echo = true) {
66
- _deprecated_function('related_posts','5.12.0', 'yarpp_related');
67
- global $yarpp;
68
 
69
- if ( false !== $reference_ID && is_bool($reference_ID) ) {
70
- _doing_it_wrong( __FUNCTION__, "This YARPP function now takes \$args first and \$reference_ID second.", '3.5');
71
  return;
72
  }
73
 
74
- if ($yarpp->get_option('cross_relate')) {
75
  $args['post_type'] = $yarpp->get_post_types();
76
- } else {
77
- $args['post_type'] = array('post');
78
- }
79
 
80
- return yarpp_related($args, $reference_ID, $echo);
81
  }
82
 
83
  /**
84
  *
85
  * @deprecated since 5.12.0 use yarpp_related() instead
86
  * @param array $args
87
- * @param bool $reference_ID
88
- * @param bool $echo
89
  * @return array
90
  */
91
- function related_pages($args = array(), $reference_ID = false, $echo = true) {
92
- _deprecated_function('related_pages','5.12.0', 'yarpp_related');
93
- global $yarpp;
94
 
95
- if (false !== $reference_ID && is_bool($reference_ID)) {
96
- _doing_it_wrong( __FUNCTION__, "This YARPP function now takes \$args first and \$reference_ID second.", '3.5');
97
  return;
98
  }
99
 
100
- if ($yarpp->get_option('cross_relate')) {
101
  $args['post_type'] = $yarpp->get_post_types();
102
- } else {
103
- $args['post_type'] = array('page');
104
- }
105
 
106
- return yarpp_related($args, $reference_ID, $echo);
107
  }
108
 
109
  /**
110
  * @deprecated since 5.12.0 use yarpp_related() instead
111
  * @param array $args
112
- * @param int $reference_ID
113
- * @param bool $echo
114
  *
115
  * @return string|void
116
  */
117
- function related_entries($args = array(), $reference_ID = false, $echo = true) {
118
- _deprecated_function('related_entries','5.12.0', 'yarpp_related');
119
- global $yarpp;
120
 
121
- if (false !== $reference_ID && is_bool($reference_ID)) {
122
- _doing_it_wrong( __FUNCTION__, "This YARPP function now takes \$args first and \$reference_ID second.", '3.5');
123
  return;
124
  }
125
 
126
- $args['post_type'] = $yarpp->get_post_types();
127
 
128
- return yarpp_related($args, $reference_ID, $echo);
129
  }
130
 
131
  /**
132
  * @deprecated since 5.12.0 use yarpp_related_exist() instead
133
  * @param array $args
134
- * @param int $reference_ID
135
  *
136
  * @return bool
137
  */
138
- function related_posts_exist($args = array(), $reference_ID = false) {
139
- _deprecated_function('related_posts_exist','5.12.0', 'yarpp_related_exist');
140
  global $yarpp;
141
 
142
- if ($yarpp->get_option('cross_relate')) {
143
  $args['post_type'] = $yarpp->get_post_types();
144
- } else {
145
- $args['post_type'] = array('post');
146
- }
147
 
148
- return yarpp_related_exist($args, $reference_ID);
149
  }
150
 
151
  /**
152
  * @deprecated since 5.12.0 use yarpp_related_exist() instead
153
  * @param array $args
154
- * @param bool $reference_ID
155
  *
156
  * @return bool
157
  */
158
- function related_pages_exist($args = array(), $reference_ID = false) {
159
- _deprecated_function('related_pages_exist','5.12.0', 'yarpp_related_exist');
160
  global $yarpp;
161
 
162
- if ($yarpp->get_option('cross_relate')) {
163
  $args['post_type'] = $yarpp->get_post_types();
164
- } else {
165
  $args['post_type'] = array( 'page' );
166
- }
167
-
168
  return yarpp_related_exist( $args, $reference_ID );
169
  }
170
 
171
  /**
172
  * @deprecated since 5.12.0 use yarpp_related_exist() instead
173
  * @param array $args
174
- * @param bool $reference_ID
175
  *
176
  * @return bool
177
  */
178
- function related_entries_exist($args = array(),$reference_ID = false) {
179
- _deprecated_function('related_entries_exist','5.12.0', 'yarpp_related_exist');
180
  global $yarpp;
181
 
182
  $args['post_type'] = $yarpp->get_post_types();
1
  <?php
2
+ /*
3
+ ---------------------------------------------------------------------------------------------------------------------
4
  Here are the related_WHATEVER functions, as introduced in 1.1.
5
  Since YARPP 2.1, these functions receive (optionally) one array argument.
6
  ----------------------------------------------------------------------------------------------------------------------*/
7
 
8
  /**
9
  * Gets the HTML for displaying related posts.
10
+ *
11
+ * @param array $args see readme.txt installation tab's "YARPP functions()" section
12
+ * @param int $reference_ID the post ID to search against. If used from within "the loop", defaults to the
13
+ * $current_post
14
+ * @param bool $echo if false only returns the HTML string
15
  * @return string HTML output
16
  */
17
+ function yarpp_related( $args = array(), $reference_ID = false, $echo = true ) {
18
  global $yarpp;
19
 
20
+ if ( is_array( $reference_ID ) ) {
21
+ _doing_it_wrong( __FUNCTION__, 'This YARPP function now takes $args first and $reference_ID second.', '3.5' );
22
  return;
23
  }
24
+
25
+ return $yarpp->display_related( $reference_ID, $args, $echo );
26
  }
27
 
28
  /**
29
  * Whether there are any related posts.
30
+ *
31
+ * @param array $args see readme.txt installation tab's "YARPP functions()" section
32
+ * @param int $reference_ID the post ID to search against. If used from within "the loop", defaults to the
33
+ * $current_post
34
  * @return bool
35
  */
36
+ function yarpp_related_exist( $args = array(), $reference_ID = false ) {
37
  global $yarpp;
38
 
39
+ if ( is_array( $reference_ID ) ) {
40
+ _doing_it_wrong( __FUNCTION__, 'This YARPP function now takes $args first and $reference_ID second.', '3.5' );
41
  return;
42
  }
43
+
44
+ return $yarpp->related_exist( $reference_ID, $args );
45
  }
46
 
47
  /**
48
  * Gets an array of related posts.
49
  *
50
+ * @param array $args see readme.txt installation tab's "YARPP functions()" section
51
+ * @param int $reference_ID the post ID to search against. If used from within "the loop", defaults to the
52
+ * $current_post
53
  *
54
  * @return WP_Post[]
55
  */
56
+ function yarpp_get_related( $args = array(), $reference_ID = false ) {
57
  global $yarpp;
58
+ return $yarpp->get_related( $reference_ID, $args );
59
  }
60
 
61
  /**
62
  * @deprecated 5.12.0 use yarpp_related instead
63
  *
64
  * @param array $args
65
+ * @param bool $reference_ID
66
+ * @param bool $echo
67
  */
68
+ function related_posts( $args = array(), $reference_ID = false, $echo = true ) {
69
+ _deprecated_function( 'related_posts', '5.12.0', 'yarpp_related' );
70
+ global $yarpp;
71
 
72
+ if ( false !== $reference_ID && is_bool( $reference_ID ) ) {
73
+ _doing_it_wrong( __FUNCTION__, 'This YARPP function now takes $args first and $reference_ID second.', '3.5' );
74
  return;
75
  }
76
 
77
+ if ( $yarpp->get_option( 'cross_relate' ) ) {
78
  $args['post_type'] = $yarpp->get_post_types();
79
+ } else {
80
+ $args['post_type'] = array( 'post' );
81
+ }
82
 
83
+ return yarpp_related( $args, $reference_ID, $echo );
84
  }
85
 
86
  /**
87
  *
88
  * @deprecated since 5.12.0 use yarpp_related() instead
89
  * @param array $args
90
+ * @param bool $reference_ID
91
+ * @param bool $echo
92
  * @return array
93
  */
94
+ function related_pages( $args = array(), $reference_ID = false, $echo = true ) {
95
+ _deprecated_function( 'related_pages', '5.12.0', 'yarpp_related' );
96
+ global $yarpp;
97
 
98
+ if ( false !== $reference_ID && is_bool( $reference_ID ) ) {
99
+ _doing_it_wrong( __FUNCTION__, 'This YARPP function now takes $args first and $reference_ID second.', '3.5' );
100
  return;
101
  }
102
 
103
+ if ( $yarpp->get_option( 'cross_relate' ) ) {
104
  $args['post_type'] = $yarpp->get_post_types();
105
+ } else {
106
+ $args['post_type'] = array( 'page' );
107
+ }
108
 
109
+ return yarpp_related( $args, $reference_ID, $echo );
110
  }
111
 
112
  /**
113
  * @deprecated since 5.12.0 use yarpp_related() instead
114
  * @param array $args
115
+ * @param int $reference_ID
116
+ * @param bool $echo
117
  *
118
  * @return string|void
119
  */
120
+ function related_entries( $args = array(), $reference_ID = false, $echo = true ) {
121
+ _deprecated_function( 'related_entries', '5.12.0', 'yarpp_related' );
122
+ global $yarpp;
123
 
124
+ if ( false !== $reference_ID && is_bool( $reference_ID ) ) {
125
+ _doing_it_wrong( __FUNCTION__, 'This YARPP function now takes $args first and $reference_ID second.', '3.5' );
126
  return;
127
  }
128
 
129
+ $args['post_type'] = $yarpp->get_post_types();
130
 
131
+ return yarpp_related( $args, $reference_ID, $echo );
132
  }
133
 
134
  /**
135
  * @deprecated since 5.12.0 use yarpp_related_exist() instead
136
  * @param array $args
137
+ * @param int $reference_ID
138
  *
139
  * @return bool
140
  */
141
+ function related_posts_exist( $args = array(), $reference_ID = false ) {
142
+ _deprecated_function( 'related_posts_exist', '5.12.0', 'yarpp_related_exist' );
143
  global $yarpp;
144
 
145
+ if ( $yarpp->get_option( 'cross_relate' ) ) {
146
  $args['post_type'] = $yarpp->get_post_types();
147
+ } else {
148
+ $args['post_type'] = array( 'post' );
149
+ }
150
 
151
+ return yarpp_related_exist( $args, $reference_ID );
152
  }
153
 
154
  /**
155
  * @deprecated since 5.12.0 use yarpp_related_exist() instead
156
  * @param array $args
157
+ * @param bool $reference_ID
158
  *
159
  * @return bool
160
  */
161
+ function related_pages_exist( $args = array(), $reference_ID = false ) {
162
+ _deprecated_function( 'related_pages_exist', '5.12.0', 'yarpp_related_exist' );
163
  global $yarpp;
164
 
165
+ if ( $yarpp->get_option( 'cross_relate' ) ) {
166
  $args['post_type'] = $yarpp->get_post_types();
167
+ } else {
168
  $args['post_type'] = array( 'page' );
169
+ }
170
+
171
  return yarpp_related_exist( $args, $reference_ID );
172
  }
173
 
174
  /**
175
  * @deprecated since 5.12.0 use yarpp_related_exist() instead
176
  * @param array $args
177
+ * @param bool $reference_ID
178
  *
179
  * @return bool
180
  */
181
+ function related_entries_exist( $args = array(), $reference_ID = false ) {
182
+ _deprecated_function( 'related_entries_exist', '5.12.0', 'yarpp_related_exist' );
183
  global $yarpp;
184
 
185
  $args['post_type'] = $yarpp->get_post_types();
includes/template_builtin.php CHANGED
@@ -8,54 +8,54 @@
8
  */
9
 
10
  $options = array(
11
- 'before_title',
12
- 'after_title',
13
- 'show_excerpt',
14
- 'excerpt_length',
15
- 'before_post',
16
- 'after_post',
17
- 'before_related',
18
- 'after_related',
19
- 'no_results'
20
- );
21
-
22
- extract($this->parse_args($args, $options));
23
-
24
- if (have_posts()) {
25
- $output .= '<!-- YARPP List -->'."\n";
26
- $output .= $before_related."\n";
27
-
28
- while (have_posts()) {
29
  the_post();
30
- $link = get_permalink();
31
- $tooltip = esc_attr((get_the_title()) ? get_the_title() : get_the_ID());
32
- $title = get_the_title();
33
- $round = round(get_the_score(),1);
34
- $score = (current_user_can('manage_options') && $domain !== 'rss' && !is_admin())
35
- ? '<abbr title="'.sprintf(__('%f is the YARPP match score between the current entry and this related entry. You are seeing this value because you are logged in to WordPress as an administrator. It is not shown to regular visitors.','yarpp'),$round).'">('.$round.')</abbr>'
36
- : null;
37
 
38
  $output .=
39
- $before_title.
40
- '<a href="'.$link.'" rel="bookmark" title="'.$tooltip.'">'.
41
- $title.' '.$score.
42
- '</a>';
43
-
44
- if ($show_excerpt) {
45
- $excerpt = strip_tags((string) get_the_excerpt());
46
- preg_replace('/([,;.-]+)\s*/','\1 ', $excerpt);
47
- $excerpt = implode(' ', array_slice(preg_split('/\s+/',$excerpt), 0, $excerpt_length)).'...';
48
- $output .= $before_post.$excerpt.$after_post;
49
  }
50
-
51
- $output .= $after_title."\n";
52
 
53
  }
54
-
55
- $output .= $after_related."\n";
56
-
57
  } else {
58
-
59
  $output .= $no_results;
60
-
61
  }
8
  */
9
 
10
  $options = array(
11
+ 'before_title',
12
+ 'after_title',
13
+ 'show_excerpt',
14
+ 'excerpt_length',
15
+ 'before_post',
16
+ 'after_post',
17
+ 'before_related',
18
+ 'after_related',
19
+ 'no_results',
20
+ );
21
+
22
+ extract( $this->parse_args( $args, $options ) );
23
+
24
+ if ( have_posts() ) {
25
+ $output .= '<!-- YARPP List -->' . "\n";
26
+ $output .= $before_related . "\n";
27
+
28
+ while ( have_posts() ) {
29
  the_post();
30
+ $link = get_permalink();
31
+ $tooltip = esc_attr( ( get_the_title() ) ? get_the_title() : get_the_ID() );
32
+ $title = get_the_title();
33
+ $round = round( get_the_score(), 1 );
34
+ $score = ( current_user_can( 'manage_options' ) && $domain !== 'rss' && ! is_admin() )
35
+ ? '<abbr title="' . sprintf( __( '%f is the YARPP match score between the current entry and this related entry. You are seeing this value because you are logged in to WordPress as an administrator. It is not shown to regular visitors.', 'yarpp' ), $round ) . '">(' . $round . ')</abbr>'
36
+ : null;
37
 
38
  $output .=
39
+ $before_title .
40
+ '<a href="' . $link . '" rel="bookmark" title="' . $tooltip . '">' .
41
+ $title . ' ' . $score .
42
+ '</a>';
43
+
44
+ if ( $show_excerpt ) {
45
+ $excerpt = strip_tags( (string) get_the_excerpt() );
46
+ preg_replace( '/([,;.-]+)\s*/', '\1 ', $excerpt );
47
+ $excerpt = implode( ' ', array_slice( preg_split( '/\s+/', $excerpt ), 0, $excerpt_length ) ) . '...';
48
+ $output .= $before_post . $excerpt . $after_post;
49
  }
50
+
51
+ $output .= $after_title . "\n";
52
 
53
  }
54
+
55
+ $output .= $after_related . "\n";
56
+
57
  } else {
58
+
59
  $output .= $no_results;
60
+
61
  }
includes/template_functions.php CHANGED
@@ -10,7 +10,7 @@ function get_the_score() {
10
  global $post;
11
 
12
  $score = $post->score;
13
- return apply_filters('get_the_score', $score);
14
  }
15
  /**
16
  * Get Dynamic styles for YARPP's built-in thumbnails template
10
  global $post;
11
 
12
  $score = $post->score;
13
+ return apply_filters( 'get_the_score', $score );
14
  }
15
  /**
16
  * Get Dynamic styles for YARPP's built-in thumbnails template
includes/template_metabox.php CHANGED
@@ -1,34 +1,34 @@
1
  <?php
2
  global $yarpp;
3
 
4
- $yarpp->cache->enforce((int) $reference_ID, false); // enforce the cache, but don't force it
5
 
6
- if ($yarpp->debug) {
7
- $keywords = $yarpp->cache->get_keywords($reference_ID);
8
- $output .= "<p>body keywords: {$keywords['body']}</p>";
9
- $output .= "<p>title keywords: {$keywords['title']}</p>";
10
  }
11
 
12
- $output .= '<p><strong>'.__( 'Related Posts:' , 'yarpp').'</strong></p>';
13
 
14
- if ($yarpp->debug) {
15
- $output .= "<p>last updated: ".$wpdb->get_var("select max(date) as updated from {$wpdb->prefix}yarpp_related_cache where reference_ID = '$reference_ID'")."</p>";
16
  }
17
 
18
- if (have_posts()) {
19
  $output .= '<style>#yarpp-related-posts ol li { list-style-type: decimal; margin: 10px 0;} #yarpp-related-posts ol li a {text-decoration: none;} .yarpp-related-action {visibility: hidden;}</style>';
20
  $output .= '<ol id="yarpp-list">';
21
- while (have_posts()) {
22
  the_post();
23
- $output .= "<li id='yarpp-related-". get_the_ID() . "'><a class='row-title' href='post.php?action=edit&post=" . get_the_ID() . "'>" . get_the_title() . "</a>";
24
- $output .= ' (' . round(get_the_score(),3) . ')';
25
- $output .= " <span class='yarpp-related-action' id=yarpp-related-" . get_the_ID() . "-action'><span class='edit'><a href='post.php?action=edit&post=" . get_the_ID() . "'>" . __('Edit','yarpp') ."</a></span> | <span class='view'><a href='" . get_permalink() . "' target='_blank'>" . __('View', 'yarpp') . "</a></span></span>";
26
  $output .= '</li>';
27
  }
28
  $output .= '</ol>';
29
- $output .= '<p>'. __( 'Whether all matches are actually displayed and how they are displayed depends on your YARPP display options.' , 'yarpp') . ' ' . __('Updating the post may change the matches.','yarpp') . '</p>';
30
  } else {
31
- $output .= '<p><em>' . __('No related posts matched.','yarpp') . ' ' . __('Updating the post may change the matches.','yarpp') . '</em></p>';
32
  }
33
 
34
- $output .= '<p class="yarpp-metabox-options"><a href="' . esc_url(admin_url('options-general.php?page=yarpp')) . '" class="button-secondary">' . __('Configure Options', 'yarpp') . '</a> <a id="yarpp-refresh" href="#" class="button-secondary">' . __('Refresh', 'yarpp') . '</a><span class="spinner"></span></p>';
1
  <?php
2
  global $yarpp;
3
 
4
+ $yarpp->cache->enforce( (int) $reference_ID, false ); // enforce the cache, but don't force it
5
 
6
+ if ( $yarpp->debug ) {
7
+ $keywords = $yarpp->cache->get_keywords( $reference_ID );
8
+ $output .= "<p>body keywords: {$keywords['body']}</p>";
9
+ $output .= "<p>title keywords: {$keywords['title']}</p>";
10
  }
11
 
12
+ $output .= '<p><strong>' . __( 'Related Posts:', 'yarpp' ) . '</strong></p>';
13
 
14
+ if ( $yarpp->debug ) {
15
+ $output .= '<p>last updated: ' . $wpdb->get_var( "select max(date) as updated from {$wpdb->prefix}yarpp_related_cache where reference_ID = '$reference_ID'" ) . '</p>';
16
  }
17
 
18
+ if ( have_posts() ) {
19
  $output .= '<style>#yarpp-related-posts ol li { list-style-type: decimal; margin: 10px 0;} #yarpp-related-posts ol li a {text-decoration: none;} .yarpp-related-action {visibility: hidden;}</style>';
20
  $output .= '<ol id="yarpp-list">';
21
+ while ( have_posts() ) {
22
  the_post();
23
+ $output .= "<li id='yarpp-related-" . get_the_ID() . "'><a class='row-title' href='post.php?action=edit&post=" . get_the_ID() . "'>" . get_the_title() . '</a>';
24
+ $output .= ' (' . round( get_the_score(), 3 ) . ')';
25
+ $output .= " <span class='yarpp-related-action' id=yarpp-related-" . get_the_ID() . "-action'><span class='edit'><a href='post.php?action=edit&post=" . get_the_ID() . "'>" . __( 'Edit', 'yarpp' ) . "</a></span> | <span class='view'><a href='" . get_permalink() . "' target='_blank'>" . __( 'View', 'yarpp' ) . '</a></span></span>';
26
  $output .= '</li>';
27
  }
28
  $output .= '</ol>';
29
+ $output .= '<p>' . __( 'Whether all matches are actually displayed and how they are displayed depends on your YARPP display options.', 'yarpp' ) . ' ' . __( 'Updating the post may change the matches.', 'yarpp' ) . '</p>';
30
  } else {
31
+ $output .= '<p><em>' . __( 'No related posts matched.', 'yarpp' ) . ' ' . __( 'Updating the post may change the matches.', 'yarpp' ) . '</em></p>';
32
  }
33
 
34
+ $output .= '<p class="yarpp-metabox-options"><a href="' . esc_url( admin_url( 'options-general.php?page=yarpp' ) ) . '" class="button-secondary">' . __( 'Configure Options', 'yarpp' ) . '</a> <a id="yarpp-refresh" href="#" class="button-secondary">' . __( 'Refresh', 'yarpp' ) . '</a><span class="spinner"></span></p>';
includes/template_thumbnails.php CHANGED
@@ -8,41 +8,45 @@
8
  * More information on the custom templates is available at http://mitcho.com/blog/projects/yarpp-3-templates/
9
  */
10
 
11
- if ( !$this->diagnostic_using_thumbnails() )
12
  $this->set_option( 'manually_using_thumbnails', true );
 
13
 
14
  $options = array( 'thumbnails_heading', 'thumbnails_default', 'no_results' );
15
  extract( $this->parse_args( $args, $options ) );
16
 
17
  // a little easter egg: if the default image URL is left blank,
18
  // default to the theme's header image. (hopefully it has one)
19
- if ( empty($thumbnails_default) )
20
  $thumbnails_default = get_header_image();
 
21
 
22
  $dimensions = $this->thumbnail_dimensions();
23
 
24
- $output .= '<!-- YARPP Thumbnails -->'."\n";
25
 
26
  $output .= '<h3>' . $thumbnails_heading . '</h3>' . "\n";
27
 
28
- if (have_posts()) {
29
  $output .= '<div class="yarpp-thumbnails-horizontal">' . "\n";
30
- while (have_posts()) {
31
  the_post();
32
 
33
- $output .= "<a class='yarpp-thumbnail' rel='norewrite' href='" . get_permalink() . "' title='" . the_title_attribute('echo=0') . "'>" . "\n";
34
 
35
  $post_thumbnail_html = '';
36
  if ( has_post_thumbnail() ) {
37
- if ( $this->diagnostic_generate_thumbnails() )
38
  $this->ensure_resized_post_thumbnail( get_the_ID(), $dimensions );
39
- $post_thumbnail_html = get_the_post_thumbnail(null, $dimensions['size'], array('data-pin-nopin' => 'true') );
 
40
  }
41
-
42
- if ( trim($post_thumbnail_html) != '' )
43
  $output .= $post_thumbnail_html;
44
- else
45
- $output .= '<span class="yarpp-thumbnail-default"><img src="' . esc_url($thumbnails_default) . '" alt="Default Thumbnail" data-pin-nopin="true" /></span>';
 
46
 
47
  $output .= '<span class="yarpp-thumbnail-title">' . get_the_title() . '</span>';
48
  $output .= '</a>' . "\n";
8
  * More information on the custom templates is available at http://mitcho.com/blog/projects/yarpp-3-templates/
9
  */
10
 
11
+ if ( ! $this->diagnostic_using_thumbnails() ) {
12
  $this->set_option( 'manually_using_thumbnails', true );
13
+ }
14
 
15
  $options = array( 'thumbnails_heading', 'thumbnails_default', 'no_results' );
16
  extract( $this->parse_args( $args, $options ) );
17
 
18
  // a little easter egg: if the default image URL is left blank,
19
  // default to the theme's header image. (hopefully it has one)
20
+ if ( empty( $thumbnails_default ) ) {
21
  $thumbnails_default = get_header_image();
22
+ }
23
 
24
  $dimensions = $this->thumbnail_dimensions();
25
 
26
+ $output .= '<!-- YARPP Thumbnails -->' . "\n";
27
 
28
  $output .= '<h3>' . $thumbnails_heading . '</h3>' . "\n";
29
 
30
+ if ( have_posts() ) {
31
  $output .= '<div class="yarpp-thumbnails-horizontal">' . "\n";
32
+ while ( have_posts() ) {
33
  the_post();
34
 
35
+ $output .= "<a class='yarpp-thumbnail' rel='norewrite' href='" . get_permalink() . "' title='" . the_title_attribute( 'echo=0' ) . "'>" . "\n";
36
 
37
  $post_thumbnail_html = '';
38
  if ( has_post_thumbnail() ) {
39
+ if ( $this->diagnostic_generate_thumbnails() ) {
40
  $this->ensure_resized_post_thumbnail( get_the_ID(), $dimensions );
41
+ }
42
+ $post_thumbnail_html = get_the_post_thumbnail( null, $dimensions['size'], array( 'data-pin-nopin' => 'true' ) );
43
  }
44
+
45
+ if ( trim( $post_thumbnail_html ) != '' ) {
46
  $output .= $post_thumbnail_html;
47
+ } else {
48
+ $output .= '<span class="yarpp-thumbnail-default"><img src="' . esc_url( $thumbnails_default ) . '" alt="Default Thumbnail" data-pin-nopin="true" /></span>';
49
+ }
50
 
51
  $output .= '<span class="yarpp-thumbnail-title">' . get_the_title() . '</span>';
52
  $output .= '</a>' . "\n";
includes/template_widget.php CHANGED
@@ -1,14 +1,14 @@
1
  <?php
2
 
3
- if (have_posts()) {
4
  $output .= '<ol>';
5
- while (have_posts()) {
6
  the_post();
7
- $output .= '<li><a href="'.get_permalink().'" rel="bookmark">'.get_the_title().'</a>';
8
- // $output .= ' ('.round(get_the_score(),3).')';
9
  $output .= '</li>';
10
  }
11
  $output .= '</ol>';
12
  } else {
13
- $output .= '<p><em>'.__('No related posts.','yarpp').'</em></p>';
14
  }
1
  <?php
2
 
3
+ if ( have_posts() ) {
4
  $output .= '<ol>';
5
+ while ( have_posts() ) {
6
  the_post();
7
+ $output .= '<li><a href="' . get_permalink() . '" rel="bookmark">' . get_the_title() . '</a>';
8
+ // $output .= ' ('.round(get_the_score(),3).')';
9
  $output .= '</li>';
10
  }
11
  $output .= '</ol>';
12
  } else {
13
+ $output .= '<p><em>' . __( 'No related posts.', 'yarpp' ) . '</em></p>';
14
  }
includes/yarpp_meta_boxes_hooks.php CHANGED
@@ -1,81 +1,81 @@
1
  <?php
2
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box.php');
3
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Contact.php');
4
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Display_Feed.php');
5
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Display_Web.php');
6
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Optin.php');
7
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Pool.php');
8
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Relatedness.php');
9
- include_once(YARPP_DIR.'/classes/YARPP_Meta_Box_Display_Rest_Api.php');
10
 
11
  global $yarpp;
12
 
13
  add_meta_box(
14
- 'yarpp_pool',
15
- __( '"The Pool"', 'yarpp' ),
16
- array(new YARPP_Meta_Box_Pool, 'display'),
17
- 'settings_page_yarpp',
18
- 'normal',
19
- 'core'
20
  );
21
 
22
  add_meta_box(
23
- 'yarpp_relatedness',
24
- __( 'The Algorithm', 'yarpp' ),
25
- array(
26
- new YARPP_Meta_Box_Relatedness,
27
- 'display'
28
- ),
29
- 'settings_page_yarpp',
30
- 'normal',
31
- 'core'
32
  );
33
 
34
  add_meta_box(
35
- 'yarpp_display_web',
36
- __('Automatic Display Options', 'yarpp'),
37
- array(
38
- new YARPP_Meta_Box_Display_Web,
39
- 'display'
40
- ),
41
- 'settings_page_yarpp',
42
- 'normal',
43
- 'core'
44
  );
45
 
46
  add_meta_box(
47
- 'yarpp_display_contact',
48
- __('Contact YARPP', 'yarpp'),
49
- array(new YARPP_Meta_Box_Contact, 'display'),
50
- 'settings_page_yarpp',
51
- 'side',
52
- 'core'
53
  );
54
 
55
  add_meta_box(
56
- 'yarpp_display_rss',
57
- __('RSS Feed Options', 'yarpp'),
58
- array(
59
- new YARPP_Meta_Box_Display_Feed,
60
- 'display'
61
- ),
62
- 'settings_page_yarpp',
63
- 'normal',
64
- 'core'
65
  );
66
 
67
- if(
68
- apply_filters('rest_enabled', true) &&
69
- function_exists('register_rest_route') &&
70
- class_exists('WP_REST_Controller') &&
71
- class_exists('WP_REST_Posts_Controller')
72
- ){
73
  add_meta_box(
74
  'yarpp_display_api',
75
- __('REST API Options', 'yarpp'),
76
  array(
77
- new YARPP_Meta_Box_Display_Rest_Api,
78
- 'display'
79
  ),
80
  'settings_page_yarpp',
81
  'normal',
@@ -83,16 +83,17 @@ if(
83
  );
84
  }
85
 
86
- function yarpp_make_optin_classy($classes) {
87
- if (!yarpp_get_option('optin') )
88
  $classes[] = 'yarpp_attention';
 
89
  return $classes;
90
  }
91
 
92
  add_filter(
93
- "postbox_classes_settings_page_yarpp_yarpp_display_optin",
94
- 'yarpp_make_optin_classy'
95
  );
96
 
97
  /** @since 3.3: hook for registering new YARPP meta boxes */
98
- //do_action('add_meta_boxes_settings_page_yarpp');
1
  <?php
2
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box.php';
3
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Contact.php';
4
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Display_Feed.php';
5
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Display_Web.php';
6
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Optin.php';
7
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Pool.php';
8
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Relatedness.php';
9
+ require_once YARPP_DIR . '/classes/YARPP_Meta_Box_Display_Rest_Api.php';
10
 
11
  global $yarpp;
12
 
13
  add_meta_box(
14
+ 'yarpp_pool',
15
+ __( '"The Pool"', 'yarpp' ),
16
+ array( new YARPP_Meta_Box_Pool(), 'display' ),
17
+ 'settings_page_yarpp',
18
+ 'normal',
19
+ 'core'
20
  );
21
 
22
  add_meta_box(
23
+ 'yarpp_relatedness',
24
+ __( 'The Algorithm', 'yarpp' ),
25
+ array(
26
+ new YARPP_Meta_Box_Relatedness(),
27
+ 'display',
28
+ ),
29
+ 'settings_page_yarpp',
30
+ 'normal',
31
+ 'core'
32
  );
33
 
34
  add_meta_box(
35
+ 'yarpp_display_web',
36
+ __( 'Automatic Display Options', 'yarpp' ),
37
+ array(
38
+ new YARPP_Meta_Box_Display_Web(),
39
+ 'display',
40
+ ),
41
+ 'settings_page_yarpp',
42
+ 'normal',
43
+ 'core'
44
  );
45
 
46
  add_meta_box(
47
+ 'yarpp_display_contact',
48
+ __( 'Contact YARPP', 'yarpp' ),
49
+ array( new YARPP_Meta_Box_Contact(), 'display' ),
50
+ 'settings_page_yarpp',
51
+ 'side',
52
+ 'core'
53
  );
54
 
55
  add_meta_box(
56
+ 'yarpp_display_rss',
57
+ __( 'RSS Feed Options', 'yarpp' ),
58
+ array(
59
+ new YARPP_Meta_Box_Display_Feed(),
60
+ 'display',
61
+ ),
62
+ 'settings_page_yarpp',
63
+ 'normal',
64
+ 'core'
65
  );
66
 
67
+ if (
68
+ apply_filters( 'rest_enabled', true ) &&
69
+ function_exists( 'register_rest_route' ) &&
70
+ class_exists( 'WP_REST_Controller' ) &&
71
+ class_exists( 'WP_REST_Posts_Controller' )
72
+ ) {
73
  add_meta_box(
74
  'yarpp_display_api',
75
+ __( 'REST API Options', 'yarpp' ),
76
  array(
77
+ new YARPP_Meta_Box_Display_Rest_Api(),
78
+ 'display',
79
  ),
80
  'settings_page_yarpp',
81
  'normal',
83
  );
84
  }
85
 
86
+ function yarpp_make_optin_classy( $classes ) {
87
+ if ( ! yarpp_get_option( 'optin' ) ) {
88
  $classes[] = 'yarpp_attention';
89
+ }
90
  return $classes;
91
  }
92
 
93
  add_filter(
94
+ 'postbox_classes_settings_page_yarpp_yarpp_display_optin',
95
+ 'yarpp_make_optin_classy'
96
  );
97
 
98
  /** @since 3.3: hook for registering new YARPP meta boxes */
99
+ // do_action('add_meta_boxes_settings_page_yarpp');
includes/yarpp_myisam_notice.php CHANGED
@@ -3,18 +3,19 @@
3
  * @var $yarpp YARPP
4
  */
5
 
6
- if($yarpp->db_options->has_fulltext_db_error()){
7
- ?>
8
- <div class="notice notice-error" >
9
- <span class="yarpp-red"><?php esc_html_e('Full-text Index creation did not work!','yarpp');?></span><br/>
10
- <?php
11
- printf(
12
- esc_html__( 'There was an error adding the full-text index to your posts table: %s', 'yarpp' ),
13
- $yarpp->db_options->get_fulltext_db_error()
14
- );
15
- $yarpp->db_options->delete_fulltext_db_error_record();
16
- ?><br/>
17
- <?php esc_html_e( 'Titles and bodies still cannot be used as relatedness criteria.', 'yarpp' ); ?>
18
- </div>
19
- <?php
20
- }
 
3
  * @var $yarpp YARPP
4
  */
5
 
6
+ if ( $yarpp->db_options->has_fulltext_db_error() ) {
7
+ ?>
8
+ <div class="notice notice-error" >
9
+ <span class="yarpp-red"><?php esc_html_e( 'Full-text Index creation did not work!', 'yarpp' ); ?></span><br/>
10
+ <?php
11
+ printf(
12
+ esc_html__( 'There was an error adding the full-text index to your posts table: %s', 'yarpp' ),
13
+ $yarpp->db_options->get_fulltext_db_error()
14
+ );
15
+ $yarpp->db_options->delete_fulltext_db_error_record();
16
+ ?>
17
+ <br/>
18
+ <?php esc_html_e( 'Titles and bodies still cannot be used as relatedness criteria.', 'yarpp' ); ?>
19
+ </div>
20
+ <?php
21
+ }
includes/yarpp_options.php CHANGED
@@ -7,171 +7,186 @@
7
  global $wpdb, $wp_version, $yarpp;
8
 
9
  /* Check to see that templates are in the right place */
10
- if (!$yarpp->diagnostic_custom_templates()) {
11
 
12
- $template_option = yarpp_get_option('template');
13
- if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('template', false);
 
 
14
 
15
- $template_option = yarpp_get_option('rss_template');
16
- if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('rss_template', false);
 
 
17
  }
18
 
19
  /**
20
  * @since 3.3 Move version checking here, in PHP.
21
  */
22
- if (current_user_can('update_plugins')) {
23
- $yarpp_version_info = $yarpp->version_info();
24
-
25
- /*
26
- * These strings are not localizable, as long as the plugin data on wordpress.org cannot be.
27
- */
28
- $slug = 'yet-another-related-posts-plugin';
29
- $plugin_name = 'Yet Another Related Posts Plugin';
30
- $file = basename(YARPP_DIR).'/yarpp.php';
31
- if ($yarpp_version_info && isset($yarpp_version_info['result']) && $yarpp_version_info['result'] === 'new') {
32
-
33
- /* Make sure the update system is aware of this version. */
34
- $current = get_site_transient('update_plugins');
35
- if (!isset($current->response[$file])) {
36
- delete_site_transient('update_plugins');
37
- wp_update_plugins();
38
- }
39
-
40
- echo '<div class="updated"><p>';
41
- $details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin='.$slug.'&TB_iframe=true&width=600&height=800');
42
- printf(
43
- __(
44
- 'There is a new version of %1$s available.'.
45
- '<a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>'.
46
- 'or <a href="%5$s">update automatically</a>.', 'yarpp'),
47
- $plugin_name,
48
- esc_url($details_url),
49
- esc_attr($plugin_name),
50
- $yarpp_version_info['current']['version'],
51
- wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=').$file, 'upgrade-plugin_'.$file)
52
- );
53
- echo '</p></div>';
54
-
55
- } else if (isset($yarpp_version_info['result']) && $yarpp_version_info['result'] === 'newbeta') {
56
-
57
- echo '<div class="updated"><p>';
58
- printf(
59
- __(
60
- "There is a new beta (%s) of Yet Another Related Posts Plugin. ".
61
- "You can <a href=\"%s\">download it here</a> at your own risk.", "yarpp"),
62
- $yarpp_version_info['beta']['version'],
63
- $yarpp_version_info['beta']['url']
64
- );
65
- echo '</p></div>';
66
-
67
- }
 
 
 
 
68
  }
69
 
70
  /* MyISAM Check */
71
- include 'yarpp_myisam_notice.php';
72
 
73
  /* This is not a yarpp plugin update, it is an yarpp option update */
74
- if (isset($_POST['update_yarpp']) && check_admin_referer('update_yarpp', 'update_yarpp-nonce')) {
75
- $new_options = array();
76
- foreach ($yarpp->default_options as $option => $default) {
77
- if ( is_bool($default) )
78
- $new_options[$option] = isset($_POST[$option]);
79
- if ( (is_string($default) || is_int($default)) &&
80
- isset($_POST[$option]) && is_string($_POST[$option]) )
81
- $new_options[$option] = stripslashes($_POST[$option]);
82
- }
83
-
84
- if ( isset($_POST['weight']) ) {
85
- $new_options['weight'] = array();
86
- $new_options['require_tax'] = array();
87
- // if we're going to use titles or bodies, make sure those indexes exist.
88
- if(isset($_POST['weight']['title']) && $_POST['weight']['title'] !== 'no'){
89
- $yarpp->enable_fulltext_titles();
90
- }
91
- if(isset($_POST['weight']['body']) && $_POST['weight']['body'] !== 'no'){
92
- $yarpp->enable_fulltext_contents();
93
- }
94
- foreach ( (array) $_POST['weight'] as $key => $value) {
95
- if ( $value == 'consider' )
96
- $new_options['weight'][$key] = 1;
97
- if ( $value == 'consider_extra' )
98
- $new_options['weight'][$key] = YARPP_EXTRA_WEIGHT;
99
- }
100
- foreach ( (array) $_POST['weight']['tax'] as $tax => $value) {
101
- if ( $value == 'consider' )
102
- $new_options['weight']['tax'][$tax] = 1;
103
- if ( $value == 'consider_extra' )
104
- $new_options['weight']['tax'][$tax] = YARPP_EXTRA_WEIGHT;
105
- if ( $value == 'require_one' ) {
106
- $new_options['weight']['tax'][$tax] = 1;
107
- $new_options['require_tax'][$tax] = 1;
108
- }
109
- if ( $value == 'require_more' ) {
110
- $new_options['weight']['tax'][$tax] = 1;
111
- $new_options['require_tax'][$tax] = 2;
112
- }
113
- }
114
- }
115
-
116
- if ( isset( $_POST['auto_display_post_types'] ) ) {
117
- $new_options['auto_display_post_types'] = array_keys( $_POST['auto_display_post_types'] );
118
- } else {
119
- $new_options['auto_display_post_types'] = array();
120
- }
121
-
122
- // The new value for "recent only" will be used directly in MySQL query, so make sure its sanitized.
123
- if ( isset($_POST['recent_only'] ) ) {
124
- if(in_array(
125
- $_POST['recent_units'],
126
- array_keys($yarpp->recent_units())
127
- )){
 
 
 
 
 
 
128
  $unit = $_POST['recent_units'];
129
- } else {
130
- $unit = 'day';
131
- }
132
- $recent = ((int)$_POST['recent_number']) . ' ' . $unit;
133
  } else {
134
- $recent = false;
135
- }
136
  $new_options['recent'] = $recent;
137
 
138
- if ( isset($_POST['exclude']) )
139
- $new_options['exclude'] = implode(',',array_keys($_POST['exclude']));
140
- else
141
- $new_options['exclude'] = '';
142
-
143
- if ( isset ($_POST['same_post_type'] ) ) {
144
- $new_options['cross_relate'] = false;
145
- } else {
146
- $new_options['cross_relate'] = true;
147
- }
148
-
149
- if ( isset ($_POST['include_post_type'] ) ) {
150
- $new_options['include_post_type'] = implode( ',', array_keys( $_POST['include_post_type'] ) );
151
- } else {
152
- $new_options['include_post_type'] = '';
153
- }
154
- $new_options['include_sticky_posts'] = isset( $_POST['include_sticky_posts'] ) ? 1 : 0;
155
- $new_options['template'] = $_POST['use_template'] == 'custom' ? $_POST['template_file'] :
156
- ( $_POST['use_template'] == 'thumbnails' ? 'thumbnails' : false );
157
- $new_options['rss_template'] = $_POST['rss_use_template'] == 'custom' ? $_POST['rss_template_file'] :
158
- ( $_POST['rss_use_template'] == 'thumbnails' ? 'thumbnails' : false );
159
-
160
- $new_options = apply_filters( 'yarpp_settings_save', $new_options );
161
- yarpp_set_option($new_options);
162
-
163
- echo '<div class="updated fade"><p>'.__('Options saved!','yarpp').'</p></div>';
 
164
  }
165
 
166
- wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
167
- wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
168
- wp_nonce_field('yarpp_display_demo', 'yarpp_display_demo-nonce', false);
169
- wp_nonce_field('yarpp_display_exclude_terms', 'yarpp_display_exclude_terms-nonce', false);
170
- wp_nonce_field('yarpp_optin_data', 'yarpp_optin_data-nonce', false);
171
- wp_nonce_field('yarpp_set_display_code', 'yarpp_set_display_code-nonce', false);
172
 
173
- if (!count($yarpp->admin->get_templates()) && $yarpp->admin->can_copy_templates()) {
174
- wp_nonce_field('yarpp_copy_templates', 'yarpp_copy_templates-nonce', false);
175
  }
176
 
177
- include(YARPP_DIR.'/includes/phtmls/yarpp_options.phtml');
7
  global $wpdb, $wp_version, $yarpp;
8
 
9
  /* Check to see that templates are in the right place */
10
+ if ( ! $yarpp->diagnostic_custom_templates() ) {
11
 
12
+ $template_option = yarpp_get_option( 'template' );
13
+ if ( $template_option !== false && $template_option !== 'thumbnails' ) {
14
+ yarpp_set_option( 'template', false );
15
+ }
16
 
17
+ $template_option = yarpp_get_option( 'rss_template' );
18
+ if ( $template_option !== false && $template_option !== 'thumbnails' ) {
19
+ yarpp_set_option( 'rss_template', false );
20
+ }
21
  }
22
 
23
  /**
24
  * @since 3.3 Move version checking here, in PHP.
25
  */
26
+ if ( current_user_can( 'update_plugins' ) ) {
27
+ $yarpp_version_info = $yarpp->version_info();
28
+
29
+ /*
30
+ * These strings are not localizable, as long as the plugin data on wordpress.org cannot be.
31
+ */
32
+ $slug = 'yet-another-related-posts-plugin';
33
+ $plugin_name = 'Yet Another Related Posts Plugin';
34
+ $file = basename( YARPP_DIR ) . '/yarpp.php';
35
+ if ( $yarpp_version_info && isset( $yarpp_version_info['result'] ) && $yarpp_version_info['result'] === 'new' ) {
36
+
37
+ /* Make sure the update system is aware of this version. */
38
+ $current = get_site_transient( 'update_plugins' );
39
+ if ( ! isset( $current->response[ $file ] ) ) {
40
+ delete_site_transient( 'update_plugins' );
41
+ wp_update_plugins();
42
+ }
43
+
44
+ echo '<div class="updated"><p>';
45
+ $details_url = self_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $slug . '&TB_iframe=true&width=600&height=800' );
46
+ printf(
47
+ __(
48
+ 'There is a new version of %1$s available.' .
49
+ '<a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>' .
50
+ 'or <a href="%5$s">update automatically</a>.',
51
+ 'yarpp'
52
+ ),
53
+ $plugin_name,
54
+ esc_url( $details_url ),
55
+ esc_attr( $plugin_name ),
56
+ $yarpp_version_info['current']['version'],
57
+ wp_nonce_url( self_admin_url( 'update.php?action=upgrade-plugin&plugin=' ) . $file, 'upgrade-plugin_' . $file )
58
+ );
59
+ echo '</p></div>';
60
+
61
+ } elseif ( isset( $yarpp_version_info['result'] ) && $yarpp_version_info['result'] === 'newbeta' ) {
62
+
63
+ echo '<div class="updated"><p>';
64
+ printf(
65
+ __(
66
+ 'There is a new beta (%s) of Yet Another Related Posts Plugin. ' .
67
+ 'You can <a href="%s">download it here</a> at your own risk.',
68
+ 'yarpp'
69
+ ),
70
+ $yarpp_version_info['beta']['version'],
71
+ $yarpp_version_info['beta']['url']
72
+ );
73
+ echo '</p></div>';
74
+
75
+ }
76
  }
77
 
78
  /* MyISAM Check */
79
+ require 'yarpp_myisam_notice.php';
80
 
81
  /* This is not a yarpp plugin update, it is an yarpp option update */
82
+ if ( isset( $_POST['update_yarpp'] ) && check_admin_referer( 'update_yarpp', 'update_yarpp-nonce' ) ) {
83
+ $new_options = array();
84
+ foreach ( $yarpp->default_options as $option => $default ) {
85
+ if ( is_bool( $default ) ) {
86
+ $new_options[ $option ] = isset( $_POST[ $option ] );
87
+ }
88
+ if ( ( is_string( $default ) || is_int( $default ) ) &&
89
+ isset( $_POST[ $option ] ) && is_string( $_POST[ $option ] ) ) {
90
+ $new_options[ $option ] = stripslashes( $_POST[ $option ] );
91
+ }
92
+ }
93
+
94
+ if ( isset( $_POST['weight'] ) ) {
95
+ $new_options['weight'] = array();
96
+ $new_options['require_tax'] = array();
97
+ // if we're going to use titles or bodies, make sure those indexes exist.
98
+ if ( isset( $_POST['weight']['title'] ) && $_POST['weight']['title'] !== 'no' ) {
99
+ $yarpp->enable_fulltext_titles();
100
+ }
101
+ if ( isset( $_POST['weight']['body'] ) && $_POST['weight']['body'] !== 'no' ) {
102
+ $yarpp->enable_fulltext_contents();
103
+ }
104
+ foreach ( (array) $_POST['weight'] as $key => $value ) {
105
+ if ( $value == 'consider' ) {
106
+ $new_options['weight'][ $key ] = 1;
107
+ }
108
+ if ( $value == 'consider_extra' ) {
109
+ $new_options['weight'][ $key ] = YARPP_EXTRA_WEIGHT;
110
+ }
111
+ }
112
+ foreach ( (array) $_POST['weight']['tax'] as $tax => $value ) {
113
+ if ( $value == 'consider' ) {
114
+ $new_options['weight']['tax'][ $tax ] = 1;
115
+ }
116
+ if ( $value == 'consider_extra' ) {
117
+ $new_options['weight']['tax'][ $tax ] = YARPP_EXTRA_WEIGHT;
118
+ }
119
+ if ( $value == 'require_one' ) {
120
+ $new_options['weight']['tax'][ $tax ] = 1;
121
+ $new_options['require_tax'][ $tax ] = 1;
122
+ }
123
+ if ( $value == 'require_more' ) {
124
+ $new_options['weight']['tax'][ $tax ] = 1;
125
+ $new_options['require_tax'][ $tax ] = 2;
126
+ }
127
+ }
128
+ }
129
+
130
+ if ( isset( $_POST['auto_display_post_types'] ) ) {
131
+ $new_options['auto_display_post_types'] = array_keys( $_POST['auto_display_post_types'] );
132
+ } else {
133
+ $new_options['auto_display_post_types'] = array();
134
+ }
135
+
136
+ // The new value for "recent only" will be used directly in MySQL query, so make sure its sanitized.
137
+ if ( isset( $_POST['recent_only'] ) ) {
138
+ if ( in_array(
139
+ $_POST['recent_units'],
140
+ array_keys( $yarpp->recent_units() )
141
+ ) ) {
142
  $unit = $_POST['recent_units'];
143
+ } else {
144
+ $unit = 'day';
145
+ }
146
+ $recent = ( (int) $_POST['recent_number'] ) . ' ' . $unit;
147
  } else {
148
+ $recent = false;
149
+ }
150
  $new_options['recent'] = $recent;
151
 
152
+ if ( isset( $_POST['exclude'] ) ) {
153
+ $new_options['exclude'] = implode( ',', array_keys( $_POST['exclude'] ) );
154
+ } else {
155
+ $new_options['exclude'] = '';
156
+ }
157
+
158
+ if ( isset( $_POST['same_post_type'] ) ) {
159
+ $new_options['cross_relate'] = false;
160
+ } else {
161
+ $new_options['cross_relate'] = true;
162
+ }
163
+
164
+ if ( isset( $_POST['include_post_type'] ) ) {
165
+ $new_options['include_post_type'] = implode( ',', array_keys( $_POST['include_post_type'] ) );
166
+ } else {
167
+ $new_options['include_post_type'] = '';
168
+ }
169
+ $new_options['include_sticky_posts'] = isset( $_POST['include_sticky_posts'] ) ? 1 : 0;
170
+ $new_options['template'] = $_POST['use_template'] == 'custom' ? $_POST['template_file'] :
171
+ ( $_POST['use_template'] == 'thumbnails' ? 'thumbnails' : false );
172
+ $new_options['rss_template'] = $_POST['rss_use_template'] == 'custom' ? $_POST['rss_template_file'] :
173
+ ( $_POST['rss_use_template'] == 'thumbnails' ? 'thumbnails' : false );
174
+
175
+ $new_options = apply_filters( 'yarpp_settings_save', $new_options );
176
+ yarpp_set_option( $new_options );
177
+
178
+ echo '<div class="updated fade"><p>' . __( 'Options saved!', 'yarpp' ) . '</p></div>';
179
  }
180
 
181
+ wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
182
+ wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
183
+ wp_nonce_field( 'yarpp_display_demo', 'yarpp_display_demo-nonce', false );
184
+ wp_nonce_field( 'yarpp_display_exclude_terms', 'yarpp_display_exclude_terms-nonce', false );
185
+ wp_nonce_field( 'yarpp_optin_data', 'yarpp_optin_data-nonce', false );
186
+ wp_nonce_field( 'yarpp_set_display_code', 'yarpp_set_display_code-nonce', false );
187
 
188
+ if ( ! count( $yarpp->admin->get_templates() ) && $yarpp->admin->can_copy_templates() ) {
189
+ wp_nonce_field( 'yarpp_copy_templates', 'yarpp_copy_templates-nonce', false );
190
  }
191
 
192
+ require YARPP_DIR . '/includes/phtmls/yarpp_options.phtml';
includes/yarpp_pro_options.php CHANGED
@@ -1,20 +1,20 @@
1
  <?php
2
  global $yarpp;
3
 
4
- if (isset($_GET['aid']) && isset($_GET['v']) && isset($_GET['st']) && isset($_GET['dpid'])) {
5
- $yarpp->yarppPro['aid'] = (trim($_GET['aid']) !== '') ? $_GET['aid'] : null;
6
- $yarpp->yarppPro['dpid']= (trim($_GET['dpid'])!== '') ? $_GET['dpid']: null;
7
- $yarpp->yarppPro['st'] = (trim($_GET['st']) !== '') ? rawurlencode($_GET['st']) : null;
8
- $yarpp->yarppPro['v'] = (trim($_GET['v']) !== '') ? rawurlencode($_GET['v']) : null;
9
 
10
- update_option('yarpp_pro', $yarpp->yarppPro);
11
  }
12
 
13
- $src = urlencode(admin_url().'options-general.php?page='.$_GET['page']);
14
- $aid = (isset($yarpp->yarppPro['aid']) && $yarpp->yarppPro['aid']) ? $yarpp->yarppPro['aid'] : 0;
15
- $st = (isset($yarpp->yarppPro['st']) && $yarpp->yarppPro['st']) ? $yarpp->yarppPro['st'] : 0;
16
- $v = (isset($yarpp->yarppPro['v']) && $yarpp->yarppPro['v']) ? $yarpp->yarppPro['v'] : 0;
17
- $d = urlencode(get_home_url());
18
- $url = 'https://yarpp.adkengage.com/AdcenterUI/PublisherUI/PublisherDashboard.aspx?src='.$src.'&d='.$d.'&aid='.$aid.'&st='.$st.'&plugin=1';
19
 
20
- include(YARPP_DIR.'/includes/phtmls/yarpp_pro_options.phtml');
1
  <?php
2
  global $yarpp;
3
 
4
+ if ( isset( $_GET['aid'] ) && isset( $_GET['v'] ) && isset( $_GET['st'] ) && isset( $_GET['dpid'] ) ) {
5
+ $yarpp->yarppPro['aid'] = ( trim( $_GET['aid'] ) !== '' ) ? $_GET['aid'] : null;
6
+ $yarpp->yarppPro['dpid'] = ( trim( $_GET['dpid'] ) !== '' ) ? $_GET['dpid'] : null;
7
+ $yarpp->yarppPro['st'] = ( trim( $_GET['st'] ) !== '' ) ? rawurlencode( $_GET['st'] ) : null;
8
+ $yarpp->yarppPro['v'] = ( trim( $_GET['v'] ) !== '' ) ? rawurlencode( $_GET['v'] ) : null;
9
 
10
+ update_option( 'yarpp_pro', $yarpp->yarppPro );
11
  }
12
 
13
+ $src = urlencode( admin_url() . 'options-general.php?page=' . $_GET['page'] );
14
+ $aid = ( isset( $yarpp->yarppPro['aid'] ) && $yarpp->yarppPro['aid'] ) ? $yarpp->yarppPro['aid'] : 0;
15
+ $st = ( isset( $yarpp->yarppPro['st'] ) && $yarpp->yarppPro['st'] ) ? $yarpp->yarppPro['st'] : 0;
16
+ $v = ( isset( $yarpp->yarppPro['v'] ) && $yarpp->yarppPro['v'] ) ? $yarpp->yarppPro['v'] : 0;
17
+ $d = urlencode( get_home_url() );
18
+ $url = 'https://yarpp.adkengage.com/AdcenterUI/PublisherUI/PublisherDashboard.aspx?src=' . $src . '&d=' . $d . '&aid=' . $aid . '&st=' . $st . '&plugin=1';
19
 
20
+ require YARPP_DIR . '/includes/phtmls/yarpp_pro_options.phtml';
includes/yarpp_pro_set_display_types.php CHANGED
@@ -1,11 +1,13 @@
1
  <?php
2
- if (!isset($_GET['ypsdt']) || $_GET['ypsdt'] === true) die();
3
- $types = (isset($_GET['types']) && is_array($_GET['types'])) ? $_GET['types'] : array();
 
 
4
 
5
- include_once(realpath('../../../../').'/wp-config.php');
6
- $yarppPro = get_option('yarpp_pro');
7
  $yarppPro['auto_display_post_types'] = $types;
8
- update_option('yarpp_pro',$yarppPro);
9
 
10
- header('Content-Type: text/plain');
11
- die('ok');
1
  <?php
2
+ if ( ! isset( $_GET['ypsdt'] ) || $_GET['ypsdt'] === true ) {
3
+ die();
4
+ }
5
+ $types = ( isset( $_GET['types'] ) && is_array( $_GET['types'] ) ) ? $_GET['types'] : array();
6
 
7
+ require_once realpath( '../../../../' ) . '/wp-config.php';
8
+ $yarppPro = get_option( 'yarpp_pro' );
9
  $yarppPro['auto_display_post_types'] = $types;
10
+ update_option( 'yarpp_pro', $yarppPro );
11
 
12
+ header( 'Content-Type: text/plain' );
13
+ die( 'ok' );
js/options_basic.min.js CHANGED
@@ -1 +1 @@
1
- jQuery(function(i){function a(){var a,e=i(this).closest("#yarpp_display_web, #yarpp_display_rss");e.length&&(value=e.find(".use_template").val(),e.find(".yarpp_subbox").hide(),e.find(".template_options_"+value).show(),a=e.find(".yarpp_no_results"),"custom"===value?a.hide():a.show(),t.apply(e))}function t(){var a=i(this).closest("#yarpp_display_web, #yarpp_display_rss");a.find(".excerpted").toggle(!("builtin"!==a.find(".use_template").val()||!a.find(".show_excerpt input").prop("checked")))}postboxes.add_postbox_toggles(pagenow),i(".use_template").each(a).change(a),i(".show_excerpt, .use_template, #yarpp-rss_display").click(t);var s=!1;function e(){var e;i("#yarpp_display_web .inside").is(":visible")&&(i(".yarpp_code_display").toggle(i("#yarpp_display_code").is(":checked")),i("#yarpp_display_web .yarpp_code_display").is(":visible")&&!s&&(s=!0,e=i("#display_demo_web"),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_display_demo",domain:"website",_ajax_nonce:i("#yarpp_display_demo-nonce").val()},beforeSend:function(){e.html(loading)},success:function(a){e.html("<pre>"+a+"</pre>")},dataType:"html"})))}i("#yarpp_display_web .handlediv, #yarpp_display_web-hide").click(e),e();var p=!1;function o(){var e;i("#yarpp_display_rss .inside").is(":visible")&&(i("#yarpp-rss_display").is(":checked")?(i(".rss_displayed").show(),i(".yarpp_code_display").toggle(i("#yarpp_display_code").is(":checked")),i("#yarpp_display_rss .yarpp_code_display").is(":visible")&&!p&&(p=!0,e=i("#display_demo_rss"),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_display_demo",domain:"rss",_ajax_nonce:i("#yarpp_display_demo-nonce").val()},beforeSend:function(){e.html(loading)},success:function(a){e.html("<pre>"+a+"</pre>")},dataType:"html"})),i("#yarpp_display_rss").each(a)):i(".rss_displayed").hide())}function n(){i("#yarpp_display_api .inside").is(":visible")&&(i("#yarpp-rest_api_display").is(":checked")?i(".yarpp_rest_displayed").show():i(".yarpp_rest_displayed").hide())}function r(){i("#yarpp-rest_api_client_side_caching").is(":checked")?i(".yarpp_rest_browser_cache_displayed").show():i(".yarpp_rest_browser_cache_displayed").hide()}i("#yarpp-rss_display, #yarpp_display_rss .handlediv, #yarpp_display_rss-hide").click(o),o(),i("#yarpp-rest_api_display").click(n),n(),i("#yarpp-rest_api_client_side_caching").click(r),r();var c=!1;function l(){var s,a;function p(e){var t;e in s||((t=i("#exclude_"+e)).find(".loading").length||(e in a?a[e]=a[e]+100:a[e]=0,i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_display_exclude_terms",taxonomy:e,offset:a[e],_ajax_nonce:i("#yarpp_display_exclude_terms-nonce").val()},beforeSend:function(){t.append(loading)},success:function(a){if(t.find(".loading").remove(),":("==a)return s[e]=!0,void t.append("-");t.append(a)},dataType:"html"})))}!c&&i("#yarpp_pool .inside").is(":visible")&&(c=!0,s={},a={},i(".exclude_terms").each(function(){var t,a=jQuery(this).attr("id");a&&(p(t=a.replace("exclude_","")),i("#exclude_"+t).parent(".yarpp_scroll_wrapper").scroll(function(){var a=i(this),e=a.children("div");a.scrollTop()+a.height()>e.height()-10&&p(t)}))}))}function d(a){i("#tab-link-"+a+" a").click(),i("#contextual-help-link").click()}function _(){var a=i(this).find("option:selected"),e=a.closest(".yarpp_form_row");a.attr("data-url")?e.find(".template_author_wrap").toggle(!!a.attr("data-author")).find("span").empty().append("<a>"+a.attr("data-author")+"</a>").attr("href",a.attr("data-url")):e.find(".template_author_wrap").toggle(!!a.attr("data-author")).find("span").text(a.attr("data-author")),e.find(".template_description_wrap").toggle(!!a.attr("data-description")).find("span").text(a.attr("data-description")),e.find(".template_file_wrap").toggle(!!a.attr("data-basename")).find("span").text(a.attr("data-basename"))}i("#yarpp_pool .handlediv, #yarpp_pool-hide").click(l),l(),i("#yarpp-optin-learnmore").click(function(){d("optin")}),i("#yarpp-help-cpt").click(function(){d("dev")}),"#help-optin"==location.hash&&setTimeout(function(){d("optin")}),i(".yarpp_help[data-help]").hover(function(){var a=i(this),e={content:"<p>"+a.attr("data-help")+"</p>",position:{edge:isRtl?"right":"left",align:"center",of:a},document:{body:a}},t=a.pointer(e).pointer("open");a.closest(".yarpp_form_row, p").mouseleave(function(){t.pointer("close")})}),i(".yarpp_template_button[data-help]").hover(function(){var a=i(this),e="<p>"+a.attr("data-help")+"</p>",t=a.pointer({content:e,position:{edge:"bottom",of:a},document:{body:a}}).pointer("open");a.mouseleave(function(){t.pointer("close")}),i(".yarpp_copy_templates_button").on("click",function(){const a=i(this),e=a.siblings(".spinner");a.addClass("yarpp-disabled"),e.addClass("is-active"),window.location=window.location+(window.location.search.length?"&":"?")+"action=copy_templates&_ajax_nonce="+i("#yarpp_copy_templates-nonce").val()})}),i(".yarpp_spin_on_click").on("click",function(){const a=i(this),e=a.siblings(".spinner");a.addClass("yarpp-disabled"),e.addClass("is-active")}),i(".yarpp_template_button:not(.disabled)").click(function(){i(this).siblings("input").val(i(this).attr("data-value")).change(),i(this).siblings().removeClass("active"),i(this).addClass("active")}),i("#template_file, #rss_template_file").each(_).change(_);var y=!1;function h(){var e;i("#optin_data_frame").is(":visible")&&!y&&(y=!0,e=i("#optin_data_frame"),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_optin_data",_ajax_nonce:i("#yarpp_optin_data-nonce").val()},beforeSend:function(){e.html(loading)},success:function(a){e.html("<pre>"+a+"</pre>")},dataType:"html"}))}function u(){setTimeout(h,0)}function f(){var a=i(".yarpp_form_post_types").is(":has(input[type=checkbox]:checked)");i("#yarpp-auto_display_archive").attr("disabled",!a),a||i("#yarpp-auto_display_archive").prop("checked",!1)}function m(a,e){a?(i(".yarpp_form_post_types #yarpp_post_type_"+e).prop("disabled",!1),i(".yarpp_form_post_types #yarpp_post_type_"+e).siblings().hide()):(i(".yarpp_form_post_types #yarpp_post_type_"+e).prop("disabled",!0),i(".yarpp_form_post_types #yarpp_post_type_"+e).siblings().show())}i("#yarpp-optin-learnmore, a[aria-controls=tab-panel-optin]").bind("click focus",u),u(),i(".sync_no_results, .sync_rss_no_results").change(function(){var a=i(this).find("input").attr("value");i(this).hasClass("sync_no_results")&&i(".sync_no_results input").attr("value",a),i(this).hasClass("sync_rss_no_results")&&i(".sync_rss_no_results input").attr("value",a)}),i("#yarpp_display_code").click(function(){var a={action:"yarpp_set_display_code",_ajax_nonce:i("#yarpp_set_display_code-nonce").val()};i(this).is(":checked")&&(a.checked=!0),i.ajax({type:"POST",url:ajaxurl,data:a}),e(),o()}),i(".yarpp_form_post_types input[type=checkbox]").change(f),f(),i("#yarpp_fulltext_expand").click(function(a){a.preventDefault();a=i("#yarpp_fulltext_details");a.slideToggle(),a.hasClass("hidden")?(a.removeClass("hidden"),i(this).text("Hide Details [-]")):(a.addClass("hidden"),i(this).text("Show Details [+]"))}),i(".include_post_type input[type=checkbox]").change(function(a){var e=i(this).attr("data-post-type");i("#yarpp-same_post_type").is(":checked")?m(i(this).is(":checked"),e):i(".yarpp_form_post_types #yarpp_post_type_"+e).prop("disabled",!1)}),i("#yarpp-same_post_type").change(function(a){i(this).is(":checked")?i(".include_post_type input[type=checkbox]").each(function(){var a=i(this).attr("data-post-type");m(i(this).is(":checked"),a)}):(i(".yarpp_form_post_types input[type=checkbox]").prop("disabled",!1),i(".yarpp_form_post_types input[type=checkbox]").siblings().hide())});var v=i('\t\t\t<div id="shareaholic-deactivate-dialog" class="shareaholic-deactivate-dialog" data-remodal-id="">\t\t\t\t<div class="shareaholic-deactivate-header" style="background-image: url('+yarpp_messages.logo+"); background-color: "+yarpp_messages.bgcolor+';"><div class="shareaholic-deactivate-text"><h2>'+yarpp_messages.model_title+'</h2></div></div>\t\t\t\t<div class="shareaholic-deactivate-body">\t\t\t\t\t<div class="shareaholic-deactivate-body-foreword">'+yarpp_messages.alert_message+'</div>\t\t\t\t\t<div class="shareaholic-deactivate-dialog-footer"> <input type="submit" class="button confirm button-secondary" id="yarpp-clear-cache-submit" value="Delete"/>\t\t\t\t\t\t<button data-remodal-action="cancel" class="button button-secondary">Cancel</button>\t\t\t\t\t\t</div>\t\t\t\t</div>\t\t\t</div>\t\t')[0];i("#yarpp-clear-cache").click(function(){i(v).remodal({hashTracking:!1,closeOnOutsideClick:!1}).open(),event.preventDefault()}),i(document.body).on("click","#yarpp-clear-cache-submit",function(){i(v).remodal().close();var t="#yarpp-clear-cache",s="#display_notices",p="notice notice-error is-dismissible";i(t).prop("disabled",!0),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_clear_cache",_ajax_nonce:i("#clear_cache-nonce").val()},beforeSend:function(){i(t).siblings(".spinner").addClass("is-active")},success:function(a){var e;i(t).siblings(".spinner").removeClass("is-active"),i(s).show(),"success"==a?(e=yarpp_messages.success,p="notice notice-success is-dismissible",i(t).prop("disabled",!1)):e="forbidden"==a?yarpp_messages.forbidden:"nonce_fail"==a?yarpp_messages.nonce_fail:yarpp_messages.error,i(s).addClass(p),i(s).html("<p>"+e+"</p>")},error:function(a){i(s).show(),i(s).addClass(p),i(t).siblings(".spinner").removeClass("is-active"),i(s).html("<p>"+yarpp_messages.error+"</p>")}}),i(s).delay(5e3).fadeOut(1e3)})});
1
+ jQuery(function(i){function a(){var a,e=i(this).closest("#yarpp_display_web, #yarpp_display_rss");e.length&&(value=e.find(".use_template").val(),e.find(".yarpp_subbox").hide(),e.find(".template_options_"+value).show(),a=e.find(".yarpp_no_results"),"custom"===value?a.hide():a.show(),a=e.find(".generate_missing_thumbnails"),"builtin"===value?a.hide():a.show(),t.apply(e))}function t(){var a=i(this).closest("#yarpp_display_web, #yarpp_display_rss");a.find(".excerpted").toggle(!("builtin"!==a.find(".use_template").val()||!a.find(".show_excerpt input").prop("checked")))}postboxes.add_postbox_toggles(pagenow),i(".use_template").each(a).change(a),i(".show_excerpt, .use_template, #yarpp-rss_display").click(t);var s=!1;function e(){var e;i("#yarpp_display_web .inside").is(":visible")&&(i(".yarpp_code_display").toggle(i("#yarpp_display_code").is(":checked")),i("#yarpp_display_web .yarpp_code_display").is(":visible")&&!s&&(s=!0,e=i("#display_demo_web"),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_display_demo",domain:"website",_ajax_nonce:i("#yarpp_display_demo-nonce").val()},beforeSend:function(){e.html(loading)},success:function(a){e.html("<pre>"+a+"</pre>")},dataType:"html"})))}i("#yarpp_display_web .handlediv, #yarpp_display_web-hide").click(e),e();var p=!1;function n(){var e;i("#yarpp_display_rss .inside").is(":visible")&&(i("#yarpp-rss_display").is(":checked")?(i(".rss_displayed").show(),i(".yarpp_code_display").toggle(i("#yarpp_display_code").is(":checked")),i("#yarpp_display_rss .yarpp_code_display").is(":visible")&&!p&&(p=!0,e=i("#display_demo_rss"),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_display_demo",domain:"rss",_ajax_nonce:i("#yarpp_display_demo-nonce").val()},beforeSend:function(){e.html(loading)},success:function(a){e.html("<pre>"+a+"</pre>")},dataType:"html"})),i("#yarpp_display_rss").each(a)):i(".rss_displayed").hide())}function o(){i("#yarpp_display_api .inside").is(":visible")&&(i("#yarpp-rest_api_display").is(":checked")?i(".yarpp_rest_displayed").show():i(".yarpp_rest_displayed").hide())}function r(){i("#yarpp-rest_api_client_side_caching").is(":checked")?i(".yarpp_rest_browser_cache_displayed").show():i(".yarpp_rest_browser_cache_displayed").hide()}i("#yarpp-rss_display, #yarpp_display_rss .handlediv, #yarpp_display_rss-hide").click(n),n(),i("#yarpp-rest_api_display").click(o),o(),i("#yarpp-rest_api_client_side_caching").click(r),r();var c=!1;function l(){var s,a;function p(e){var t;e in s||((t=i("#exclude_"+e)).find(".loading").length||(e in a?a[e]=a[e]+100:a[e]=0,i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_display_exclude_terms",taxonomy:e,offset:a[e],_ajax_nonce:i("#yarpp_display_exclude_terms-nonce").val()},beforeSend:function(){t.append(loading)},success:function(a){if(t.find(".loading").remove(),":("==a)return s[e]=!0,void t.append("-");t.append(a)},dataType:"html"})))}!c&&i("#yarpp_pool .inside").is(":visible")&&(c=!0,s={},a={},i(".exclude_terms").each(function(){var t,a=jQuery(this).attr("id");a&&(p(t=a.replace("exclude_","")),i("#exclude_"+t).parent(".yarpp_scroll_wrapper").scroll(function(){var a=i(this),e=a.children("div");a.scrollTop()+a.height()>e.height()-10&&p(t)}))}))}function d(a){i("#tab-link-"+a+" a").click(),i("#contextual-help-link").click()}function _(){var a=i(this).find("option:selected"),e=a.closest(".yarpp_form_row");a.attr("data-url")?e.find(".template_author_wrap").toggle(!!a.attr("data-author")).find("span").empty().append("<a>"+a.attr("data-author")+"</a>").attr("href",a.attr("data-url")):e.find(".template_author_wrap").toggle(!!a.attr("data-author")).find("span").text(a.attr("data-author")),e.find(".template_description_wrap").toggle(!!a.attr("data-description")).find("span").text(a.attr("data-description")),e.find(".template_file_wrap").toggle(!!a.attr("data-basename")).find("span").text(a.attr("data-basename"))}i("#yarpp_pool .handlediv, #yarpp_pool-hide").click(l),l(),i("#yarpp-optin-learnmore").click(function(){d("optin")}),i("#yarpp-help-cpt").click(function(){d("dev")}),"#help-optin"==location.hash&&setTimeout(function(){d("optin")}),i(".yarpp_help[data-help]").hover(function(){var a=i(this),e={content:"<p>"+a.attr("data-help")+"</p>",position:{edge:isRtl?"right":"left",align:"center",of:a},document:{body:a}},t=a.pointer(e).pointer("open");a.closest(".yarpp_form_row, p").mouseleave(function(){t.pointer("close")})}),i(".yarpp_template_button[data-help]").hover(function(){var a=i(this),e="<p>"+a.attr("data-help")+"</p>",t=a.pointer({content:e,position:{edge:"bottom",of:a},document:{body:a}}).pointer("open");a.mouseleave(function(){t.pointer("close")}),i(".yarpp_copy_templates_button").on("click",function(){const a=i(this),e=a.siblings(".spinner");a.addClass("yarpp-disabled"),e.addClass("is-active"),window.location=window.location+(window.location.search.length?"&":"?")+"action=copy_templates&_ajax_nonce="+i("#yarpp_copy_templates-nonce").val()})}),i(".yarpp_spin_on_click").on("click",function(){const a=i(this),e=a.siblings(".spinner");a.addClass("yarpp-disabled"),e.addClass("is-active")}),i(".yarpp_template_button:not(.disabled)").click(function(){i(this).siblings("input").val(i(this).attr("data-value")).change(),i(this).siblings().removeClass("active"),i(this).addClass("active")}),i("#template_file, #rss_template_file").each(_).change(_);var y=!1;function h(){var e;i("#optin_data_frame").is(":visible")&&!y&&(y=!0,e=i("#optin_data_frame"),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_optin_data",_ajax_nonce:i("#yarpp_optin_data-nonce").val()},beforeSend:function(){e.html(loading)},success:function(a){e.html("<pre>"+a+"</pre>")},dataType:"html"}))}function u(){setTimeout(h,0)}function f(){var a=i(".yarpp_form_post_types").is(":has(input[type=checkbox]:checked)");i("#yarpp-auto_display_archive").attr("disabled",!a),a||i("#yarpp-auto_display_archive").prop("checked",!1)}function m(a,e){a?(i(".yarpp_form_post_types #yarpp_post_type_"+e).prop("disabled",!1),i(".yarpp_form_post_types #yarpp_post_type_"+e).siblings().hide()):(i(".yarpp_form_post_types #yarpp_post_type_"+e).prop("disabled",!0),i(".yarpp_form_post_types #yarpp_post_type_"+e).siblings().show())}i("#yarpp-optin-learnmore, a[aria-controls=tab-panel-optin]").bind("click focus",u),u(),i(".sync_no_results, .sync_rss_no_results").change(function(){var a=i(this).find("input").attr("value");i(this).hasClass("sync_no_results")&&i(".sync_no_results input").attr("value",a),i(this).hasClass("sync_rss_no_results")&&i(".sync_rss_no_results input").attr("value",a)}),i("#yarpp_display_code").click(function(){var a={action:"yarpp_set_display_code",_ajax_nonce:i("#yarpp_set_display_code-nonce").val()};i(this).is(":checked")&&(a.checked=!0),i.ajax({type:"POST",url:ajaxurl,data:a}),e(),n()}),i(".yarpp_form_post_types input[type=checkbox]").change(f),f(),i("#yarpp_fulltext_expand").click(function(a){a.preventDefault();a=i("#yarpp_fulltext_details");a.slideToggle(),a.hasClass("hidden")?(a.removeClass("hidden"),i(this).text("Hide Details [-]")):(a.addClass("hidden"),i(this).text("Show Details [+]"))}),i(".include_post_type input[type=checkbox]").change(function(a){var e=i(this).attr("data-post-type");i("#yarpp-same_post_type").is(":checked")?m(i(this).is(":checked"),e):i(".yarpp_form_post_types #yarpp_post_type_"+e).prop("disabled",!1)}),i("#yarpp-same_post_type").change(function(a){i(this).is(":checked")?i(".include_post_type input[type=checkbox]").each(function(){var a=i(this).attr("data-post-type");m(i(this).is(":checked"),a)}):(i(".yarpp_form_post_types input[type=checkbox]").prop("disabled",!1),i(".yarpp_form_post_types input[type=checkbox]").siblings().hide())});var v=i('\t\t\t<div id="shareaholic-deactivate-dialog" class="shareaholic-deactivate-dialog" data-remodal-id="">\t\t\t\t<div class="shareaholic-deactivate-header" style="background-image: url('+yarpp_messages.logo+"); background-color: "+yarpp_messages.bgcolor+';"><div class="shareaholic-deactivate-text"><h2>'+yarpp_messages.model_title+'</h2></div></div>\t\t\t\t<div class="shareaholic-deactivate-body">\t\t\t\t\t<div class="shareaholic-deactivate-body-foreword">'+yarpp_messages.alert_message+'</div>\t\t\t\t\t<div class="shareaholic-deactivate-dialog-footer"> <input type="submit" class="button confirm button-secondary" id="yarpp-clear-cache-submit" value="Delete"/>\t\t\t\t\t\t<button data-remodal-action="cancel" class="button button-secondary">Cancel</button>\t\t\t\t\t\t</div>\t\t\t\t</div>\t\t\t</div>\t\t')[0];i("#yarpp-clear-cache").click(function(){i(v).remodal({hashTracking:!1,closeOnOutsideClick:!1}).open(),event.preventDefault()}),i(document.body).on("click","#yarpp-clear-cache-submit",function(){i(v).remodal().close();var t="#yarpp-clear-cache",s="#display_notices",p="notice notice-error is-dismissible";i(t).prop("disabled",!0),i.ajax({type:"POST",url:ajaxurl,data:{action:"yarpp_clear_cache",_ajax_nonce:i("#clear_cache-nonce").val()},beforeSend:function(){i(t).siblings(".spinner").addClass("is-active")},success:function(a){var e;i(t).siblings(".spinner").removeClass("is-active"),i(s).show(),"success"==a?(e=yarpp_messages.success,p="notice notice-success is-dismissible",i(t).prop("disabled",!1)):e="forbidden"==a?yarpp_messages.forbidden:"nonce_fail"==a?yarpp_messages.nonce_fail:yarpp_messages.error,i(s).addClass(p),i(s).html("<p>"+e+"</p>")},error:function(a){i(s).show(),i(s).addClass(p),i(t).siblings(".spinner").removeClass("is-active"),i(s).html("<p>"+yarpp_messages.error+"</p>")}}),i(s).delay(5e3).fadeOut(1e3)})});
lib/plugin-deactivation-survey/deactivate-feedback-form.php CHANGED
@@ -60,19 +60,19 @@ if ( ! function_exists( 'shareaholic_deactivate_feedback' ) ) {
60
  $current_user = wp_get_current_user();
61
  if ( $current_user instanceof WP_User && is_user_logged_in() && $current_user->ID ) {
62
  $email = $current_user->user_email;
63
- if ( is_array($current_user->roles) ) {
64
- $role = reset($current_user->roles);
65
  } else {
66
  $role = '';
67
  }
68
  } else {
69
  $email = '';
70
- $role = '';
71
  }
72
 
73
  foreach ( $plugins as $plugin ) {
74
  $plugin->email = $email;
75
- $plugin->role = $role;
76
  }
77
 
78
  // Send plugin data.
60
  $current_user = wp_get_current_user();
61
  if ( $current_user instanceof WP_User && is_user_logged_in() && $current_user->ID ) {
62
  $email = $current_user->user_email;
63
+ if ( is_array( $current_user->roles ) ) {
64
+ $role = reset( $current_user->roles );
65
  } else {
66
  $role = '';
67
  }
68
  } else {
69
  $email = '';
70
+ $role = '';
71
  }
72
 
73
  foreach ( $plugins as $plugin ) {
74
  $plugin->email = $email;
75
+ $plugin->role = $role;
76
  }
77
 
78
  // Send plugin data.
readme.txt CHANGED
@@ -1,71 +1,113 @@
1
- === Yet Another Related Posts Plugin (YARPP) ===
2
  Contributors: jeffparker, shareaholic
3
- Tags: related, related posts, similar posts, posts, pages, thumbnails, feeds, multisite, multilingual
 
4
  Requires at least: 3.7
5
  Requires PHP: 5.3
6
  License: GPLv2 or later
7
  Tested up to: 5.7
8
- Stable tag: 5.23.0
9
 
10
- The most popular plugin to display a list of related posts on your site based on a powerful unique algorithm.
11
 
12
  == Description ==
13
 
14
- *Yet Another Related Posts Plugin* (YARPP) is a professionally maintained and feature rich plugin that displays pages, posts, and custom post types related to the current entry, introducing your readers to other relevant content on your site. Automatically added Related Posts can increase your pageviews up to 10%. Just install and activate.
15
 
16
  **Key Features**
17
  -------------------------------------------
18
- * **Thumbnail or list view** of related content.
19
- * **Related posts, pages, and custom post types.**
20
- * **Templating**: The YARPP templating system gives you advanced control of how your results are displayed.
21
- * **An advanced and versatile algorithm**: Using a customizable algorithm considering post titles, content, tags, categories, and custom taxonomies, YARPP finds related content from across your site.
22
- * **Related posts in feeds**: Display related posts in RSS feeds with custom display options.
23
- * **REST API support** - Embed related posts in your web or JavaScript driven app! ([documentation](https://support.shareaholic.com/hc/en-us/articles/360046456752))
24
- * **Shortcode support** - Use `[yarpp]` shortcode to place related posts anywhere ([documentation](https://wordpress.org/plugins/yet-another-related-posts-plugin/#%0Ahow%20can%20i%20move%20the%20related%20posts%20display%3F%0A))
25
- * **Gutenberg Block support**
26
- * **HTTPS support**
27
- * **bbPress forums support**
28
- * **WordPress Multisite support**
29
- * **Professionally maintained** and supported with regular updates
 
 
 
 
 
30
 
31
  **YARPP Algorithm Explained**
32
  -------------------------------------------
33
 
34
  https://videopress.com/v/0n2TSzkb
35
 
 
 
 
 
36
  **Trusted since 2008**
37
  -------------------------------------------
38
  The **Yet Another Related Posts Plugin** (YARPP) is the **most popular and widely used** [Related Posts plugin for WordPress](https://yarpp.com/), encouraging Discovery and Engagement since 2008!
39
 
40
  YARPP works best with PHP 5.3 or greater, MySQL 5.6 or greater OR MariaDB 10.1 or greater, and WordPress 3.7 or greater. See [the FAQ](https://wordpress.org/plugins/yet-another-related-posts-plugin/faq/) for answers to common questions.
41
 
 
 
 
 
 
 
 
 
 
42
  == Installation ==
43
 
44
- = Auto display on your website =
45
 
46
- 1. Copy the folder `yet-another-related-posts-plugin` into the directory `wp-content/plugins/` and activate the plugin.
47
- 2. (optionally) copy the sample template files inside the `yarpp-templates` folder into your active theme.
48
- 3. Go to the "YARPP" settings page to customize YARPP.
 
 
 
49
 
50
- = Auto display in your feeds =
51
 
52
- Make sure the "display related posts in feeds" option is turned on if you would like to show related posts in your RSS and Atom feeds. The "display related posts in feeds" option can be used regardless of whether you auto display them on your website (and vice versa).
 
 
 
53
 
54
- = Widget =
55
 
56
- Related posts can also be displayed as a widget. Go to the Appearance > Widgets options page and add the "Related Posts (YARPP)" widget. Choose to display content from YARPP Basic. The widget will only be displayed on single entry (permalink) pages.
 
 
57
 
58
- The YARPP widget can be used even if the "auto display" option is turned off.
59
 
60
- = Custom display through templates =
61
 
62
- YARPP allows the advanced user with knowledge of PHP to customize the display of related posts using a custom templating mechanism.
63
 
64
- = REST API =
65
 
66
- YARPP adds a REST API endpoint for fetching related posts. The JSON results from the REST API query are the same as you would see if you were visiting a post on your website (the same quantity and order). It is possible to override the quantity at the time of making the REST API request.
67
 
68
- [[Documentation](https://support.shareaholic.com/hc/en-us/articles/360046456752)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  = Shortcode =
71
 
@@ -81,9 +123,9 @@ If you know the reference Post ID that you want to show content related to, use:
81
 
82
  To specify which YARPP template to use, use the "template" attribute like so:
83
 
84
- `[yarpp template="yarpp-template-photoblog"]` // where `yarpp-template-photoblog.php` is the file name of the custom template
85
- `[yarpp template="list"]` // built-in "List" template
86
- `[yarpp template="thumbnails"]` // built-in "Thumbnails" template
87
 
88
  To specify maximum number of posts to show, use the "limit" attribute like so:
89
 
@@ -96,6 +138,133 @@ To add YARPP shortcode to your theme files (eg. single.php), use:
96
 
97
  If you're adding the shortcode *outside [the loop](http://codex.wordpress.org/The_Loop)*, you must provide the reference_id.
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  == Frequently Asked Questions ==
100
 
101
  If your question isn't here, ask your own question at [the WordPress.org forums](https://wordpress.org/support/plugin/yet-another-related-posts-plugin).
@@ -104,64 +273,77 @@ If your question isn't here, ask your own question at [the WordPress.org forums]
104
 
105
  Most likely you have "no related posts" right now because the default "match threshold" is too high. Here's what we recommend to find an appropriate match threshold: lower your match threshold in the YARPP "Algorithm" options to something very low, like 1. (If you don't see the match threshold, you may need to display the "Algorithm" options via the "Screen Options" tab at the top.) Most likely the really low threshold will pull up many posts that aren't actually related (false positives), so look at some of your posts' related posts and their match scores. This will help you find an appropriate threshold. You want it lower than what you have now, but high enough so it doesn't have many false positives.
106
 
107
- = How can I move the related posts display? =
108
-
109
- If you do not want to show the Related Posts display in its default position (right below the post content), first go to YARPP options and turn off the "automatically display" options in the "website" section. If you would like to instead display it in your sidebar and you have a widget-aware theme, YARPP provides a Related Posts widget which you can add under "Appearance" > "Widgets."
110
-
111
- If you would like to add the Related Posts display elsewhere, edit your relevant theme file (most likely something like `single.php`) and add the shortcode code `[yarpp]` (recommended) or PHP function `yarpp_related();` within [The Loop](https://codex.wordpress.org/The_Loop) where you want to display the related posts. Make sure you don't add `echo yarpp_related();` or you may end up with duplicates in your related posts section.
112
-
113
  = How can I limit related posts to a certain time frame? For instance, I don't want to show posts from two years ago. =
114
 
115
- Yes. In Wordpress, go to "Settings" and "Related Posts (YARPP)" and make sure "The Pool" is checked in the "Screen Options" section at the top of the page. In "The Pool" section, check the box next to "Show only posts from the past *X* months."
116
 
117
  = Where do I tell YARPP to display related posts only by tags? =
118
 
119
  In WordPress, go to "Settings" and "YARPP" and make sure "Algorithm" is checked in the "Screen Options" section at the top of the page. In the "Algorithm" section, configure the dropdown boxes next to "Titles," "Bodies," "Categories," and "Tags."
120
 
121
- = Can I specify related posts? =
122
 
123
  Sorry, but specifying related posts, displaying related posts from external WordPress sites, and pulling content from the Comments section are all outside the scope of YARPP at this time.
124
 
125
  = I'm seeing related posts displayed on the home page. How do I prevent that? =
126
 
127
- Some WordPress themes treat the home page as an archive or a "page." Go to "Settings" then "Related Posts (YARPP)" and view the "Display Options" section. Make sure "Pages" and "Also display in archives" are not checked.
128
 
129
  = How can I prevent the "related posts" list from displaying on specific posts? =
130
 
131
- When editing a post or page, uncheck “Display Related Posts”, which is located next to the WordPress editor. Be sure to update or publish to save your changes.
 
 
132
 
133
- An older method was to add `<?noyarpp-->` to the HTML code of any post to prevent related posts from displaying. This solution will only work if you are using "Automatic Display" in the "Display Options" section.
134
 
135
- If you are programatically calling `yarpp_related()`, the shortcode `[yarpp]` from PHP code or the YARPP Block, you'll have to do your own checking to see if related posts are appropriate to display or not.
136
 
137
- = I'm using the Thumbnails display in YARPP 4. How do I override the style of the text that displays? The title only shows two lines, the font is larger than I'd like, I'd like to center the thumbnails, etc. =
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  If you're familiar with CSS, you can override any YARPP styles by editing your theme's `style.css` file, or any other CSS file you may have created that loads after the YARPP one. To edit your theme's CSS file, go to "Appearance" then "Editor" and then click `style.css` in the right sidebar. Add changes at the bottom of the file and click "Save." If you do edit this file, just make sure you add `!important` after each style declaration, to make sure they'll override the YARPP rules.
140
 
141
  Some common overrides that YARPP users have added are:
142
 
143
- `
144
  /* Reduces the title font size and displays more than two title lines */
145
  .yarpp-thumbnail {height: 200px !important;}
146
  .yarpp-thumbnail-title {font-size:0.8em !important; max-height: 4em !important}
147
 
148
  /* Centers the thumbnail section */
149
  .yarpp-related-widget {text-align:center !important;}
150
- `
151
 
152
  Once you save any CSS changes, empty your browser's cache and reload your page to see the effect.
153
 
154
  = I'm using the Thumbnails display. How can I change the thumbnail size? =
155
 
156
- As of YARPP 5.19.0, YARPP usually defaults to using WordPress' default thumbnail size. This can be changed to another thumbnail size using the YARPP setting "Thumbnail Size".
157
 
158
- However, if you used YARPP before 5.19.0, or your theme defines a "yarpp-thumbnail" size, the default is the "yarpp-thumbnail".
159
 
160
- To change "yarpp-thumbnail" size, add `add_image_size('yarpp-thumbnail', $width, $height, true);` to your theme's `functions.php` file with appropriate width and height variables.
161
 
162
  When you do this, make sure you also set the YARPP setting "Thumbnail Size" to "yarpp-thumbnail".
163
 
164
- Each time you change YARPP's thumbnail dimensions like this, you will probably want to have WordPress regenerate appropriate sized thumbnails for all of your images. I highly recommend the [Regenerate Thumbnails](https://wordpress.org/extend/plugins/regenerate-thumbnails/) plugin for this purpose.
165
 
166
  = I'm using the Thumbnails display. Why aren't the right size thumbnails being served? =
167
 
@@ -175,11 +357,7 @@ There are two options for doing so:
175
 
176
  = I'm using the Thumbnails display. Why are some of my posts missing appropriate images? =
177
 
178
- YARPP's thumbnail view requires that a WordPress "featured image" be set for each post. If you have many posts that never had a featured image set, I recommend the plugin [Auto Post Thumbnail](https://wordpress.org/extend/plugins/auto-post-thumbnail/), which will generate post thumbnails for you.
179
-
180
- = How can I use the custom template feature? =
181
-
182
- YARPP's custom templates feature allows you to uber-customize the related posts display using the same coding conventions and [Template Tags](https://codex.wordpress.org/Template_Tags) as in WordPress themes. Custom templates must be in your *active theme's main directory* in order to be recognized by YARPP. If your theme did not ship with YARPP templates, move the files in the `yarpp-templates` directory which ships with YARPP into your active theme's main directory. Be sure to move the *files* (which must be named `yarpp-template-`...`.php`) to your theme, not the entire directory.
183
 
184
  = Is YARPP compatible with WordPress Multisite? =
185
 
@@ -197,20 +375,16 @@ However, YARPP does have difficulty with languages that don't place spaces betwe
197
 
198
  = Does YARPP slow down my blog/server? =
199
 
200
- The YARPP calculation of related content does make a little impact, yes. However, YARPP caches all of its results, so any post's results need only be calculated once. YARPP's queries have been significantly optimized since version 3.5.
201
 
202
  If you are running a large site and need to throttle YARPP's computation, try the official [YARPP Experiments](https://wordpress.org/extend/plugins/yarpp-experiments/) plugin which adds this throttling functionality.
203
 
204
  = Are there any plugins that are incompatible with YARPP? =
205
 
206
- * [DISQUS](https://wordpress.org/extend/plugins/disqus-comment-system/): go to the DISQUS plugin advanced settings and turn on the "Check this if you have a problem with comment counts not showing on permalinks".
207
  * [SEO_Pager plugin](https://wordpress.org/support/topic/267966): turn off the automatic display option in SEO Pager and instead add the code manually.
208
- * [Pagebar 2](http://www.elektroelch.de/hacks/wp/pagebar/);
209
- * [WP Contact Form III plugin and Contact Form Plugin](https://wordpress.org/support/topic/392605);
210
- * [WPML](http://wpml.org): various incompatibilities have been reported. The multilingual plugin [Polylang](https://polylang.wordpress.com/) has great support for YARPP and is suggested as a replacement for WPML.
211
  * Other related posts plugins, obviously, may also be incompatible.
212
 
213
- Please submit similar bugs by starting a new thread on [the WordPress.org forums](https://wordpress.org/support/plugin/yet-another-related-posts-plugin). I check the forums regularly and will try to release a quick bugfix.
214
 
215
  = YARPP seems to be broken since I upgraded to WordPress X.X. =
216
 
@@ -218,78 +392,64 @@ Before upgrading to a new WordPress version, you should first deactivate all plu
218
 
219
  1. Visit the "YARPP" settings page to verify your settings.
220
  2. Deactivate YARPP, replace the YARPP files on the server with a fresh copy of the new version, and then reactivate it.
221
- 3. Install the official [YARPP Experiments](https://wordpress.org/extend/plugins/yarpp-experiments/) plugin to flush the cache.
222
 
223
  = Can I clear my cache? Can I build up the cache manually? =
224
 
225
  Yes, there is a button to clear YARPP's cache table in YARPP's WP Admin options.
226
 
227
- = I removed the YARPP plugin but I still see YARPP-related database tables. Shouldn't those be removed, too? =
228
-
229
- Beginning with version 4.0.7, YARPP includes clean uninstall functionality. If you no longer wish to use YARPP, first deactivate YARPP using the "Plugins" page in WordPress, then click the "Delete" link found on the same page. This process will automatically remove all YARPP-related files, including temp tables. If you manually try to remove YARPP files instead of going through WordPress, some files or temp tables could remain.
230
 
231
- = Does YARPP support custom post types? =
232
-
233
- Yes. To make YARPP support your custom post type, the attribute `yarpp_support` must be set to true on the custom post type when it is registered. It will then be available on options on the YARPP settings page.
234
 
235
  `'yarpp_support' => true`
236
 
237
- If you would like to programmatically control which post types are considered in an automatically-displayed related posts display, use the `yarpp_map_post_types` filter.
238
 
239
- = Can I customize how YARPP displays? =
 
 
 
 
 
 
 
 
 
 
240
 
241
- Yes. Developers can call YARPP's powerful relatedness algorithm from anywhere in their own code. Some examples and more details are in my slides from my [WordCamp Birmingham talk](http://www.slideshare.net/mitcho/relate-all-the-things).
242
 
243
- `
244
- yarpp_related(array(
245
- // Pool options: these determine the "pool" of entities which are considered
246
- 'post_type' => array('post', 'page', ...),
247
- 'show_pass_post' => false, // show password-protected posts
248
- 'past_only' => false, // show only posts which were published before the reference post
249
- 'exclude' => array(), // a list of term_taxonomy_ids. entities with any of these terms will be excluded from consideration.
250
- 'recent' => false, // to limit to entries published recently, set to something like '15 day', '20 week', or '12 month'.
251
- // Relatedness algorithm options: these determine how "relatedness" is computed
252
- // Weights are used to construct the "match score" between candidates and the reference post
253
- 'weight' => array(
254
- 'body' => 1,
255
- 'title' => 2, // larger weights mean this criteria will be weighted more heavily
256
- 'tax' => array(
257
- 'post_tag' => 1,
258
- ... // put any taxonomies you want to consider here with their weights
259
- )
260
- ),
261
- // Specify taxonomies and a number here to require that a certain number be shared:
262
- 'require_tax' => array(
263
- 'post_tag' => 1 // for example, this requires all results to have at least one 'post_tag' in common.
264
- ),
265
- // The threshold which must be met by the "match score"
266
- 'threshold' => 5,
267
-
268
- // Display options:
269
- 'template' => , // either the name of a file in your active theme or the boolean false to use the builtin template
270
- 'limit' => 5, // maximum number of results
271
- 'order' => 'score DESC'
272
- ),
273
- $reference_ID, // second argument: (optional) the post ID. If not included, it will use the current post.
274
- true); // third argument: (optional) true to echo the HTML block; false to return it
275
- `
276
 
277
- Options which are not specified will default to those specified in the YARPP settings page. Additionally, if you are using the built-in template rather than specifying a custom template file in `template`, the following arguments can be used to override the various parts of the builtin template: `before_title`, `after_title`, `before_post`, `after_post`, `before_related`, `after_related`, `no_results`, `excerpt_length`.
 
 
 
278
 
279
- If you need to use related entries programmatically or to know whether they exist, you can use the functions `yarpp_get_related( $args, $reference_ID )` and `yarpp_related_exist( $args, $reference_ID )`. `yarpp_get_related` returns an array of `post` objects, just like the WordPress function `get_posts`. `yarpp_related_exist` returns a boolean for whether any such related entries exist. For each function, `$args` takes the same arguments as those shown for `yarpp_related` above, except for the various display and template options.
 
 
 
280
 
281
- Note that custom YARPP queries using the functions mentioned here are *not* cached in the built-in YARPP caching system. Thus, if you notice any performance hits, you may need to write your own code to cache the results.
 
 
 
 
282
 
283
- Here is an example of how to use a custom YARPP query and cache the results for a day:
284
 
285
- `
286
- $result = get_transient('yarpp_custom_results_for_' . $post->ID);
287
- if(! $result){
288
- $result = yarpp_related(['post_type' => 'reply'],null,false);
289
- set_transient('yarpp_custom_results_for_' . $post->ID, $result, DAY_IN_SECONDS);
290
- }
291
- echo $result;
292
- `
293
 
294
  = Does YARPP support custom taxonomies? =
295
 
@@ -301,7 +461,7 @@ If you would like to choose custom taxonomies to choose in the YARPP settings UI
301
 
302
  If you want to prevent the Review Notice from appearing you can use the function below:
303
 
304
- `
305
  /**
306
  * Disable YARPP Review Notice
307
  *
@@ -310,22 +470,33 @@ function yarpp_disable_review_notice() {
310
  remove_action('admin_notices', array('YARPP_Admin', 'display_review_notice'));
311
  }
312
  add_action('admin_init', 'yarpp_disable_review_notice', 11);
313
- `
314
 
315
  = Can I disable the request-for-feedback modal when deactivating the plugin? =
316
  Sure. Use the following code:
317
 
318
- `
319
  add_action(
320
- 'admin_init',
321
- function(){
322
- remove_all_filters('shareaholic_deactivate_feedback_form_plugins');
323
- },
324
- 11
325
  );
326
- `
 
 
 
 
 
327
 
328
  == Changelog ==
 
 
 
 
 
 
329
  = 5.23.0 (02-June-2021) =
330
  * [New](https://wordpress.org/support/topic/is-it-possible-to-use-different-styles-of-yarpp-in-every-post/): Ability to specify maximum number of posts to show in the YARPP shortcode. For example:
331
  + `[yarpp template="list" limit=3]` // maximum post limit set to 3
@@ -470,7 +641,7 @@ add_filter( 'yarpp_enqueue_related_style', '_\_return_false' );
470
  * [Bugfix](https://wordpress.org/support/topic/please-exclude-the-gutenberg-blocks/): Exclude Gutenberg blocks so that they don't appear as related
471
 
472
  = 5.4.0 (03-August-2020) =
473
- * New: Shortcode support! `[yarpp]` ([documentation](https://wordpress.org/plugins/yet-another-related-posts-plugin/#%0Ahow%20can%20i%20move%20the%20related%20posts%20display%3F%0A))
474
  * Enhancement: Adds YARPP score to REST API responses ([documentation](https://support.shareaholic.com/hc/en-us/articles/360046456752))
475
  * Enhancement: Prepare for default jQuery version update in upcoming WordPress Core
476
  * Bugfix: Fixed admin panel tooltips
@@ -1176,5 +1347,5 @@ After a break of many years, the plugin is 100% supported now that the baton has
1176
  * Initial upload
1177
 
1178
  == Upgrade Notice ==
1179
- = 5.23.0 =
1180
  We update this plugin regularly so we can make it better for you. Update to the latest version for all of the available features and improvements. Thank you for using YARPP!
1
+ === YARPP - Yet Another Related Posts Plugin ===
2
  Contributors: jeffparker, shareaholic
3
+ Tags: related posts, contextual related posts, similar posts, posts, seo, thumbnails, feeds, multisite, multilingual
4
+ Donate link: https://yarpp.com
5
  Requires at least: 3.7
6
  Requires PHP: 5.3
7
  License: GPLv2 or later
8
  Tested up to: 5.7
9
+ Stable tag: 5.24.0
10
 
11
+ The best WordPress plugin for displaying related posts. Simple and flexible, with a powerful proven algorithm and inbuilt caching.
12
 
13
  == Description ==
14
 
15
+ *Yet Another Related Posts Plugin (YARPP)* is a professionally maintained, highly customizable, performant and feature rich plugin that displays pages, posts, and custom post types related to the current entry. YARPP introduces your visitors to other relevant content on your site -- boosting visitor engagement, time on site and SEO. Related Posts can increase your pageviews up to 10%. Simply install, activate and watch your sessions and pageviews increase.
16
 
17
  **Key Features**
18
  -------------------------------------------
19
+ * **An advanced and versatile algorithm**: Using a customizable algorithm considering post titles, content, tags, categories, and custom taxonomies, YARPP finds related content from across your site
20
+ * **Caching**: Inbuilt cache makes subsequent queries super efficient and fast
21
+ * **Custom Templates and Styles**: Use the inbuilt **list** or **thumbnail** templates, or use the YARPP custom templating system for 100% control of how results are styles and displayed
22
+ * **Flexible** with a full range of placement options, including:
23
+ + [Automatic Display Options](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation) (pick where to show YARPP from the YARPP settings page)
24
+ + [RSS/Feed Options](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation)
25
+ + [Gutenberg Block](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation)
26
+ + [[yarpp] Shortcode](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation)
27
+ + [Widget](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation)
28
+ + [YARPP functions()](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation)
29
+ + [REST API](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation)
30
+ * **Works with all languages**, including those with full-width (double-byte) characters and those that don't use spaces between words
31
+ * **Custom post type and taxonomy** support
32
+ * **WordPress Multisite** support
33
+ * **bbPress forums** support
34
+ * **WooCommerce** support
35
+ * **Professionally maintained and supported** with regular updates
36
 
37
  **YARPP Algorithm Explained**
38
  -------------------------------------------
39
 
40
  https://videopress.com/v/0n2TSzkb
41
 
42
+ **Translate YARPP**
43
+
44
+ YARPP is available for [translation directly on WordPress.org](https://translate.wordpress.org/projects/wp-plugins/yet-another-related-posts-plugin/). Check out the official [Translator Handbook](https://make.wordpress.org/polyglots/handbook/rosetta/theme-plugin-directories/) to contribute.
45
+
46
  **Trusted since 2008**
47
  -------------------------------------------
48
  The **Yet Another Related Posts Plugin** (YARPP) is the **most popular and widely used** [Related Posts plugin for WordPress](https://yarpp.com/), encouraging Discovery and Engagement since 2008!
49
 
50
  YARPP works best with PHP 5.3 or greater, MySQL 5.6 or greater OR MariaDB 10.1 or greater, and WordPress 3.7 or greater. See [the FAQ](https://wordpress.org/plugins/yet-another-related-posts-plugin/faq/) for answers to common questions.
51
 
52
+ == Screenshots ==
53
+
54
+ 1. YARPP options in WP-Admin: Automatic Display Options
55
+ 2. YARPP options in WP-Admin: "The Pool" settings
56
+ 3. YARPP options in WP-Admin: "The Algorithm" settings
57
+ 4. Example - starwars.com
58
+ 5. Example - CB2.com
59
+ 6. Example - chrisguillebeau.com
60
+
61
  == Installation ==
62
 
63
+ = Install YARPP from within WordPress =
64
 
65
+ 1. Visit the plugins page within your WordPress dashboard and select `Add New`
66
+ 1. Search for `YARPP`
67
+ 1. Press "Install Now" for the `YARPP` plugin
68
+ 1. Activate YARPP from your Plugins page
69
+ 1. Go to the "YARPP" settings page to customize YARPP
70
+ 1. *[optional]* copy the sample YARPP Custom Template files inside the `yarpp-templates` folder into your active theme folder.
71
 
72
+ = Install YARPP Manually =
73
 
74
+ 1. Upload the `yet-another-related-posts-plugin` folder to the `/wp-content/plugins/` directory
75
+ 1. Activate YARPP from your Plugins page
76
+ 1. Go to the "YARPP" settings page to customize YARPP
77
+ 1. *[optional]* copy the sample YARPP Custom Template files inside the `yarpp-templates` folder into your active theme folder.
78
 
79
+ = Install YARPP with the WP-CLI =
80
 
81
+ 1. `wp plugin install yet-another-related-posts-plugin --activate`
82
+ 1. Go to the "YARPP" settings page to customize YARPP
83
+ 1. *[optional]* copy the sample YARPP Custom Template files inside the `yarpp-templates` folder into your active theme folder.
84
 
85
+ The *YARPP custom template* feature allows you to easily customize look and feel using the same coding conventions and [Template Tags](https://codex.wordpress.org/Template_Tags) as in WordPress themes.
86
 
87
+ Your YARPP Custom Template file must be in the *active theme's main directory* in order to be recognized by YARPP. If your theme did not ship with a YARPP templates, move the files in the `yarpp-templates` directory which ships with YARPP into your active theme's main directory. Be sure to move the *files* (which must be named `yarpp-template-`...`.php`) to your theme, not the entire directory. There is no limit restriction on custom templates.
88
 
 
89
 
90
+ = After Activation =
91
 
92
+ You should customize your Pool, Algorithm and Automatic Display Options settings from the YARPP settings page. YARPP supports a full range of placement options, including Automatic Display Options (pick where to show YARPP from the YARPP settings page), Block, Shortcode, Widget, YARPP functions() and REST API support. Details below.
93
 
94
+ = Automatic Display Options =
95
+
96
+ Configurable from the YARPP settings page, the *Automatic Display Option* automatically displays YARPP right below post content. You can configure which posts types to display YARPP on from the YARPP settings page.
97
+
98
+ If you do not want to show the Related Posts display in its default position (right below the post content), first go to YARPP options and turn off the "Automatic Display Options".
99
+
100
+ If you would like to instead display it in your sidebar and you have a widget-aware theme, YARPP provides a Related Posts widget which you can add under "Appearance" > "Widgets."
101
+
102
+ If you would like to add Related Posts elsewhere (such as inline related posts), edit your relevant theme file (most likely something like `single.php`) and add the shortcode code `[yarpp]` or PHP function `yarpp_related();` within [The Loop](https://codex.wordpress.org/The_Loop) where you want to display the related posts. Make sure you don't add `echo yarpp_related();` or you may end up with duplicates in your related posts section. The YARPP Block is also an option.
103
+
104
+ = Automatic Display in Feed Options =
105
+
106
+ Make sure the "display related posts in feeds" option is turned on if you would like to show related posts in your RSS and Atom feeds. The "display related posts in feeds" option can be used regardless of whether you auto display them on your website (and vice versa).
107
+
108
+ = Block =
109
+
110
+ YARPP ships with full support for Gutenberg Blocks. You can place YARPP's Block manually wherever you’d like in post content.
111
 
112
  = Shortcode =
113
 
123
 
124
  To specify which YARPP template to use, use the "template" attribute like so:
125
 
126
+ `[yarpp template="yarpp-template-photoblog"]` - where `yarpp-template-photoblog.php` is the file name of the custom template
127
+ `[yarpp template="list"]` - built-in "List" template
128
+ `[yarpp template="thumbnails"]` - built-in "Thumbnails" template
129
 
130
  To specify maximum number of posts to show, use the "limit" attribute like so:
131
 
138
 
139
  If you're adding the shortcode *outside [the loop](http://codex.wordpress.org/The_Loop)*, you must provide the reference_id.
140
 
141
+ = Widget =
142
+
143
+ Related posts can also be displayed as a widget. Go to the Appearance > Widgets options page and add the "Related Posts (YARPP)" widget. Choose to display content from YARPP Basic. The widget will only be displayed on single entry (permalink) pages.
144
+
145
+ The YARPP widget can be used even if the "auto display" option is turned off.
146
+
147
+ = REST API =
148
+
149
+ Add related posts to your JavaScript driven app!
150
+
151
+ YARPP adds a REST API endpoint for fetching related posts. The JSON results from the REST API query are the same as you would see if you were visiting a post on your website (the same quantity and order). It is possible to override the quantity at the time of making the REST API request.
152
+
153
+ [[Documentation](https://support.shareaholic.com/hc/en-us/articles/360046456752)]
154
+
155
+ = YARPP functions() =
156
+
157
+ Developers can call YARPP's powerful relatedness algorithm from anywhere in their own code. Some examples and more details are in this [WordCamp Birmingham talk](https://www.slideshare.net/mitcho/relate-all-the-things).
158
+
159
+ You may use the functions defined in `includes/related_functions.php` in your own code, notably:
160
+
161
+ 1. `yarpp_related()` - gets the HTML for related posts and displays it
162
+ 1. `yarpp_related_exist()` - checks whether any related posts exists
163
+ 1. `yarpp_get_related()` - returns the list of related posts (`WP_Post` objects)
164
+
165
+ *Examples:*
166
+
167
+ Show related posts, using all the settings set in the YARPP settings page:
168
+
169
+ `<?php yarpp_related(); ?>`
170
+
171
+ Each of these functions will default to using the settings set in your the YARPP settings page, but can be customized. For example:
172
+
173
+ <code>
174
+ yarpp_related(
175
+ array(
176
+ // Pool options: these determine the "pool" of entities which are considered
177
+ 'post_type' => array('post', 'page', 'wc_product', ...), // post types to include in results
178
+ 'show_pass_post' => false, // show password-protected posts
179
+ 'past_only' => false, // show only posts which were published before the reference post
180
+ 'exclude' => array(), // a list of term_taxonomy_ids. entities with any of these terms will be excluded from consideration.
181
+ 'recent' => false, // to limit to entries published recently, set to like '15 day', '20 week', or '12 month' (https://www.mysqltutorial.org/mysql-interval/)
182
+
183
+ // Relatedness algorithm options: these determine how "relatedness" is computed
184
+ // Weights are used to construct the "match score" between candidates and the reference post
185
+ 'weight' => array(
186
+ 'body' => 1,
187
+ 'title' => 2, // larger weights mean this criteria will be weighted more heavily
188
+ 'tax' => array(
189
+ 'post_tag' => 1,
190
+ ... // put any taxonomies you want to consider here with their weights
191
+ )
192
+ ),
193
+ // Specify taxonomies and a number here to require that a certain number be shared:
194
+ 'require_tax' => array(
195
+ 'post_tag' => 1 // for example, this requires all results to have at least one 'post_tag' in common
196
+ ),
197
+ // The threshold which must be met by the "match score" to be considered related
198
+ 'threshold' => 5,
199
+
200
+ // Display options:
201
+ 'template' => 'thumbnails', // which theme/custom template to use. Built-in ones include "list" and "thumbnails", or the name of a YARPP template file in your active theme folder starting with "yarpp-template-". Example: yarpp-template-videos or yarpp-template-videos.php
202
+ 'limit' => 5, // maximum number of results
203
+ 'order' => 'score DESC', // column on "wp_posts" to order by, then a space, and whether to order in ascending ("ASC") or descending ("DESC") order
204
+ 'promote_yarpp' => true, // boolean indicating whether to add 'Powered by YARPP' below related posts
205
+ ),
206
+ $reference_ID, // second argument: (optional) the post ID. If not included, will use the current post.
207
+ true // third argument: (optional) true to echo the HTML block; false to return it
208
+ );
209
+ </code>
210
+
211
+ Options which are not specified will default to those specified on the YARPP settings page. Additionally, if you are using a builtin template rather than specifying a custom template file in `template`, the following arguments can be used to override the various parts of the builtin template: `before_title`, `after_title`, `before_post`, `after_post`, `before_related`, `after_related`, `no_results`, `excerpt_length`.
212
+
213
+ If you need to implement related entries programmatically or to know whether they exist, you can use the functions:
214
+
215
+ 1. `yarpp_get_related( $args, $reference_ID )`
216
+ Returns an array of `post` objects, just like the WordPress function `get_posts`.
217
+ 1. `yarpp_related_exist( $args, $reference_ID )`
218
+ Returns a boolean for whether any such related entries exist.
219
+
220
+ For each of these functions, `$args` takes the same arguments as those detailed for `yarpp_related()` above, except for the various display and template options.
221
+
222
+ Note that at this time custom YARPP queries using the functions mentioned here are *not* cached in the built-in YARPP caching system. Thus, if you notice any performance hits, you may need to write your own code to cache the results.
223
+
224
+ Example of how to use a custom YARPP query and cache the results for a day:
225
+
226
+ <code>
227
+ $result = get_transient('yarpp_custom_results_for_' . $post->ID);
228
+ if(! $result){
229
+ $result = yarpp_related(['post_type' => 'reply'],null,false);
230
+ set_transient('yarpp_custom_results_for_' . $post->ID, $result, DAY_IN_SECONDS);
231
+ }
232
+ echo $result;
233
+ </code>
234
+
235
+ Show at most 4 related WooCommerce products based on their title and especially on their categories, assuming custom YARPP template
236
+ `yarpp-related-wc-products.php` has been added to the active theme folder:
237
+
238
+ <code>
239
+ yarpp_related(
240
+ array(
241
+ 'limit' => 4,
242
+ 'weight' => array(
243
+ 'title' => 1,
244
+ 'tax' => array(
245
+ 'category' => 2
246
+ )
247
+ ),
248
+ 'post_type' => 'wc_product',
249
+ 'template' => 'yarpp-related-wc-products.php'
250
+ )
251
+ );
252
+ </code>
253
+
254
+ Check for posts related to post with ID 123, and loop through them in order to do some more custom logic:
255
+
256
+ <code>
257
+ $related_posts = yarpp_get_related(array(), 123);
258
+ if(! $related_posts){
259
+ echo 'No related posts';
260
+ } else {
261
+ foreach($related_posts as $post){
262
+ // $post is a WP_Post object.
263
+ echo $post->post_title;
264
+ }
265
+ }
266
+ </code>
267
+
268
  == Frequently Asked Questions ==
269
 
270
  If your question isn't here, ask your own question at [the WordPress.org forums](https://wordpress.org/support/plugin/yet-another-related-posts-plugin).
273
 
274
  Most likely you have "no related posts" right now because the default "match threshold" is too high. Here's what we recommend to find an appropriate match threshold: lower your match threshold in the YARPP "Algorithm" options to something very low, like 1. (If you don't see the match threshold, you may need to display the "Algorithm" options via the "Screen Options" tab at the top.) Most likely the really low threshold will pull up many posts that aren't actually related (false positives), so look at some of your posts' related posts and their match scores. This will help you find an appropriate threshold. You want it lower than what you have now, but high enough so it doesn't have many false positives.
275
 
 
 
 
 
 
 
276
  = How can I limit related posts to a certain time frame? For instance, I don't want to show posts from two years ago. =
277
 
278
+ In Wordpress, go to "Settings" and "Related Posts (YARPP)" and make sure "The Pool" is checked in the "Screen Options" section at the top of the page. In "The Pool" section, check the box next to "Show only posts from the past *X* months."
279
 
280
  = Where do I tell YARPP to display related posts only by tags? =
281
 
282
  In WordPress, go to "Settings" and "YARPP" and make sure "Algorithm" is checked in the "Screen Options" section at the top of the page. In the "Algorithm" section, configure the dropdown boxes next to "Titles," "Bodies," "Categories," and "Tags."
283
 
284
+ = Can I manually specify related posts? =
285
 
286
  Sorry, but specifying related posts, displaying related posts from external WordPress sites, and pulling content from the Comments section are all outside the scope of YARPP at this time.
287
 
288
  = I'm seeing related posts displayed on the home page. How do I prevent that? =
289
 
290
+ Some WordPress themes treat the home page as an archive or a "page." Go to "Settings" then "Related Posts (YARPP)" and view the "Automatic Display Options" section. Make sure "Pages" and "Also display in archives" are not checked.
291
 
292
  = How can I prevent the "related posts" list from displaying on specific posts? =
293
 
294
+ **Option 1:**
295
+
296
+ On the edit post page, uncheck “Display Related Posts” in the YARPP box. Be sure to update or publish to save your changes.
297
 
298
+ **Option 2:**
299
 
300
+ Add `<?noyarpp-->` to the HTML code of any post to prevent related posts from displaying.
301
 
302
+ **Option 3:**
303
+
304
+ Use the `noyarpp` filter. For example:
305
+
306
+ <code>
307
+ // Disable YARPP Automatic Display in specific categories
308
+ function yarpp_disable_categories() {
309
+ // Examples of in_category usage: https://codex.wordpress.org/Function_Reference/in_category
310
+ if ( in_category( array( 'my_category_1_slug', 'my_category_2_slug' ) ) ) {
311
+ return true;
312
+ }
313
+ }
314
+ add_filter( 'noyarpp', 'yarpp_disable_categories' );
315
+ </code>
316
+
317
+ These solutions only work if you are using "Automatic Display" in the "Display Options" section. If you are programatically calling `yarpp_related()`, the shortcode `[yarpp]` from PHP code or the YARPP Block, you will need to do your own conditional checks.
318
+
319
+ = I'm using the Thumbnails display in YARPP 4+. How do I override the style of the text that displays? The title only shows two lines, the font is larger than I'd like, I'd like to center the thumbnails, etc. =
320
 
321
  If you're familiar with CSS, you can override any YARPP styles by editing your theme's `style.css` file, or any other CSS file you may have created that loads after the YARPP one. To edit your theme's CSS file, go to "Appearance" then "Editor" and then click `style.css` in the right sidebar. Add changes at the bottom of the file and click "Save." If you do edit this file, just make sure you add `!important` after each style declaration, to make sure they'll override the YARPP rules.
322
 
323
  Some common overrides that YARPP users have added are:
324
 
325
+ <code>
326
  /* Reduces the title font size and displays more than two title lines */
327
  .yarpp-thumbnail {height: 200px !important;}
328
  .yarpp-thumbnail-title {font-size:0.8em !important; max-height: 4em !important}
329
 
330
  /* Centers the thumbnail section */
331
  .yarpp-related-widget {text-align:center !important;}
332
+ </code>
333
 
334
  Once you save any CSS changes, empty your browser's cache and reload your page to see the effect.
335
 
336
  = I'm using the Thumbnails display. How can I change the thumbnail size? =
337
 
338
+ As of YARPP v5.19.0, YARPP usually defaults to using WordPress' default thumbnail size. This can be changed to another thumbnail size using the YARPP setting "Thumbnail Size".
339
 
340
+ However, if you used YARPP before v5.19.0, or your theme defines a "yarpp-thumbnail" size, the default is the "yarpp-thumbnail". To change "yarpp-thumbnail" size, add the following to your theme's `functions.php` file with appropriate width and height variables:
341
 
342
+ `add_image_size('yarpp-thumbnail', $width, $height, true);`
343
 
344
  When you do this, make sure you also set the YARPP setting "Thumbnail Size" to "yarpp-thumbnail".
345
 
346
+ Each time you change YARPP's thumbnail dimensions like this, you will probably want to have WordPress regenerate appropriate sized thumbnails for all of your images. We highly recommend the [Regenerate Thumbnails](https://wordpress.org/extend/plugins/regenerate-thumbnails/) plugin for this purpose.
347
 
348
  = I'm using the Thumbnails display. Why aren't the right size thumbnails being served? =
349
 
357
 
358
  = I'm using the Thumbnails display. Why are some of my posts missing appropriate images? =
359
 
360
+ YARPP's thumbnail view requires that a WordPress "featured image" be set for each post. If you have many posts that never had a featured image set, we recommend the plugin [Auto Post Thumbnail](https://wordpress.org/extend/plugins/auto-post-thumbnail/), which will generate post thumbnails for you.
 
 
 
 
361
 
362
  = Is YARPP compatible with WordPress Multisite? =
363
 
375
 
376
  = Does YARPP slow down my blog/server? =
377
 
378
+ YARPP is a highly optimized plugin with an inbuilt cache that makes subsequent queries super efficient. This means that YARPP will not slow your site down.
379
 
380
  If you are running a large site and need to throttle YARPP's computation, try the official [YARPP Experiments](https://wordpress.org/extend/plugins/yarpp-experiments/) plugin which adds this throttling functionality.
381
 
382
  = Are there any plugins that are incompatible with YARPP? =
383
 
 
384
  * [SEO_Pager plugin](https://wordpress.org/support/topic/267966): turn off the automatic display option in SEO Pager and instead add the code manually.
 
 
 
385
  * Other related posts plugins, obviously, may also be incompatible.
386
 
387
+ Please submit similar bugs by starting a new thread on [the WordPress.org forums](https://wordpress.org/support/plugin/yet-another-related-posts-plugin). We check the forums regularly and will try to release a quick bugfix.
388
 
389
  = YARPP seems to be broken since I upgraded to WordPress X.X. =
390
 
392
 
393
  1. Visit the "YARPP" settings page to verify your settings.
394
  2. Deactivate YARPP, replace the YARPP files on the server with a fresh copy of the new version, and then reactivate it.
395
+ 3. From the "YARPP" settings page, flush the YARPP cache
396
 
397
  = Can I clear my cache? Can I build up the cache manually? =
398
 
399
  Yes, there is a button to clear YARPP's cache table in YARPP's WP Admin options.
400
 
401
+ = How to add support for a Custom Post Type (CPT)? =
 
 
402
 
403
+ To make YARPP support your Custom Post Type (CPT), the attribute `yarpp_support` must be set to true when the CPT is registered. The CPT will then be available in the YARPP settings page.
 
 
404
 
405
  `'yarpp_support' => true`
406
 
407
+ For example:
408
 
409
+ <code>
410
+ function register_my_cpt() {
411
+ $args = array(
412
+ 'public' => true,
413
+ 'label' => 'Books',
414
+ 'yarpp_support' => true,
415
+ );
416
+ register_post_type( 'book', $args );
417
+ }
418
+ add_action( 'init', 'register_my_cpt' );
419
+ </code>
420
 
421
+ If you do not have access to the code which is registering the CPT, maybe because it is a third-party plugin that is creating it, you can still add the `yarpp_support` argument:
422
 
423
+ <code>
424
+ /**
425
+ * Filter the CPT to register more options
426
+ *
427
+ * @param $args array The original CPT args.
428
+ * @param $post_type string The CPT slug.
429
+ *
430
+ * @return array
431
+ */
432
+ function add_yarpp_support_to_post_types( $args, $post_type ) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
 
434
+ // If not our target CPT, exit.
435
+ if ( 'my_custom_post_type' !== $post_type ) {
436
+ return $args;
437
+ }
438
 
439
+ // Add additional YARPP support option.
440
+ $cpt_args = array(
441
+ 'yarpp_support' => true
442
+ );
443
 
444
+ // Merge args together.
445
+ return array_merge( $args, $cpt_args );
446
+ }
447
+ add_filter( 'register_post_type_args', 'add_yarpp_support_to_post_types', 10, 2 );
448
+ </code>
449
 
450
+ *You should replace `my_custom_post_type` with the CPT that you need to add YARPP support to and add this code to the `functions.php` of your theme.*
451
 
452
+ If you would like to programmatically control which post types are considered in an automatically-displayed related posts display, use the `yarpp_map_post_types` filter.
 
 
 
 
 
 
 
453
 
454
  = Does YARPP support custom taxonomies? =
455
 
461
 
462
  If you want to prevent the Review Notice from appearing you can use the function below:
463
 
464
+ <code>
465
  /**
466
  * Disable YARPP Review Notice
467
  *
470
  remove_action('admin_notices', array('YARPP_Admin', 'display_review_notice'));
471
  }
472
  add_action('admin_init', 'yarpp_disable_review_notice', 11);
473
+ </code>
474
 
475
  = Can I disable the request-for-feedback modal when deactivating the plugin? =
476
  Sure. Use the following code:
477
 
478
+ <code>
479
  add_action(
480
+ 'admin_init',
481
+ function(){
482
+ remove_all_filters('shareaholic_deactivate_feedback_form_plugins');
483
+ },
484
+ 11
485
  );
486
+ </code>
487
+
488
+ = I removed the YARPP plugin but I still see YARPP-related database tables. Shouldn't those be removed, too? =
489
+
490
+ Beginning with version 4.0.7, YARPP includes clean uninstall functionality. If you no longer wish to use YARPP, first deactivate YARPP using the "Plugins" page in WordPress, then click the "Delete" link found on the same page. This process will automatically remove all YARPP-related files, including temp tables. If you manually try to remove YARPP files instead of going through WordPress, some files or temp tables could remain.
491
+
492
 
493
  == Changelog ==
494
+
495
+ = 5.24.0 (17-June-2021) =
496
+ * Enhancement: Option to automatically generate missing thumbnail sizes on the fly when using Custom YARPP Templates
497
+ * [New](https://wordpress.org/support/topic/remove-yarpp-from-the_content-or-the_excerpt/): Control YARPP Automatic Display programatically with filter support for `noyarpp`. For example: `add_filter( 'noyarpp', 'custom_function' );`
498
+ * Enhancement: Use the faster and less memory intensive function `strpos()` instead of `stristr()`
499
+
500
  = 5.23.0 (02-June-2021) =
501
  * [New](https://wordpress.org/support/topic/is-it-possible-to-use-different-styles-of-yarpp-in-every-post/): Ability to specify maximum number of posts to show in the YARPP shortcode. For example:
502
  + `[yarpp template="list" limit=3]` // maximum post limit set to 3
641
  * [Bugfix](https://wordpress.org/support/topic/please-exclude-the-gutenberg-blocks/): Exclude Gutenberg blocks so that they don't appear as related
642
 
643
  = 5.4.0 (03-August-2020) =
644
+ * New: Shortcode support! `[yarpp]` ([documentation](https://wordpress.org/plugins/yet-another-related-posts-plugin/#installation))
645
  * Enhancement: Adds YARPP score to REST API responses ([documentation](https://support.shareaholic.com/hc/en-us/articles/360046456752))
646
  * Enhancement: Prepare for default jQuery version update in upcoming WordPress Core
647
  * Bugfix: Fixed admin panel tooltips
1347
  * Initial upload
1348
 
1349
  == Upgrade Notice ==
1350
+ = 5.24.0 =
1351
  We update this plugin regularly so we can make it better for you. Update to the latest version for all of the available features and improvements. Thank you for using YARPP!
src/js/block.js CHANGED
@@ -1,123 +1,127 @@
1
  (function (blocks, i18n, element, components, editor, blockEditor) {
2
- var el = element.createElement;
3
- const { registerBlockType } = blocks;
4
- const { __ } = i18n; //translation functions
5
- const iconEl = el('img', {
6
- src: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTQ1cHgiIGhlaWdodD0iMTkxcHgiIHZpZXdCb3g9IjAgMCAxNDUgMTkxIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0OC4yICg0NzMyNykgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+bWFyazwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJtYXJrIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxLjAwMDAwMCwgMC4wMDAwMDApIiBmaWxsPSIjMDAwMDAwIiBmaWxsLXJ1bGU9Im5vbnplcm8iPgogICAgICAgICAgICA8ZyBpZD0iY29mZmVlIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg3MS41MDAwMDAsIDEyMC43MDM3MDQpIHNjYWxlKC0xLCAxKSByb3RhdGUoLTE4MC4wMDAwMDApIHRyYW5zbGF0ZSgtNzEuNTAwMDAwLCAtMTIwLjcwMzcwNCkgdHJhbnNsYXRlKDAuMDAwMDAwLCA1MS43MDM3MDQpIj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik00Mi44NjA1NzA2LDEzNi4wODIyOCBDMzIuODM4MzcwNSwxMzQuNzgzMzg4IDI1LjQ2Njk2OTcsMTMyLjg5OTk5NyAyMC43NDYzNjgxLDEzMC40MzIxMDMgTDE3LjM2OTMyMjUsMTI3LjgwMTg0OSBMMTcuNjk2MTMzMywxMTMuMjg2NzM4IEMxNy45MTQwMDcyLDk5LjM1NjEyOTIgMTcuOTE0MDA3Miw5OC42NzQyMTEzIDE1LjYyNjMzMSw5Ni44MjMyOTEyIEM5Ljg1MjY3MjI5LDkyLjE0NzI4MjcgMCw3OS4yNjM5ODU1IDAsNjguNTQ4MTMyNSBDMCw2My4xOTAyMDYgMS41NTkxMDc0Myw2MC4wNjIyODM2IDQuODI3MjE2MTksNTQuNDEyMTA2NiBDNy4wMDU5NTUzNSw1MC44MDc2ODMzIDEzLjUyNDk3MDMsNDUuNTM3MDMzNCAxNC43MjMyNzY5LDQ0LjU2Mjg2NDkgQzE3LjAxMDk1MjksNDMuMDA0MTk1MyAxOC40NTg2OTE5LDQ0LjEzMDMxMzggMTcuNjk2MTMzMywzMy4xMjIyMTAyIEMxNi44MjQ2Mzc2LDE5LjM4NjQzNSAxNi4wNjIwNzg5LDE3LjQyODU2MjEgMjQuMDE0NDc2OCwxMi44NDk5NzAzIEMzNC43OTkyMzU4LDYuNjE1MjkyMTkgNDIuNzUxNjMzNywzLjU5NTM2OTk3IDUyLjc3MzgzMzksMS43NDQ0NDk5IEM3Ni42MzEwMjc3LC0yLjQ0NDQ3NDQ2IDExMy4zNDI3ODMsMS4yNTczNjU2OCAxMjYuMzA2MjgsOS4xNDgxMzAxNyBDMTMzLjkzMTg2OCwxMy45MjE1NTU2IDEzNi41NDYzNTUsMTYuODQ0MDYxIDEzNi41NDYzNTUsMjAuOTM1NTY4NCBDMTQwLjQ2ODA4NSw4Ny44OTM0MTM3IDE0Mi41Mzc4ODgsMTIxLjg1OTQyIDE0Mi43NTU3NjEsMTIyLjgzMzU4OSBDMTQzLjE5MTUwOSwxMjUuMDc0MTc3IDE0Mi43NTU3NjEsMTI1LjY1ODY3NyAxMzkuMTYwODQyLDEyNy4zMTQ3NjQgQzEzNC4wNDA4MDQsMTI5LjY1Mjc2OSAxMjcuODMxMzk4LDEzMC44MjE3NzEgMTA2LjU4ODY5MSwxMzMuMzU0NjA5IEM5Ny42NTU4NjA3LDEzNC40MjYxOTQgODcuMDg4OTc1OCwxMzUuNjkyNjEzIDgzLjE2NzI0NTIsMTM2LjI3NzExNCBDNzQuNTYxMjI1NSwxMzcuNDQ2MTE2IDUyLjU1NTk2LDEzNy4zNDg2OTkgNDIuODYwNTcwNiwxMzYuMDgyMjggWiBNODQuNTMwMjczNCwxMzIuMDc4NzA0IEM5MC4yMzM4MTY3LDEzMS4zODQ4NTYgOTkuMDk4MzIxMywxMzAuMjUwMDg2IDEwOS4wMzgwODYsMTI5LjE5MzQ1IEMxMjMuMjY5NTg5LDEyNy4wMjU1MDQgMTM1LjQxOTkwMSwxMjUuNjI2MzMxIDEzNi4wNTI0MTMsMTIzLjMzMDg1OSBDMTM2LjI2MzI1LDEyMi42OTMyMjggMTIzLjkzNDI5NSwxMjAuOTc0MjM5IDEyMC4zNTAwNjQsMTE5LjgyNjUwMyBDMTE0LjEzMDM3MSwxMTcuNzg2MDg0IDEwMi4yODI2OTYsMTIwLjE4NTg4MSA5MC4zNzQ5MTk3LDEyMi40MTM1NjMgQzc4LjUwNDkyOTIsMTI0LjYzNDE3NSA2NS40NTYzNDA4LDEyMy4zMzA4NTkgNTcuMjU0NTk4NywxMjMuMzMwODU5IEM1Ny4yNTQ1OTg3LDEyMy4zMzA4NTkgNTIuNDc1NDQ2NiwxMjIuNTIzMTkzIDQyLjkxNzE0MjUsMTIwLjkwNzg2MSBDMzQuODc2MDMxNiwxMTkuNTQ4OTMxIDM2LjIyMTA1NjEsMTE5LjEyMjQ5NCAzMC4wMDEzNjIyLDEyMS44MDA1NDUgQzI2LjQxNzEzMTksMTIzLjQ1ODM4NSAyMy4yNTQ1NzU3LDEyNS4yNDM3NTIgMjMuMTQ5MTU3MiwxMjYuMDA4OTEgQzIzLjE0OTE1NzIsMTI2LjY0NjU0MSAyMy40NDM2MjM4LDEyOC40NjE1MjIgMjYuNDE3MTMxOSwxMjkuOTYyMjIxIEMzMC43NTg3ODkxLDEzMi4xNTM0MTEgNDMuNTE0MTYwMiwxMzIuNDQxMDA4IDU0LjcxNDM1NTUsMTMyLjk4NzM5NSBDNjMuNDg1ODM5OCwxMzIuOTg3Mzk1IDc4LjgyNjczMDEsMTMyLjc3MjU1MSA4NC41MzAyNzM0LDEzMi4wNzg3MDQgWiBNMzkuODcwNjc2MSwxMTYuNzY2ODQ0IEM0NC4xMjY4ODU2LDExNS43MjU4NzYgNTMuNjc3NDA0MSwxMTQuMjExNzQgNjEuMTUxNzIyOCwxMTMuMzYwMDM4IEM3OC43OTk0MjAxLDExMS4zNzI3MzQgMTM0Ljk2MDYyMSwxMTkuNTExMjE1IDEzNS4xNjgyNDEsMTE5LjIyNzMxNSBDMTM1LjM3NTg2MSwxMTkuMDM4MDQ5IDEzNC40NDE1NzEsNTQuMTE5NDYyNSAxMzEuMzI3MjcyLDI5LjcwNDAxNzcgQzEyOS44NzM5MzIsMTguOTE1Nzk3OCAxMjkuMzU0ODgyLDE3Ljk2OTQ2MjcgMTIyLjA4ODE4MywxMy40MjcwNTQ0IEMxMTAuNDYxNDY1LDYuMDQ1NjQwODQgNzQuNTQzMjEwNywyLjczMzQ2ODA4IDUzLjM2NTk3NCw2Ljk5MTk3NTkgQzQyLjk4NDk3NTcsOS4wNzM5MTMwNyAzNi43NTYzNzY3LDExLjcyMzY1MTMgMjcuNDEzNDc4MSwxNy42ODU1NjIzIEwyMi4yODExNjk0LDIxLjU4ODA4NTQgTDIzLjU3MjUwODgsMTIxLjMwOTI1MyBMMzkuODcwNjc2MSwxMTYuNzY2ODQ0IFogTTE3LjU5OTcwNDMsNjUuODAxMzgyMSBDMTcuNTk5NzA0Myw1MC44MjAwMDIzIDE4LjE3MDY1OTIsNTAuNzUyOTc1MyAxNy41OTk3MDQzLDUwLjc1Mjk3NTMgQzE0LjIyNTgzNzcsNTAuNzUyOTc1MyAxMC42ODY5OTQ2LDUzLjIwODYyOTYgNy45MzM0NTE3Miw1Ny42NDI4NTY0IEM1LjgxMDQ2NjgsNjEuMDYxNjUwNyA1LjUwMzQ2MTY2LDY1LjYzMDE2MjggNS41MDM0NjE2Niw2Ny4yMjgwNzE0IEM1LjUwMzQ2MTY2LDc4LjAyNjAyMTMgMTAuODY3NjAxOCw4Ni41MTAxNTI1IDE3LjU5OTcwNDMsODYuNTEwMTUyNSBDMTcuNTk5NzA0Myw4Ni41MTAxNTI1IDE3LjU5OTcwNDMsNzkuNjA3MjI5IDE3LjU5OTcwNDMsNjUuODAxMzgyMSBaIiBpZD0ibXVnIiBzdHJva2U9IiMwMDAwMDAiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDxnIGlkPSJGYWNlIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg1MC45NDI4NTAsIDYwLjQwMDc5NykiPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02Mi4xNjA3NzgsMzMuNTQ3NTgzNSBDNTguNDA4MjI2MiwyNi42MDQxNTMzIDYwLjExMzkzMTYsMTkuMDI5NTAyMiA2NC44ODk5MDY2LDE5LjAyOTUwMjIgQzY3LjYxOTAzNTMsMTkuMDI5NTAyMiA3MC42ODkzMDQ5LDIxLjU1NDM4NiA3MS43MTI3MjgyLDI0LjcxMDQ5MDYgQzc0LjEwMDcxNTcsMzEuMDIyNjk5OSA2NS4yMzEwNDc4LDM5LjIyODU3MTggNjIuMTYwNzc4LDMzLjU0NzU4MzUgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTIuMTAzMDM4MzcsMzQuMDA2MTkwNiBDLTEuNjQ5NTEzNDksMjcuMDYyNzYwMyAwLjA1NjE5MTkwMTksMTkuNDg4MTA5MiA0LjgzMjE2NywxOS40ODgxMDkyIEM3LjU2MTI5NTYzLDE5LjQ4ODEwOTIgMTAuNjMxNTY1MywyMi4wMTI5OTI5IDExLjY1NDk4ODUsMjUuMTY5MDk3NiBDMTQuMDQyOTc2MSwzMS40ODEzMDY4IDUuMTczMzA4MDgsMzkuNjg3MTc4OSAyLjEwMzAzODM3LDM0LjAwNjE5MDYgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTMxLjI3NDQ0ODEsMTMuNDg2Nzc4OCBDMjIuMzUyNjcyOCw5Ljc1NzE4ODQ0IDIyLjM1MjY3MjgsNi44NTYzOTU5NyAzMS42OTkyOTQ2LDIuOTE5NjA2MTggQzQyLjEwODAzMjQsLTEuMjI0MzgzMDcgNTQuNjQxMDAyNSwtMC44MDk5ODQxNDcgNTkuMTAxODkwMiwzLjc0ODQwNDAzIEM2Mi4yODgyMzg1LDcuNDc3OTk0MzUgNjIuMjg4MjM4NSw3Ljg5MjM5MzI4IDU4Ljg4OTQ2NjksMTAuNzkzMTg1OCBDNTMuMTU0MDM5OSwxNS43NjU5NzI5IDM5LjM0NjUzMDUsMTcuMDA5MTY5NiAzMS4yNzQ0NDgxLDEzLjQ4Njc3ODggWiBNMzQuOTc2NzUxLDcuOTA3NDgwOTMgQzMxLjkwMDc0OTksMTAuMTEwNDkzNyAzNi42OTIxOTYxLDEwLjMyOTQyNTggNDQuNzk0NzQwOCw5LjkxNzg4MDc4IEM1Ni4wMTA3NjU5LDkuMjAxOTk3NDEgNTYuMTM5MTMwOSw0LjQyOTQzMDIxIDQ0LjcxMDU0MzIsNC45MTI0NDYyMyBDMzkuOTU1OTI2OCw1LjA0NDI5NDI5IDM1Ljc0NTc1MTMsNy4zNTY3Mjc3NSAzNC45NzY3NTEsNy45MDc0ODA5MyBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8ZyBpZD0iU3RlYW0iIHRyYW5zZm9ybT0idHJhbnNsYXRlKDU5LjAwMDAwMCwgMC4wMDAwMDApIj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik00LjE2MDcyNzYzLDAgQzMuODM3ODQ1OSwyLjYzMDYwNzA1IDMuNjM2ODk2NjIsNS4zMDMwNTE1OSAzLjU1OTg2MzAyLDcuOTkwOTU4NDEgQzMuNTAzOTksMTEuNzQ3MDY3OSA0LjM0NTcxNTczLDE1LjM3MjE2MjYgNS44ODAxMjQ4MywxNy45ODM3MjUxIEM2Ljg5MDgwOTkzLDE5Ljc5NTY2IDcuODk1MzMyMywyMS42MjM4Njk4IDguODkzNjkxOTYsMjMuNDY4MzU0NCBDOS45NDgxNjY2MywyNS4zNTQ0ODk1IDEwLjY1MTEyNjEsMjcuNzYxNTg3NSAxMC45MDg4OTk0LDMwLjM2ODg5NjkgQzExLjIxOTk2NDQsMzMuNTA1NjYyMyAxMC43MjU3NDQzLDM2LjcyMzg3OTUgOS41NTkyNjUwOCwzOS4xNTczMjM3IEM4LjMyNzMwNjcyLDQxLjc4NjcwODYgNi42NzAxMDYxOCw0My42OTM5NDg1IDQuODA3ODEyNiw0NC42MjU2NzgxIEw0LjE2MDcyNzYzLDQ1IEM0LjU0ODk3ODYyLDQzLjc5NTY2IDQuOTE4NzQxNDUsNDIuNjg4OTY5MiA1LjI2MDc3MjA4LDQxLjU2NjAwMzYgQzUuNzIyOTc1NjMsNDAuMDUyNDQxMiA2LjE4NTE3OTE3LDM4LjUzODg3ODkgNi42MTA0MDY0NCwzNi45NzY0OTE5IEM3LjEwOTgxODQzLDM1LjIzMjYwNTYgNy4wNTAwOTQzNCwzMy4xNTQzNzM1IDYuNDUzMjU3MjMsMzEuNTA4MTM3NCBDNi4yMjkzNzk3LDMwLjkyMTQxNDkgNS45NzIzMTQ0NiwzMC4zNzYxMzUxIDUuNjg1OTk5MzQsMjkuODgwNjUxIEM0LjY2OTE1MTUzLDI4LjA0MTU5MTQgMy42MjQ1NzE1MiwyNi4yNjc2MzExIDIuNjM1NDU1OTIsMjQuNDEyMjk2NiBDMS40NTE3ODQ1NCwyMi4yNjgxOTg3IDAuNjIzODI5MjUsMTkuNTk0ODU0NyAwLjI0MTI0MTU0MiwxNi42ODE3MzYgQy0wLjQzODk4OTM5NiwxMS43NzA5NzU3IDAuMzQwNTA0MzQyLDYuNTg3ODgxNzIgMi4zMTE5MTM0MywyLjkxMzIwMDczIEMyLjc2NDg3MjkxLDIuMDE4MDgzMTkgMy4zMDEwMjkwMywxLjI4NTcxNDI5IDMuODAwMjA4ODcsMC40NTU2OTYyMDIgTDQuMDY4Mjg2OTIsNS4wNTkyNDQxNmUtMTUgTDQuMTYwNzI3NjMsMCBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik00MiwyMi4yNzg0MzM1IEM0MS41MDg3NTY2LDIzLjI0Nzc0OCA0MS4wMzY3Nzc2LDI0LjE3NTUyMDUgNDAuNTU1MTY2NCwyNS4xNTg2ODIzIEM0MC4xODQ1MjQ5LDI1Ljk1MjczODQgMzkuODYyMjU0NSwyNi43OTEzMDc5IDM5LjU5MTk0NCwyNy42NjUwNTI4IEMzOS4yOTU2OTQzLDI4Ljg5MjY3NTUgMzkuMjI5MjU3MSwzMC4yMTA3MjI5IDM5LjM5OTI5OTQsMzEuNDg2OTIxNCBDMzkuNTQzNzgyOSwzMy40MjU1NTA0IDM5LjcyNjc5NTEsMzUuMzY0MTc5NSAzOS44MDM4NTI5LDM3LjMwMjgwODUgQzM5Ljg1NjMxMzIsMzguOTU2Nzk5MyAzOS41MTY3MTU1LDQwLjU4NzQxNCAzOC44NDA2MzA1LDQxLjkyNzgyMzUgQzM4LjAxMDUwMjcsNDMuNjk1MDc1NCAzNi42NjAyMTU1LDQ0LjgxMzgwOTIgMzUuMTgwMzg1Myw0NC45NjAzOTMyIEMzMy43MjAwMDUsNDUuMTQ4NDYwOCAzMi4yNTU4ODU1LDQ0LjY2MzQ3NzQgMzEsNDMuNTc1NjU4MSBMMzEuMTM0ODUxMSw0My40MDk0ODk5IEMzMi4wOTgwNzM2LDQyLjQ5NTU2NDkgMzMuMTI4NzIxNSw0MS41OTU0ODcxIDM0LjEwMTU3NjIsNDAuNjQwMDE5OSBDMzQuNzYwMzc3MSw0MC4wNjgxMTA0IDM1LjA3ODA5MzUsMzguOTQwMzI5NiAzNC44ODE3ODYzLDM3Ljg3MDU0OTkgQzM0LjUzOTkyMDgsMzUuNTA3MDY1NyAzNC4zNzUyMzI1LDMzLjA5NzcxNjYgMzQuMzkwNTQzLDMwLjY4Mzc3NSBDMzQuNTUzMDI0NywyNi4zNjI2MjcyIDM2Ljc5MjQzMTgsMjIuNzkxMzAwNCAzOS43NjUzMjQsMjIuMTEyMjY1MyBDNDAuNDE5NDA4MSwyMS45NjI1NzgyIDQxLjA4NTg0NTcsMjEuOTYyNTc4MiA0MS43Mzk5Mjk5LDIyLjExMjI2NTMgTDQxLjg4NDQxMzQsMjIuMTEyMjY1MyBMNDIsMjIuMjc4NDMzNSBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+',
7
- });
8
- var ServerSideRender = wp.serverSideRender;
9
- const { RichText, InspectorControls } = blockEditor;
10
- const {
11
- TextControl,
12
- CheckboxControl,
13
- RadioControl,
14
- SelectControl,
15
- TextareaControl,
16
- ToggleControl,
17
- RangeControl,
18
- Panel,
19
- PanelBody,
20
- PanelRow,
21
- } = components;
22
 
23
- registerBlockType('yarpp/yarpp-block', {
24
- title: __('YARPP Block', 'yarpp'),
25
- description: __('Display related posts by YARPP', 'yarpp'),
26
- category: 'yarpp',
27
- icon: iconEl,
28
- keywords: [__('yarpp', 'yarpp'), __('related posts', 'yarpp'), __('posts', 'yarpp')],
29
- supports: {
30
- html: false,
31
- },
 
 
 
 
32
 
33
- attributes: {
34
- limit: {
35
- type: 'number',
36
- default: 6,
37
- },
38
- template: {
39
- type: 'string',
40
- default: yarpp_localized.selected_theme_style,
41
- },
42
- yarpp_preview: {
43
- type: 'string',
44
- },
45
- },
46
- example: {
47
- attributes: {
48
- yarpp_preview: 'yarpp_preview',
49
- },
50
- },
51
- edit: function (props) {
52
- const attributes = props.attributes;
53
- const setAttributes = props.setAttributes;
54
- var template = Object.keys(yarpp_localized.template).map(function (key) {
55
- return { value: key, label: yarpp_localized.template[key] };
56
- });
57
 
58
- if (props.isSelected) {
59
- // console.debug(props.attributes);
60
- }
61
 
62
- // Functions to update attributes.
63
- function changeThumbnail(template) {
64
- setAttributes({ template });
65
- }
66
 
67
- return [
68
- /**
69
- * Server side render
70
- */
71
- el(
72
- 'div',
73
- { className: props.className },
74
- el(ServerSideRender, {
75
- block: 'yarpp/yarpp-block',
76
- attributes: attributes,
77
- }),
78
- ),
79
 
80
- /**
81
- * Inspector
82
- */
83
- el(
84
- InspectorControls,
85
- {},
86
- el(
87
- PanelBody,
88
- { title: 'YARPP Posts Settings', initialOpen: true },
89
 
90
- el(TextControl, {
91
- label: __('Maximum number of posts', 'yarpp'),
92
- value: attributes.limit,
93
- onChange: function (val) {
94
- setAttributes({ limit: parseInt(val) });
95
- },
96
- type: 'number',
97
- min: 1,
98
- step: 1,
99
- }),
100
- el(SelectControl, {
101
- value: attributes.template,
102
- label: __('Theme', 'yarpp'),
103
- onChange: changeThumbnail,
104
- options: template,
105
- }),
106
- ),
107
- ),
108
- ];
109
- },
110
 
111
- save() {
112
- return null; //save has to exist. This all we need
113
- },
114
- });
115
  })(
116
- window.wp.blocks,
117
- window.wp.i18n,
118
- window.wp.element,
119
- window.wp.components,
120
- window.wp.editor,
121
- window.wp.blockEditor,
122
- window.wp.serverSideRender,
123
  );
1
  (function (blocks, i18n, element, components, editor, blockEditor) {
2
+ var el = element.createElement;
3
+ const { registerBlockType } = blocks;
4
+ const { __ } = i18n; //translation functions
5
+ const iconEl = el('img', {
6
+ src: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTQ1cHgiIGhlaWdodD0iMTkxcHgiIHZpZXdCb3g9IjAgMCAxNDUgMTkxIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0OC4yICg0NzMyNykgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+bWFyazwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJtYXJrIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxLjAwMDAwMCwgMC4wMDAwMDApIiBmaWxsPSIjMDAwMDAwIiBmaWxsLXJ1bGU9Im5vbnplcm8iPgogICAgICAgICAgICA8ZyBpZD0iY29mZmVlIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg3MS41MDAwMDAsIDEyMC43MDM3MDQpIHNjYWxlKC0xLCAxKSByb3RhdGUoLTE4MC4wMDAwMDApIHRyYW5zbGF0ZSgtNzEuNTAwMDAwLCAtMTIwLjcwMzcwNCkgdHJhbnNsYXRlKDAuMDAwMDAwLCA1MS43MDM3MDQpIj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik00Mi44NjA1NzA2LDEzNi4wODIyOCBDMzIuODM4MzcwNSwxMzQuNzgzMzg4IDI1LjQ2Njk2OTcsMTMyLjg5OTk5NyAyMC43NDYzNjgxLDEzMC40MzIxMDMgTDE3LjM2OTMyMjUsMTI3LjgwMTg0OSBMMTcuNjk2MTMzMywxMTMuMjg2NzM4IEMxNy45MTQwMDcyLDk5LjM1NjEyOTIgMTcuOTE0MDA3Miw5OC42NzQyMTEzIDE1LjYyNjMzMSw5Ni44MjMyOTEyIEM5Ljg1MjY3MjI5LDkyLjE0NzI4MjcgMCw3OS4yNjM5ODU1IDAsNjguNTQ4MTMyNSBDMCw2My4xOTAyMDYgMS41NTkxMDc0Myw2MC4wNjIyODM2IDQuODI3MjE2MTksNTQuNDEyMTA2NiBDNy4wMDU5NTUzNSw1MC44MDc2ODMzIDEzLjUyNDk3MDMsNDUuNTM3MDMzNCAxNC43MjMyNzY5LDQ0LjU2Mjg2NDkgQzE3LjAxMDk1MjksNDMuMDA0MTk1MyAxOC40NTg2OTE5LDQ0LjEzMDMxMzggMTcuNjk2MTMzMywzMy4xMjIyMTAyIEMxNi44MjQ2Mzc2LDE5LjM4NjQzNSAxNi4wNjIwNzg5LDE3LjQyODU2MjEgMjQuMDE0NDc2OCwxMi44NDk5NzAzIEMzNC43OTkyMzU4LDYuNjE1MjkyMTkgNDIuNzUxNjMzNywzLjU5NTM2OTk3IDUyLjc3MzgzMzksMS43NDQ0NDk5IEM3Ni42MzEwMjc3LC0yLjQ0NDQ3NDQ2IDExMy4zNDI3ODMsMS4yNTczNjU2OCAxMjYuMzA2MjgsOS4xNDgxMzAxNyBDMTMzLjkzMTg2OCwxMy45MjE1NTU2IDEzNi41NDYzNTUsMTYuODQ0MDYxIDEzNi41NDYzNTUsMjAuOTM1NTY4NCBDMTQwLjQ2ODA4NSw4Ny44OTM0MTM3IDE0Mi41Mzc4ODgsMTIxLjg1OTQyIDE0Mi43NTU3NjEsMTIyLjgzMzU4OSBDMTQzLjE5MTUwOSwxMjUuMDc0MTc3IDE0Mi43NTU3NjEsMTI1LjY1ODY3NyAxMzkuMTYwODQyLDEyNy4zMTQ3NjQgQzEzNC4wNDA4MDQsMTI5LjY1Mjc2OSAxMjcuODMxMzk4LDEzMC44MjE3NzEgMTA2LjU4ODY5MSwxMzMuMzU0NjA5IEM5Ny42NTU4NjA3LDEzNC40MjYxOTQgODcuMDg4OTc1OCwxMzUuNjkyNjEzIDgzLjE2NzI0NTIsMTM2LjI3NzExNCBDNzQuNTYxMjI1NSwxMzcuNDQ2MTE2IDUyLjU1NTk2LDEzNy4zNDg2OTkgNDIuODYwNTcwNiwxMzYuMDgyMjggWiBNODQuNTMwMjczNCwxMzIuMDc4NzA0IEM5MC4yMzM4MTY3LDEzMS4zODQ4NTYgOTkuMDk4MzIxMywxMzAuMjUwMDg2IDEwOS4wMzgwODYsMTI5LjE5MzQ1IEMxMjMuMjY5NTg5LDEyNy4wMjU1MDQgMTM1LjQxOTkwMSwxMjUuNjI2MzMxIDEzNi4wNTI0MTMsMTIzLjMzMDg1OSBDMTM2LjI2MzI1LDEyMi42OTMyMjggMTIzLjkzNDI5NSwxMjAuOTc0MjM5IDEyMC4zNTAwNjQsMTE5LjgyNjUwMyBDMTE0LjEzMDM3MSwxMTcuNzg2MDg0IDEwMi4yODI2OTYsMTIwLjE4NTg4MSA5MC4zNzQ5MTk3LDEyMi40MTM1NjMgQzc4LjUwNDkyOTIsMTI0LjYzNDE3NSA2NS40NTYzNDA4LDEyMy4zMzA4NTkgNTcuMjU0NTk4NywxMjMuMzMwODU5IEM1Ny4yNTQ1OTg3LDEyMy4zMzA4NTkgNTIuNDc1NDQ2NiwxMjIuNTIzMTkzIDQyLjkxNzE0MjUsMTIwLjkwNzg2MSBDMzQuODc2MDMxNiwxMTkuNTQ4OTMxIDM2LjIyMTA1NjEsMTE5LjEyMjQ5NCAzMC4wMDEzNjIyLDEyMS44MDA1NDUgQzI2LjQxNzEzMTksMTIzLjQ1ODM4NSAyMy4yNTQ1NzU3LDEyNS4yNDM3NTIgMjMuMTQ5MTU3MiwxMjYuMDA4OTEgQzIzLjE0OTE1NzIsMTI2LjY0NjU0MSAyMy40NDM2MjM4LDEyOC40NjE1MjIgMjYuNDE3MTMxOSwxMjkuOTYyMjIxIEMzMC43NTg3ODkxLDEzMi4xNTM0MTEgNDMuNTE0MTYwMiwxMzIuNDQxMDA4IDU0LjcxNDM1NTUsMTMyLjk4NzM5NSBDNjMuNDg1ODM5OCwxMzIuOTg3Mzk1IDc4LjgyNjczMDEsMTMyLjc3MjU1MSA4NC41MzAyNzM0LDEzMi4wNzg3MDQgWiBNMzkuODcwNjc2MSwxMTYuNzY2ODQ0IEM0NC4xMjY4ODU2LDExNS43MjU4NzYgNTMuNjc3NDA0MSwxMTQuMjExNzQgNjEuMTUxNzIyOCwxMTMuMzYwMDM4IEM3OC43OTk0MjAxLDExMS4zNzI3MzQgMTM0Ljk2MDYyMSwxMTkuNTExMjE1IDEzNS4xNjgyNDEsMTE5LjIyNzMxNSBDMTM1LjM3NTg2MSwxMTkuMDM4MDQ5IDEzNC40NDE1NzEsNTQuMTE5NDYyNSAxMzEuMzI3MjcyLDI5LjcwNDAxNzcgQzEyOS44NzM5MzIsMTguOTE1Nzk3OCAxMjkuMzU0ODgyLDE3Ljk2OTQ2MjcgMTIyLjA4ODE4MywxMy40MjcwNTQ0IEMxMTAuNDYxNDY1LDYuMDQ1NjQwODQgNzQuNTQzMjEwNywyLjczMzQ2ODA4IDUzLjM2NTk3NCw2Ljk5MTk3NTkgQzQyLjk4NDk3NTcsOS4wNzM5MTMwNyAzNi43NTYzNzY3LDExLjcyMzY1MTMgMjcuNDEzNDc4MSwxNy42ODU1NjIzIEwyMi4yODExNjk0LDIxLjU4ODA4NTQgTDIzLjU3MjUwODgsMTIxLjMwOTI1MyBMMzkuODcwNjc2MSwxMTYuNzY2ODQ0IFogTTE3LjU5OTcwNDMsNjUuODAxMzgyMSBDMTcuNTk5NzA0Myw1MC44MjAwMDIzIDE4LjE3MDY1OTIsNTAuNzUyOTc1MyAxNy41OTk3MDQzLDUwLjc1Mjk3NTMgQzE0LjIyNTgzNzcsNTAuNzUyOTc1MyAxMC42ODY5OTQ2LDUzLjIwODYyOTYgNy45MzM0NTE3Miw1Ny42NDI4NTY0IEM1LjgxMDQ2NjgsNjEuMDYxNjUwNyA1LjUwMzQ2MTY2LDY1LjYzMDE2MjggNS41MDM0NjE2Niw2Ny4yMjgwNzE0IEM1LjUwMzQ2MTY2LDc4LjAyNjAyMTMgMTAuODY3NjAxOCw4Ni41MTAxNTI1IDE3LjU5OTcwNDMsODYuNTEwMTUyNSBDMTcuNTk5NzA0Myw4Ni41MTAxNTI1IDE3LjU5OTcwNDMsNzkuNjA3MjI5IDE3LjU5OTcwNDMsNjUuODAxMzgyMSBaIiBpZD0ibXVnIiBzdHJva2U9IiMwMDAwMDAiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDxnIGlkPSJGYWNlIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg1MC45NDI4NTAsIDYwLjQwMDc5NykiPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02Mi4xNjA3NzgsMzMuNTQ3NTgzNSBDNTguNDA4MjI2MiwyNi42MDQxNTMzIDYwLjExMzkzMTYsMTkuMDI5NTAyMiA2NC44ODk5MDY2LDE5LjAyOTUwMjIgQzY3LjYxOTAzNTMsMTkuMDI5NTAyMiA3MC42ODkzMDQ5LDIxLjU1NDM4NiA3MS43MTI3MjgyLDI0LjcxMDQ5MDYgQzc0LjEwMDcxNTcsMzEuMDIyNjk5OSA2NS4yMzEwNDc4LDM5LjIyODU3MTggNjIuMTYwNzc4LDMzLjU0NzU4MzUgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTIuMTAzMDM4MzcsMzQuMDA2MTkwNiBDLTEuNjQ5NTEzNDksMjcuMDYyNzYwMyAwLjA1NjE5MTkwMTksMTkuNDg4MTA5MiA0LjgzMjE2NywxOS40ODgxMDkyIEM3LjU2MTI5NTYzLDE5LjQ4ODEwOTIgMTAuNjMxNTY1MywyMi4wMTI5OTI5IDExLjY1NDk4ODUsMjUuMTY5MDk3NiBDMTQuMDQyOTc2MSwzMS40ODEzMDY4IDUuMTczMzA4MDgsMzkuNjg3MTc4OSAyLjEwMzAzODM3LDM0LjAwNjE5MDYgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTMxLjI3NDQ0ODEsMTMuNDg2Nzc4OCBDMjIuMzUyNjcyOCw5Ljc1NzE4ODQ0IDIyLjM1MjY3MjgsNi44NTYzOTU5NyAzMS42OTkyOTQ2LDIuOTE5NjA2MTggQzQyLjEwODAzMjQsLTEuMjI0MzgzMDcgNTQuNjQxMDAyNSwtMC44MDk5ODQxNDcgNTkuMTAxODkwMiwzLjc0ODQwNDAzIEM2Mi4yODgyMzg1LDcuNDc3OTk0MzUgNjIuMjg4MjM4NSw3Ljg5MjM5MzI4IDU4Ljg4OTQ2NjksMTAuNzkzMTg1OCBDNTMuMTU0MDM5OSwxNS43NjU5NzI5IDM5LjM0NjUzMDUsMTcuMDA5MTY5NiAzMS4yNzQ0NDgxLDEzLjQ4Njc3ODggWiBNMzQuOTc2NzUxLDcuOTA3NDgwOTMgQzMxLjkwMDc0OTksMTAuMTEwNDkzNyAzNi42OTIxOTYxLDEwLjMyOTQyNTggNDQuNzk0NzQwOCw5LjkxNzg4MDc4IEM1Ni4wMTA3NjU5LDkuMjAxOTk3NDEgNTYuMTM5MTMwOSw0LjQyOTQzMDIxIDQ0LjcxMDU0MzIsNC45MTI0NDYyMyBDMzkuOTU1OTI2OCw1LjA0NDI5NDI5IDM1Ljc0NTc1MTMsNy4zNTY3Mjc3NSAzNC45NzY3NTEsNy45MDc0ODA5MyBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8ZyBpZD0iU3RlYW0iIHRyYW5zZm9ybT0idHJhbnNsYXRlKDU5LjAwMDAwMCwgMC4wMDAwMDApIj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik00LjE2MDcyNzYzLDAgQzMuODM3ODQ1OSwyLjYzMDYwNzA1IDMuNjM2ODk2NjIsNS4zMDMwNTE1OSAzLjU1OTg2MzAyLDcuOTkwOTU4NDEgQzMuNTAzOTksMTEuNzQ3MDY3OSA0LjM0NTcxNTczLDE1LjM3MjE2MjYgNS44ODAxMjQ4MywxNy45ODM3MjUxIEM2Ljg5MDgwOTkzLDE5Ljc5NTY2IDcuODk1MzMyMywyMS42MjM4Njk4IDguODkzNjkxOTYsMjMuNDY4MzU0NCBDOS45NDgxNjY2MywyNS4zNTQ0ODk1IDEwLjY1MTEyNjEsMjcuNzYxNTg3NSAxMC45MDg4OTk0LDMwLjM2ODg5NjkgQzExLjIxOTk2NDQsMzMuNTA1NjYyMyAxMC43MjU3NDQzLDM2LjcyMzg3OTUgOS41NTkyNjUwOCwzOS4xNTczMjM3IEM4LjMyNzMwNjcyLDQxLjc4NjcwODYgNi42NzAxMDYxOCw0My42OTM5NDg1IDQuODA3ODEyNiw0NC42MjU2NzgxIEw0LjE2MDcyNzYzLDQ1IEM0LjU0ODk3ODYyLDQzLjc5NTY2IDQuOTE4NzQxNDUsNDIuNjg4OTY5MiA1LjI2MDc3MjA4LDQxLjU2NjAwMzYgQzUuNzIyOTc1NjMsNDAuMDUyNDQxMiA2LjE4NTE3OTE3LDM4LjUzODg3ODkgNi42MTA0MDY0NCwzNi45NzY0OTE5IEM3LjEwOTgxODQzLDM1LjIzMjYwNTYgNy4wNTAwOTQzNCwzMy4xNTQzNzM1IDYuNDUzMjU3MjMsMzEuNTA4MTM3NCBDNi4yMjkzNzk3LDMwLjkyMTQxNDkgNS45NzIzMTQ0NiwzMC4zNzYxMzUxIDUuNjg1OTk5MzQsMjkuODgwNjUxIEM0LjY2OTE1MTUzLDI4LjA0MTU5MTQgMy42MjQ1NzE1MiwyNi4yNjc2MzExIDIuNjM1NDU1OTIsMjQuNDEyMjk2NiBDMS40NTE3ODQ1NCwyMi4yNjgxOTg3IDAuNjIzODI5MjUsMTkuNTk0ODU0NyAwLjI0MTI0MTU0MiwxNi42ODE3MzYgQy0wLjQzODk4OTM5NiwxMS43NzA5NzU3IDAuMzQwNTA0MzQyLDYuNTg3ODgxNzIgMi4zMTE5MTM0MywyLjkxMzIwMDczIEMyLjc2NDg3MjkxLDIuMDE4MDgzMTkgMy4zMDEwMjkwMywxLjI4NTcxNDI5IDMuODAwMjA4ODcsMC40NTU2OTYyMDIgTDQuMDY4Mjg2OTIsNS4wNTkyNDQxNmUtMTUgTDQuMTYwNzI3NjMsMCBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik00MiwyMi4yNzg0MzM1IEM0MS41MDg3NTY2LDIzLjI0Nzc0OCA0MS4wMzY3Nzc2LDI0LjE3NTUyMDUgNDAuNTU1MTY2NCwyNS4xNTg2ODIzIEM0MC4xODQ1MjQ5LDI1Ljk1MjczODQgMzkuODYyMjU0NSwyNi43OTEzMDc5IDM5LjU5MTk0NCwyNy42NjUwNTI4IEMzOS4yOTU2OTQzLDI4Ljg5MjY3NTUgMzkuMjI5MjU3MSwzMC4yMTA3MjI5IDM5LjM5OTI5OTQsMzEuNDg2OTIxNCBDMzkuNTQzNzgyOSwzMy40MjU1NTA0IDM5LjcyNjc5NTEsMzUuMzY0MTc5NSAzOS44MDM4NTI5LDM3LjMwMjgwODUgQzM5Ljg1NjMxMzIsMzguOTU2Nzk5MyAzOS41MTY3MTU1LDQwLjU4NzQxNCAzOC44NDA2MzA1LDQxLjkyNzgyMzUgQzM4LjAxMDUwMjcsNDMuNjk1MDc1NCAzNi42NjAyMTU1LDQ0LjgxMzgwOTIgMzUuMTgwMzg1Myw0NC45NjAzOTMyIEMzMy43MjAwMDUsNDUuMTQ4NDYwOCAzMi4yNTU4ODU1LDQ0LjY2MzQ3NzQgMzEsNDMuNTc1NjU4MSBMMzEuMTM0ODUxMSw0My40MDk0ODk5IEMzMi4wOTgwNzM2LDQyLjQ5NTU2NDkgMzMuMTI4NzIxNSw0MS41OTU0ODcxIDM0LjEwMTU3NjIsNDAuNjQwMDE5OSBDMzQuNzYwMzc3MSw0MC4wNjgxMTA0IDM1LjA3ODA5MzUsMzguOTQwMzI5NiAzNC44ODE3ODYzLDM3Ljg3MDU0OTkgQzM0LjUzOTkyMDgsMzUuNTA3MDY1NyAzNC4zNzUyMzI1LDMzLjA5NzcxNjYgMzQuMzkwNTQzLDMwLjY4Mzc3NSBDMzQuNTUzMDI0NywyNi4zNjI2MjcyIDM2Ljc5MjQzMTgsMjIuNzkxMzAwNCAzOS43NjUzMjQsMjIuMTEyMjY1MyBDNDAuNDE5NDA4MSwyMS45NjI1NzgyIDQxLjA4NTg0NTcsMjEuOTYyNTc4MiA0MS43Mzk5Mjk5LDIyLjExMjI2NTMgTDQxLjg4NDQxMzQsMjIuMTEyMjY1MyBMNDIsMjIuMjc4NDMzNSBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+',
7
+ });
8
+ var ServerSideRender = wp.serverSideRender;
9
+ const { RichText, InspectorControls } = blockEditor;
10
+ const {
11
+ TextControl,
12
+ CheckboxControl,
13
+ RadioControl,
14
+ SelectControl,
15
+ TextareaControl,
16
+ ToggleControl,
17
+ RangeControl,
18
+ Panel,
19
+ PanelBody,
20
+ PanelRow,
21
+ } = components;
22
 
23
+ registerBlockType('yarpp/yarpp-block', {
24
+ title: __('YARPP Block', 'yarpp'),
25
+ description: __('Display related posts by YARPP', 'yarpp'),
26
+ category: 'yarpp',
27
+ icon: iconEl,
28
+ keywords: [
29
+ __('yarpp', 'yarpp'),
30
+ __('related posts', 'yarpp'),
31
+ __('posts', 'yarpp'),
32
+ ],
33
+ supports: {
34
+ html: false,
35
+ },
36
 
37
+ attributes: {
38
+ limit: {
39
+ type: 'number',
40
+ default: 6,
41
+ },
42
+ template: {
43
+ type: 'string',
44
+ default: yarpp_localized.selected_theme_style,
45
+ },
46
+ yarpp_preview: {
47
+ type: 'string',
48
+ },
49
+ },
50
+ example: {
51
+ attributes: {
52
+ yarpp_preview: 'yarpp_preview',
53
+ },
54
+ },
55
+ edit: function (props) {
56
+ const attributes = props.attributes;
57
+ const setAttributes = props.setAttributes;
58
+ var template = Object.keys(yarpp_localized.template).map(function (key) {
59
+ return { value: key, label: yarpp_localized.template[key] };
60
+ });
61
 
62
+ if (props.isSelected) {
63
+ // console.debug(props.attributes);
64
+ }
65
 
66
+ // Functions to update attributes.
67
+ function changeThumbnail(template) {
68
+ setAttributes({ template });
69
+ }
70
 
71
+ return [
72
+ /**
73
+ * Server side render
74
+ */
75
+ el(
76
+ 'div',
77
+ { className: props.className },
78
+ el(ServerSideRender, {
79
+ block: 'yarpp/yarpp-block',
80
+ attributes: attributes,
81
+ }),
82
+ ),
83
 
84
+ /**
85
+ * Inspector
86
+ */
87
+ el(
88
+ InspectorControls,
89
+ {},
90
+ el(
91
+ PanelBody,
92
+ { title: 'YARPP Posts Settings', initialOpen: true },
93
 
94
+ el(TextControl, {
95
+ label: __('Maximum number of posts', 'yarpp'),
96
+ value: attributes.limit,
97
+ onChange: function (val) {
98
+ setAttributes({ limit: parseInt(val) });
99
+ },
100
+ type: 'number',
101
+ min: 1,
102
+ step: 1,
103
+ }),
104
+ el(SelectControl, {
105
+ value: attributes.template,
106
+ label: __('Theme', 'yarpp'),
107
+ onChange: changeThumbnail,
108
+ options: template,
109
+ }),
110
+ ),
111
+ ),
112
+ ];
113
+ },
114
 
115
+ save() {
116
+ return null; //save has to exist. This all we need
117
+ },
118
+ });
119
  })(
120
+ window.wp.blocks,
121
+ window.wp.i18n,
122
+ window.wp.element,
123
+ window.wp.components,
124
+ window.wp.editor,
125
+ window.wp.blockEditor,
126
+ window.wp.serverSideRender,
127
  );
src/js/metabox.js CHANGED
@@ -1,84 +1,84 @@
1
  jQuery(document).ready(function ($) {
2
- var loaded_metabox = false;
3
- var display = $('#yarpp-related-posts');
4
 
5
- /*
6
- * Populates Metabox initially
7
- */
8
- function yarpp_metabox_initial_display() {
9
- if (!$('#yarpp_relatedposts') || !display.length || !$('#post_ID').val()) return;
10
 
11
- if (!loaded_metabox) {
12
- loaded_metabox = true;
13
- yarpp_metabox_populate(false);
14
- }
15
- }
16
 
17
- /*
18
- * Populates Metabox
19
- * @param bool refresh
20
- */
21
- function yarpp_metabox_populate(refresh) {
22
- var data = {
23
- action: 'yarpp_display',
24
- domain: 'metabox',
25
- ID: parseInt($('#post_ID').val()),
26
- _ajax_nonce: $('#yarpp_display-nonce').val(),
27
- };
28
- if (typeof refresh !== 'undefined' && refresh) {
29
- data['refresh'] = true;
30
- }
31
- $.ajax({
32
- type: 'POST',
33
- url: ajaxurl,
34
- data: data,
35
- error: function () {
36
- display.html('Error');
37
- },
38
- success: function (html) {
39
- display.html(html);
40
- },
41
- dataType: 'html',
42
- });
43
- }
44
 
45
- $('#yarpp_relatedposts .handlediv, #yarpp_relatedposts-hide').click(function () {
46
- setTimeout(yarpp_metabox_initial_display, 0);
47
- });
48
 
49
- /*
50
- * Metabox Actions
51
- */
52
- $(document).on('touchstart mouseenter', '#yarpp-list li', function () {
53
- $(this).children('.yarpp-related-action').css('visibility', 'visible');
54
- });
55
 
56
- $(document).on('touchend mouseleave', '#yarpp-list li', function () {
57
- $(this).children('.yarpp-related-action').css('visibility', 'hidden');
58
- });
59
 
60
- /*
61
- * Metabox Refresh Button
62
- */
63
- $(document).on('click', '#yarpp-refresh', function (e) {
64
- e.preventDefault();
65
 
66
- var display = $('#yarpp-related-posts');
67
 
68
- if ($(this).hasClass('disabled')) return false;
69
 
70
- const refresh_button = $(this);
71
- const spinner = refresh_button.siblings('.spinner');
72
 
73
- refresh_button.addClass('yarpp-disabled');
74
- spinner.css('visibility', 'visible');
75
 
76
- $('#yarpp-list').css('opacity', 0.6);
77
- yarpp_metabox_populate(true);
78
- });
79
 
80
- /*
81
- * Initial Load
82
- */
83
- yarpp_metabox_initial_display();
84
  });
1
  jQuery(document).ready(function ($) {
2
+ var loaded_metabox = false;
3
+ var display = $('#yarpp-related-posts');
4
 
5
+ /*
6
+ * Populates Metabox initially
7
+ */
8
+ function yarpp_metabox_initial_display() {
9
+ if (!$('#yarpp_relatedposts') || !display.length || !$('#post_ID').val()) return;
10
 
11
+ if (!loaded_metabox) {
12
+ loaded_metabox = true;
13
+ yarpp_metabox_populate(false);
14
+ }
15
+ }
16
 
17
+ /*
18
+ * Populates Metabox
19
+ * @param bool refresh
20
+ */
21
+ function yarpp_metabox_populate(refresh) {
22
+ var data = {
23
+ action: 'yarpp_display',
24
+ domain: 'metabox',
25
+ ID: parseInt($('#post_ID').val()),
26
+ _ajax_nonce: $('#yarpp_display-nonce').val(),
27
+ };
28
+ if (typeof refresh !== 'undefined' && refresh) {
29
+ data['refresh'] = true;
30
+ }
31
+ $.ajax({
32
+ type: 'POST',
33
+ url: ajaxurl,
34
+ data: data,
35
+ error: function () {
36
+ display.html('Error');
37
+ },
38
+ success: function (html) {
39
+ display.html(html);
40
+ },
41
+ dataType: 'html',
42
+ });
43
+ }
44
 
45
+ $('#yarpp_relatedposts .handlediv, #yarpp_relatedposts-hide').click(function () {
46
+ setTimeout(yarpp_metabox_initial_display, 0);
47
+ });
48
 
49
+ /*
50
+ * Metabox Actions
51
+ */
52
+ $(document).on('touchstart mouseenter', '#yarpp-list li', function () {
53
+ $(this).children('.yarpp-related-action').css('visibility', 'visible');
54
+ });
55
 
56
+ $(document).on('touchend mouseleave', '#yarpp-list li', function () {
57
+ $(this).children('.yarpp-related-action').css('visibility', 'hidden');
58
+ });
59
 
60
+ /*
61
+ * Metabox Refresh Button
62
+ */
63
+ $(document).on('click', '#yarpp-refresh', function (e) {
64
+ e.preventDefault();
65
 
66
+ var display = $('#yarpp-related-posts');
67
 
68
+ if ($(this).hasClass('disabled')) return false;
69
 
70
+ const refresh_button = $(this);
71
+ const spinner = refresh_button.siblings('.spinner');
72
 
73
+ refresh_button.addClass('yarpp-disabled');
74
+ spinner.css('visibility', 'visible');
75
 
76
+ $('#yarpp-list').css('opacity', 0.6);
77
+ yarpp_metabox_populate(true);
78
+ });
79
 
80
+ /*
81
+ * Initial Load
82
+ */
83
+ yarpp_metabox_initial_display();
84
  });
src/js/options_basic.js CHANGED
@@ -1,424 +1,441 @@
1
  jQuery(function ($) {
2
- // since 3.3: add screen option toggles
3
- postboxes.add_postbox_toggles(pagenow);
4
-
5
- function template() {
6
- var metabox = $(this).closest('#yarpp_display_web, #yarpp_display_rss');
7
- if (!metabox.length) return;
8
-
9
- value = metabox.find('.use_template').val();
10
-
11
- metabox.find('.yarpp_subbox').hide();
12
- metabox.find('.template_options_' + value).show();
13
-
14
- var no_results_area = metabox.find('.yarpp_no_results');
15
- // The "no_results" input is special. Its used by the non-custom templates.
16
- if (value === 'custom') {
17
- no_results_area.hide();
18
- } else {
19
- no_results_area.show();
20
- }
21
- excerpt.apply(metabox);
22
- }
23
- $('.use_template').each(template).change(template);
24
-
25
- function excerpt() {
26
- var metabox = $(this).closest('#yarpp_display_web, #yarpp_display_rss');
27
- metabox
28
- .find('.excerpted')
29
- .toggle(
30
- !!(
31
- metabox.find('.use_template').val() === 'builtin' &&
32
- metabox.find('.show_excerpt input').prop('checked')
33
- ),
34
- );
35
- }
36
- $('.show_excerpt, .use_template, #yarpp-rss_display').click(excerpt);
37
-
38
- var loaded_demo_web = false;
39
- function display() {
40
- if (!$('#yarpp_display_web .inside').is(':visible')) return;
41
-
42
- $('.yarpp_code_display').toggle($('#yarpp_display_code').is(':checked'));
43
- if ($('#yarpp_display_web .yarpp_code_display').is(':visible') && !loaded_demo_web) {
44
- loaded_demo_web = true;
45
- var demo_web = $('#display_demo_web');
46
- $.ajax({
47
- type: 'POST',
48
- url: ajaxurl,
49
- data: {
50
- action: 'yarpp_display_demo',
51
- domain: 'website',
52
- _ajax_nonce: $('#yarpp_display_demo-nonce').val(),
53
- },
54
- beforeSend: function () {
55
- demo_web.html(loading);
56
- },
57
- success: function (html) {
58
- demo_web.html('<pre>' + html + '</pre>');
59
- },
60
- dataType: 'html',
61
- });
62
- }
63
- }
64
- $('#yarpp_display_web .handlediv, #yarpp_display_web-hide').click(display);
65
- display();
66
-
67
- var loaded_demo_rss = false;
68
- function rss_display() {
69
- if (!$('#yarpp_display_rss .inside').is(':visible')) return;
70
- if ($('#yarpp-rss_display').is(':checked')) {
71
- $('.rss_displayed').show();
72
- $('.yarpp_code_display').toggle($('#yarpp_display_code').is(':checked'));
73
- if (
74
- $('#yarpp_display_rss .yarpp_code_display').is(':visible') &&
75
- !loaded_demo_rss
76
- ) {
77
- loaded_demo_rss = true;
78
- var demo_rss = $('#display_demo_rss');
79
- $.ajax({
80
- type: 'POST',
81
- url: ajaxurl,
82
- data: {
83
- action: 'yarpp_display_demo',
84
- domain: 'rss',
85
- _ajax_nonce: $('#yarpp_display_demo-nonce').val(),
86
- },
87
- beforeSend: function () {
88
- demo_rss.html(loading);
89
- },
90
- success: function (html) {
91
- demo_rss.html('<pre>' + html + '</pre>');
92
- },
93
- dataType: 'html',
94
- });
95
- }
96
- $('#yarpp_display_rss').each(template);
97
- } else {
98
- $('.rss_displayed').hide();
99
- }
100
- }
101
- $('#yarpp-rss_display, #yarpp_display_rss .handlediv, #yarpp_display_rss-hide').click(
102
- rss_display,
103
- );
104
- rss_display();
105
-
106
- function yarpp_rest_display() {
107
- if (!$('#yarpp_display_api .inside').is(':visible')) return;
108
- if ($('#yarpp-rest_api_display').is(':checked')) {
109
- $('.yarpp_rest_displayed').show();
110
- } else {
111
- $('.yarpp_rest_displayed').hide();
112
- }
113
- }
114
- $('#yarpp-rest_api_display').click(yarpp_rest_display);
115
- yarpp_rest_display();
116
-
117
- function yarpp_rest_cache_display() {
118
- if ($('#yarpp-rest_api_client_side_caching').is(':checked')) {
119
- $('.yarpp_rest_browser_cache_displayed').show();
120
- } else {
121
- $('.yarpp_rest_browser_cache_displayed').hide();
122
- }
123
- }
124
- $('#yarpp-rest_api_client_side_caching').click(yarpp_rest_cache_display);
125
- yarpp_rest_cache_display();
126
-
127
- var loaded_disallows = false;
128
- function load_disallows() {
129
- if (loaded_disallows || !$('#yarpp_pool .inside').is(':visible')) return;
130
- loaded_disallows = true;
131
-
132
- var finished_taxonomies = {},
133
- term_indices = {};
134
- function load_disallow(taxonomy) {
135
- if (taxonomy in finished_taxonomies) return;
136
- var display = $('#exclude_' + taxonomy);
137
- // only do one query at a time:
138
- if (display.find('.loading').length) return;
139
-
140
- if (taxonomy in term_indices) term_indices[taxonomy] = term_indices[taxonomy] + 100;
141
- else term_indices[taxonomy] = 0;
142
- $.ajax({
143
- type: 'POST',
144
- url: ajaxurl,
145
- data: {
146
- action: 'yarpp_display_exclude_terms',
147
- taxonomy: taxonomy,
148
- offset: term_indices[taxonomy],
149
- _ajax_nonce: $('#yarpp_display_exclude_terms-nonce').val(),
150
- },
151
- beforeSend: function () {
152
- display.append(loading);
153
- },
154
- success: function (html) {
155
- display.find('.loading').remove();
156
- if (':(' == html) {
157
- // no more :(
158
- finished_taxonomies[taxonomy] = true;
159
- display.append('-');
160
- return;
161
- }
162
- display.append(html);
163
- },
164
- dataType: 'html',
165
- });
166
- }
167
-
168
- $('.exclude_terms').each(function () {
169
- var id = jQuery(this).attr('id'),
170
- taxonomy;
171
- if (!id) return;
172
-
173
- taxonomy = id.replace('exclude_', '');
174
-
175
- load_disallow(taxonomy);
176
- $('#exclude_' + taxonomy)
177
- .parent('.yarpp_scroll_wrapper')
178
- .scroll(function () {
179
- var parent = $(this),
180
- content = parent.children('div');
181
- if (parent.scrollTop() + parent.height() > content.height() - 10)
182
- load_disallow(taxonomy);
183
- });
184
- });
185
- }
186
- $('#yarpp_pool .handlediv, #yarpp_pool-hide').click(load_disallows);
187
- load_disallows();
188
-
189
- function show_help(section) {
190
- $('#tab-link-' + section + ' a').click();
191
- $('#contextual-help-link').click();
192
- }
193
- $('#yarpp-optin-learnmore').click(function () {
194
- show_help('optin');
195
- });
196
- $('#yarpp-help-cpt').click(function () {
197
- show_help('dev');
198
- });
199
- if (location.hash == '#help-optin')
200
- setTimeout(function () {
201
- show_help('optin');
202
- });
203
-
204
- $('.yarpp_help[data-help]').hover(function () {
205
- var that = $(this),
206
- help = '<p>' + that.attr('data-help') + '</p>',
207
- options = {
208
- content: help,
209
- position: {
210
- edge: isRtl ? 'right' : 'left',
211
- align: 'center',
212
- of: that,
213
- },
214
- document: { body: that },
215
- };
216
-
217
- var pointer = that.pointer(options).pointer('open');
218
- that.closest('.yarpp_form_row, p').mouseleave(function () {
219
- pointer.pointer('close');
220
- });
221
- });
222
-
223
- $('.yarpp_template_button[data-help]').hover(function () {
224
- var that = $(this),
225
- help = '<p>' + that.attr('data-help') + '</p>',
226
- options = {
227
- content: help,
228
- position: {
229
- edge: 'bottom',
230
- // align: 'center',
231
- of: that,
232
- },
233
- document: { body: that },
234
- };
235
-
236
- var pointer = that.pointer(options).pointer('open');
237
- that.mouseleave(function () {
238
- pointer.pointer('close');
239
- });
240
-
241
- // Only setup the copy templates button once it exists.
242
- $('.yarpp_copy_templates_button').on('click', function () {
243
- const copy_templates_button = $(this);
244
- const spinner = copy_templates_button.siblings('.spinner');
245
-
246
- copy_templates_button.addClass('yarpp-disabled');
247
- spinner.addClass('is-active');
248
-
249
- window.location =
250
- window.location +
251
- (window.location.search.length ? '&' : '?') +
252
- 'action=copy_templates&_ajax_nonce=' +
253
- $('#yarpp_copy_templates-nonce').val();
254
- });
255
- });
256
-
257
- $('.yarpp_spin_on_click').on('click', function () {
258
- const button = $(this);
259
- const spinner = button.siblings('.spinner');
260
-
261
- button.addClass('yarpp-disabled');
262
- spinner.addClass('is-active');
263
- });
264
-
265
- $('.yarpp_template_button:not(.disabled)').click(function () {
266
- $(this).siblings('input').val($(this).attr('data-value')).change();
267
- $(this).siblings().removeClass('active');
268
- $(this).addClass('active');
269
- });
270
-
271
- function template_info() {
272
- var template = $(this).find('option:selected'),
273
- row = template.closest('.yarpp_form_row');
274
- if (!!template.attr('data-url')) {
275
- row
276
- .find('.template_author_wrap')
277
- .toggle(!!template.attr('data-author'))
278
- .find('span')
279
- .empty()
280
- .append('<a>' + template.attr('data-author') + '</a>')
281
- .attr('href', template.attr('data-url'));
282
- } else {
283
- row
284
- .find('.template_author_wrap')
285
- .toggle(!!template.attr('data-author'))
286
- .find('span')
287
- .text(template.attr('data-author'));
288
- }
289
- row
290
- .find('.template_description_wrap')
291
- .toggle(!!template.attr('data-description'))
292
- .find('span')
293
- .text(template.attr('data-description'));
294
- row
295
- .find('.template_file_wrap')
296
- .toggle(!!template.attr('data-basename'))
297
- .find('span')
298
- .text(template.attr('data-basename'));
299
- }
300
- $('#template_file, #rss_template_file').each(template_info).change(template_info);
301
-
302
- var loaded_optin_data = false;
303
- function _display_optin_data() {
304
- if (!$('#optin_data_frame').is(':visible') || loaded_optin_data) return;
305
- loaded_optin_data = true;
306
- var frame = $('#optin_data_frame');
307
- $.ajax({
308
- type: 'POST',
309
- url: ajaxurl,
310
- data: {
311
- action: 'yarpp_optin_data',
312
- _ajax_nonce: $('#yarpp_optin_data-nonce').val(),
313
- },
314
- beforeSend: function () {
315
- frame.html(loading);
316
- },
317
- success: function (html) {
318
- frame.html('<pre>' + html + '</pre>');
319
- },
320
- dataType: 'html',
321
- });
322
- }
323
- function display_optin_data() {
324
- setTimeout(_display_optin_data, 0);
325
- }
326
- $('#yarpp-optin-learnmore, a[aria-controls=tab-panel-optin]').bind(
327
- 'click focus',
328
- display_optin_data,
329
- );
330
- display_optin_data();
331
-
332
- function sync_no_results() {
333
- var value = $(this).find('input').attr('value');
334
- if ($(this).hasClass('sync_no_results'))
335
- $('.sync_no_results input').attr('value', value);
336
- if ($(this).hasClass('sync_rss_no_results'))
337
- $('.sync_rss_no_results input').attr('value', value);
338
- }
339
- $('.sync_no_results, .sync_rss_no_results').change(sync_no_results);
340
-
341
- $('#yarpp_display_code').click(function () {
342
- var args = {
343
- action: 'yarpp_set_display_code',
344
- _ajax_nonce: $('#yarpp_set_display_code-nonce').val(),
345
- };
346
- if ($(this).is(':checked')) args.checked = true;
347
- $.ajax({ type: 'POST', url: ajaxurl, data: args });
348
- display();
349
- rss_display();
350
- });
351
-
352
- function auto_display_archive() {
353
- var available = $('.yarpp_form_post_types').is(':has(input[type=checkbox]:checked)');
354
- $('#yarpp-auto_display_archive').attr('disabled', !available);
355
- if (!available) $('#yarpp-auto_display_archive').prop('checked', false);
356
- }
357
-
358
- $('.yarpp_form_post_types input[type=checkbox]').change(auto_display_archive);
359
- auto_display_archive();
360
-
361
- $('#yarpp_fulltext_expand').click(function (e) {
362
- e.preventDefault();
363
- var details = $('#yarpp_fulltext_details');
364
-
365
- details.slideToggle();
366
-
367
- if (details.hasClass('hidden')) {
368
- details.removeClass('hidden');
369
- $(this).text('Hide Details [-]');
370
- } else {
371
- details.addClass('hidden');
372
- $(this).text('Show Details [+]');
373
- }
374
- });
375
- $('.include_post_type input[type=checkbox]').change(function (e) {
376
- var get_attr = $(this).attr('data-post-type');
377
- if ($('#yarpp-same_post_type').is(':checked')) {
378
- yarpp_enable_disabel_checkbox($(this).is(':checked'), get_attr);
379
- } else {
380
- $('.yarpp_form_post_types #yarpp_post_type_' + get_attr).prop('disabled', false);
381
- }
382
- });
383
- $('#yarpp-same_post_type').change(function (e) {
384
- var get_checkboxes = '.include_post_type input[type=checkbox]';
385
- if ($(this).is(':checked')) {
386
- $(get_checkboxes).each(function () {
387
- var get_attr = $(this).attr('data-post-type');
388
- yarpp_enable_disabel_checkbox($(this).is(':checked'), get_attr);
389
- });
390
- } else {
391
- $('.yarpp_form_post_types input[type=checkbox]').prop('disabled', false);
392
- $('.yarpp_form_post_types input[type=checkbox]').siblings().hide();
393
- }
394
- });
395
- function yarpp_enable_disabel_checkbox(checked, get_attr) {
396
- if (checked) {
397
- $('.yarpp_form_post_types #yarpp_post_type_' + get_attr).prop('disabled', false);
398
- $('.yarpp_form_post_types #yarpp_post_type_' + get_attr)
399
- .siblings()
400
- .hide();
401
- } else {
402
- $('.yarpp_form_post_types #yarpp_post_type_' + get_attr).prop('disabled', true);
403
- $('.yarpp_form_post_types #yarpp_post_type_' + get_attr)
404
- .siblings()
405
- .show();
406
- }
407
- }
408
- var yarpp_model = $(
409
- '\
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  <div id="shareaholic-deactivate-dialog" class="shareaholic-deactivate-dialog" data-remodal-id="">\
411
  <div class="shareaholic-deactivate-header" style="background-image: url(' +
412
- yarpp_messages.logo +
413
- '); background-color: ' +
414
- yarpp_messages.bgcolor +
415
- ';"><div class="shareaholic-deactivate-text"><h2>' +
416
- yarpp_messages.model_title +
417
- '</h2></div></div>\
418
  <div class="shareaholic-deactivate-body">\
419
  <div class="shareaholic-deactivate-body-foreword">' +
420
- yarpp_messages.alert_message +
421
- '</div>\
422
  <div class="shareaholic-deactivate-dialog-footer">\
423
  <input type="submit" class="button confirm button-secondary" id="yarpp-clear-cache-submit" value="Delete"/>\
424
  <button data-remodal-action="cancel" class="button button-secondary">Cancel</button>\
@@ -426,59 +443,59 @@ jQuery(function ($) {
426
  </div>\
427
  </div>\
428
  ',
429
- )[0];
430
- $('#yarpp-clear-cache').click(function () {
431
- var inst = $(yarpp_model).remodal({
432
- hashTracking: false,
433
- closeOnOutsideClick: false,
434
- });
435
- inst.open();
436
- event.preventDefault();
437
- });
438
- $(document.body).on('click', '#yarpp-clear-cache-submit', function () {
439
- var inst = $(yarpp_model).remodal();
440
- /**
441
- * Closes the modal window
442
- */
443
- inst.close();
444
- var cache_button = '#yarpp-clear-cache';
445
- var display_notices = '#display_notices';
446
- var notice_class = 'notice notice-error is-dismissible';
447
- $(cache_button).prop('disabled', true);
448
- $.ajax({
449
- type: 'POST',
450
- url: ajaxurl,
451
- data: {
452
- action: 'yarpp_clear_cache',
453
- _ajax_nonce: $('#clear_cache-nonce').val(),
454
- },
455
- beforeSend: function () {
456
- $(cache_button).siblings('.spinner').addClass('is-active');
457
- },
458
- success: function (data) {
459
- $(cache_button).siblings('.spinner').removeClass('is-active');
460
- $(display_notices).show();
461
- if ('success' == data) {
462
- var message = yarpp_messages.success;
463
- notice_class = 'notice notice-success is-dismissible';
464
- $(cache_button).prop('disabled', false);
465
- } else if ('forbidden' == data) {
466
- var message = yarpp_messages.forbidden;
467
- } else if ('nonce_fail' == data) {
468
- var message = yarpp_messages.nonce_fail;
469
- } else {
470
- var message = yarpp_messages.error;
471
- }
472
- $(display_notices).addClass(notice_class);
473
- $(display_notices).html('<p>' + message + '</p>');
474
- },
475
- error: function (data) {
476
- $(display_notices).show();
477
- $(display_notices).addClass(notice_class);
478
- $(cache_button).siblings('.spinner').removeClass('is-active');
479
- $(display_notices).html('<p>' + yarpp_messages.error + '</p>');
480
- },
481
- });
482
- $(display_notices).delay(5000).fadeOut(1000);
483
- });
484
  });
1
  jQuery(function ($) {
2
+ // since 3.3: add screen option toggles
3
+ postboxes.add_postbox_toggles(pagenow);
4
+
5
+ function template() {
6
+ var metabox = $(this).closest('#yarpp_display_web, #yarpp_display_rss');
7
+ if (!metabox.length) return;
8
+
9
+ value = metabox.find('.use_template').val();
10
+
11
+ metabox.find('.yarpp_subbox').hide();
12
+ metabox.find('.template_options_' + value).show();
13
+
14
+ var no_results_area = metabox.find('.yarpp_no_results');
15
+ // The "no_results" input is special. Its used by the non-custom templates.
16
+ if (value === 'custom') {
17
+ no_results_area.hide();
18
+ } else {
19
+ no_results_area.show();
20
+ }
21
+ var generate_missing_thumbnails = metabox.find('.generate_missing_thumbnails');
22
+ if (value === 'builtin') {
23
+ generate_missing_thumbnails.hide();
24
+ } else {
25
+ generate_missing_thumbnails.show();
26
+ }
27
+ excerpt.apply(metabox);
28
+ }
29
+ $('.use_template').each(template).change(template);
30
+
31
+ function excerpt() {
32
+ var metabox = $(this).closest('#yarpp_display_web, #yarpp_display_rss');
33
+ metabox
34
+ .find('.excerpted')
35
+ .toggle(
36
+ !!(
37
+ metabox.find('.use_template').val() === 'builtin' &&
38
+ metabox.find('.show_excerpt input').prop('checked')
39
+ ),
40
+ );
41
+ }
42
+ $('.show_excerpt, .use_template, #yarpp-rss_display').click(excerpt);
43
+
44
+ var loaded_demo_web = false;
45
+ function display() {
46
+ if (!$('#yarpp_display_web .inside').is(':visible')) return;
47
+
48
+ $('.yarpp_code_display').toggle($('#yarpp_display_code').is(':checked'));
49
+ if (
50
+ $('#yarpp_display_web .yarpp_code_display').is(':visible') &&
51
+ !loaded_demo_web
52
+ ) {
53
+ loaded_demo_web = true;
54
+ var demo_web = $('#display_demo_web');
55
+ $.ajax({
56
+ type: 'POST',
57
+ url: ajaxurl,
58
+ data: {
59
+ action: 'yarpp_display_demo',
60
+ domain: 'website',
61
+ _ajax_nonce: $('#yarpp_display_demo-nonce').val(),
62
+ },
63
+ beforeSend: function () {
64
+ demo_web.html(loading);
65
+ },
66
+ success: function (html) {
67
+ demo_web.html('<pre>' + html + '</pre>');
68
+ },
69
+ dataType: 'html',
70
+ });
71
+ }
72
+ }
73
+ $('#yarpp_display_web .handlediv, #yarpp_display_web-hide').click(display);
74
+ display();
75
+
76
+ var loaded_demo_rss = false;
77
+ function rss_display() {
78
+ if (!$('#yarpp_display_rss .inside').is(':visible')) return;
79
+ if ($('#yarpp-rss_display').is(':checked')) {
80
+ $('.rss_displayed').show();
81
+ $('.yarpp_code_display').toggle($('#yarpp_display_code').is(':checked'));
82
+ if (
83
+ $('#yarpp_display_rss .yarpp_code_display').is(':visible') &&
84
+ !loaded_demo_rss
85
+ ) {
86
+ loaded_demo_rss = true;
87
+ var demo_rss = $('#display_demo_rss');
88
+ $.ajax({
89
+ type: 'POST',
90
+ url: ajaxurl,
91
+ data: {
92
+ action: 'yarpp_display_demo',
93
+ domain: 'rss',
94
+ _ajax_nonce: $('#yarpp_display_demo-nonce').val(),
95
+ },
96
+ beforeSend: function () {
97
+ demo_rss.html(loading);
98
+ },
99
+ success: function (html) {
100
+ demo_rss.html('<pre>' + html + '</pre>');
101
+ },
102
+ dataType: 'html',
103
+ });
104
+ }
105
+ $('#yarpp_display_rss').each(template);
106
+ } else {
107
+ $('.rss_displayed').hide();
108
+ }
109
+ }
110
+ $('#yarpp-rss_display, #yarpp_display_rss .handlediv, #yarpp_display_rss-hide').click(
111
+ rss_display,
112
+ );
113
+ rss_display();
114
+
115
+ function yarpp_rest_display() {
116
+ if (!$('#yarpp_display_api .inside').is(':visible')) return;
117
+ if ($('#yarpp-rest_api_display').is(':checked')) {
118
+ $('.yarpp_rest_displayed').show();
119
+ } else {
120
+ $('.yarpp_rest_displayed').hide();
121
+ }
122
+ }
123
+ $('#yarpp-rest_api_display').click(yarpp_rest_display);
124
+ yarpp_rest_display();
125
+
126
+ function yarpp_rest_cache_display() {
127
+ if ($('#yarpp-rest_api_client_side_caching').is(':checked')) {
128
+ $('.yarpp_rest_browser_cache_displayed').show();
129
+ } else {
130
+ $('.yarpp_rest_browser_cache_displayed').hide();
131
+ }
132
+ }
133
+ $('#yarpp-rest_api_client_side_caching').click(yarpp_rest_cache_display);
134
+ yarpp_rest_cache_display();
135
+
136
+ var loaded_disallows = false;
137
+ function load_disallows() {
138
+ if (loaded_disallows || !$('#yarpp_pool .inside').is(':visible')) return;
139
+ loaded_disallows = true;
140
+
141
+ var finished_taxonomies = {},
142
+ term_indices = {};
143
+ function load_disallow(taxonomy) {
144
+ if (taxonomy in finished_taxonomies) return;
145
+ var display = $('#exclude_' + taxonomy);
146
+ // only do one query at a time:
147
+ if (display.find('.loading').length) return;
148
+
149
+ if (taxonomy in term_indices)
150
+ term_indices[taxonomy] = term_indices[taxonomy] + 100;
151
+ else term_indices[taxonomy] = 0;
152
+ $.ajax({
153
+ type: 'POST',
154
+ url: ajaxurl,
155
+ data: {
156
+ action: 'yarpp_display_exclude_terms',
157
+ taxonomy: taxonomy,
158
+ offset: term_indices[taxonomy],
159
+ _ajax_nonce: $('#yarpp_display_exclude_terms-nonce').val(),
160
+ },
161
+ beforeSend: function () {
162
+ display.append(loading);
163
+ },
164
+ success: function (html) {
165
+ display.find('.loading').remove();
166
+ if (':(' == html) {
167
+ // no more :(
168
+ finished_taxonomies[taxonomy] = true;
169
+ display.append('-');
170
+ return;
171
+ }
172
+ display.append(html);
173
+ },
174
+ dataType: 'html',
175
+ });
176
+ }
177
+
178
+ $('.exclude_terms').each(function () {
179
+ var id = jQuery(this).attr('id'),
180
+ taxonomy;
181
+ if (!id) return;
182
+
183
+ taxonomy = id.replace('exclude_', '');
184
+
185
+ load_disallow(taxonomy);
186
+ $('#exclude_' + taxonomy)
187
+ .parent('.yarpp_scroll_wrapper')
188
+ .scroll(function () {
189
+ var parent = $(this),
190
+ content = parent.children('div');
191
+ if (parent.scrollTop() + parent.height() > content.height() - 10)
192
+ load_disallow(taxonomy);
193
+ });
194
+ });
195
+ }
196
+ $('#yarpp_pool .handlediv, #yarpp_pool-hide').click(load_disallows);
197
+ load_disallows();
198
+
199
+ function show_help(section) {
200
+ $('#tab-link-' + section + ' a').click();
201
+ $('#contextual-help-link').click();
202
+ }
203
+ $('#yarpp-optin-learnmore').click(function () {
204
+ show_help('optin');
205
+ });
206
+ $('#yarpp-help-cpt').click(function () {
207
+ show_help('dev');
208
+ });
209
+ if (location.hash == '#help-optin')
210
+ setTimeout(function () {
211
+ show_help('optin');
212
+ });
213
+
214
+ $('.yarpp_help[data-help]').hover(function () {
215
+ var that = $(this),
216
+ help = '<p>' + that.attr('data-help') + '</p>',
217
+ options = {
218
+ content: help,
219
+ position: {
220
+ edge: isRtl ? 'right' : 'left',
221
+ align: 'center',
222
+ of: that,
223
+ },
224
+ document: { body: that },
225
+ };
226
+
227
+ var pointer = that.pointer(options).pointer('open');
228
+ that.closest('.yarpp_form_row, p').mouseleave(function () {
229
+ pointer.pointer('close');
230
+ });
231
+ });
232
+
233
+ $('.yarpp_template_button[data-help]').hover(function () {
234
+ var that = $(this),
235
+ help = '<p>' + that.attr('data-help') + '</p>',
236
+ options = {
237
+ content: help,
238
+ position: {
239
+ edge: 'bottom',
240
+ // align: 'center',
241
+ of: that,
242
+ },
243
+ document: { body: that },
244
+ };
245
+
246
+ var pointer = that.pointer(options).pointer('open');
247
+ that.mouseleave(function () {
248
+ pointer.pointer('close');
249
+ });
250
+
251
+ // Only setup the copy templates button once it exists.
252
+ $('.yarpp_copy_templates_button').on('click', function () {
253
+ const copy_templates_button = $(this);
254
+ const spinner = copy_templates_button.siblings('.spinner');
255
+
256
+ copy_templates_button.addClass('yarpp-disabled');
257
+ spinner.addClass('is-active');
258
+
259
+ window.location =
260
+ window.location +
261
+ (window.location.search.length ? '&' : '?') +
262
+ 'action=copy_templates&_ajax_nonce=' +
263
+ $('#yarpp_copy_templates-nonce').val();
264
+ });
265
+ });
266
+
267
+ $('.yarpp_spin_on_click').on('click', function () {
268
+ const button = $(this);
269
+ const spinner = button.siblings('.spinner');
270
+
271
+ button.addClass('yarpp-disabled');
272
+ spinner.addClass('is-active');
273
+ });
274
+
275
+ $('.yarpp_template_button:not(.disabled)').click(function () {
276
+ $(this).siblings('input').val($(this).attr('data-value')).change();
277
+ $(this).siblings().removeClass('active');
278
+ $(this).addClass('active');
279
+ });
280
+
281
+ function template_info() {
282
+ var template = $(this).find('option:selected'),
283
+ row = template.closest('.yarpp_form_row');
284
+ if (!!template.attr('data-url')) {
285
+ row.find('.template_author_wrap')
286
+ .toggle(!!template.attr('data-author'))
287
+ .find('span')
288
+ .empty()
289
+ .append('<a>' + template.attr('data-author') + '</a>')
290
+ .attr('href', template.attr('data-url'));
291
+ } else {
292
+ row.find('.template_author_wrap')
293
+ .toggle(!!template.attr('data-author'))
294
+ .find('span')
295
+ .text(template.attr('data-author'));
296
+ }
297
+ row.find('.template_description_wrap')
298
+ .toggle(!!template.attr('data-description'))
299
+ .find('span')
300
+ .text(template.attr('data-description'));
301
+ row.find('.template_file_wrap')
302
+ .toggle(!!template.attr('data-basename'))
303
+ .find('span')
304
+ .text(template.attr('data-basename'));
305
+ }
306
+ $('#template_file, #rss_template_file').each(template_info).change(template_info);
307
+
308
+ var loaded_optin_data = false;
309
+ function _display_optin_data() {
310
+ if (!$('#optin_data_frame').is(':visible') || loaded_optin_data) return;
311
+ loaded_optin_data = true;
312
+ var frame = $('#optin_data_frame');
313
+ $.ajax({
314
+ type: 'POST',
315
+ url: ajaxurl,
316
+ data: {
317
+ action: 'yarpp_optin_data',
318
+ _ajax_nonce: $('#yarpp_optin_data-nonce').val(),
319
+ },
320
+ beforeSend: function () {
321
+ frame.html(loading);
322
+ },
323
+ success: function (html) {
324
+ frame.html('<pre>' + html + '</pre>');
325
+ },
326
+ dataType: 'html',
327
+ });
328
+ }
329
+ function display_optin_data() {
330
+ setTimeout(_display_optin_data, 0);
331
+ }
332
+ $('#yarpp-optin-learnmore, a[aria-controls=tab-panel-optin]').bind(
333
+ 'click focus',
334
+ display_optin_data,
335
+ );
336
+ display_optin_data();
337
+
338
+ function sync_no_results() {
339
+ var value = $(this).find('input').attr('value');
340
+ if ($(this).hasClass('sync_no_results'))
341
+ $('.sync_no_results input').attr('value', value);
342
+ if ($(this).hasClass('sync_rss_no_results'))
343
+ $('.sync_rss_no_results input').attr('value', value);
344
+ }
345
+ $('.sync_no_results, .sync_rss_no_results').change(sync_no_results);
346
+
347
+ $('#yarpp_display_code').click(function () {
348
+ var args = {
349
+ action: 'yarpp_set_display_code',
350
+ _ajax_nonce: $('#yarpp_set_display_code-nonce').val(),
351
+ };
352
+ if ($(this).is(':checked')) args.checked = true;
353
+ $.ajax({ type: 'POST', url: ajaxurl, data: args });
354
+ display();
355
+ rss_display();
356
+ });
357
+
358
+ function auto_display_archive() {
359
+ var available = $('.yarpp_form_post_types').is(
360
+ ':has(input[type=checkbox]:checked)',
361
+ );
362
+ $('#yarpp-auto_display_archive').attr('disabled', !available);
363
+ if (!available) $('#yarpp-auto_display_archive').prop('checked', false);
364
+ }
365
+
366
+ $('.yarpp_form_post_types input[type=checkbox]').change(auto_display_archive);
367
+ auto_display_archive();
368
+
369
+ $('#yarpp_fulltext_expand').click(function (e) {
370
+ e.preventDefault();
371
+ var details = $('#yarpp_fulltext_details');
372
+
373
+ details.slideToggle();
374
+
375
+ if (details.hasClass('hidden')) {
376
+ details.removeClass('hidden');
377
+ $(this).text('Hide Details [-]');
378
+ } else {
379
+ details.addClass('hidden');
380
+ $(this).text('Show Details [+]');
381
+ }
382
+ });
383
+ $('.include_post_type input[type=checkbox]').change(function (e) {
384
+ var get_attr = $(this).attr('data-post-type');
385
+ if ($('#yarpp-same_post_type').is(':checked')) {
386
+ yarpp_enable_disabel_checkbox($(this).is(':checked'), get_attr);
387
+ } else {
388
+ $('.yarpp_form_post_types #yarpp_post_type_' + get_attr).prop(
389
+ 'disabled',
390
+ false,
391
+ );
392
+ }
393
+ });
394
+ $('#yarpp-same_post_type').change(function (e) {
395
+ var get_checkboxes = '.include_post_type input[type=checkbox]';
396
+ if ($(this).is(':checked')) {
397
+ $(get_checkboxes).each(function () {
398
+ var get_attr = $(this).attr('data-post-type');
399
+ yarpp_enable_disabel_checkbox($(this).is(':checked'), get_attr);
400
+ });
401
+ } else {
402
+ $('.yarpp_form_post_types input[type=checkbox]').prop('disabled', false);
403
+ $('.yarpp_form_post_types input[type=checkbox]').siblings().hide();
404
+ }
405
+ });
406
+ function yarpp_enable_disabel_checkbox(checked, get_attr) {
407
+ if (checked) {
408
+ $('.yarpp_form_post_types #yarpp_post_type_' + get_attr).prop(
409
+ 'disabled',
410
+ false,
411
+ );
412
+ $('.yarpp_form_post_types #yarpp_post_type_' + get_attr)
413
+ .siblings()
414
+ .hide();
415
+ } else {
416
+ $('.yarpp_form_post_types #yarpp_post_type_' + get_attr).prop(
417
+ 'disabled',
418
+ true,
419
+ );
420
+ $('.yarpp_form_post_types #yarpp_post_type_' + get_attr)
421
+ .siblings()
422
+ .show();
423
+ }
424
+ }
425
+ var yarpp_model = $(
426
+ '\
427
  <div id="shareaholic-deactivate-dialog" class="shareaholic-deactivate-dialog" data-remodal-id="">\
428
  <div class="shareaholic-deactivate-header" style="background-image: url(' +
429
+ yarpp_messages.logo +
430
+ '); background-color: ' +
431
+ yarpp_messages.bgcolor +
432
+ ';"><div class="shareaholic-deactivate-text"><h2>' +
433
+ yarpp_messages.model_title +
434
+ '</h2></div></div>\
435
  <div class="shareaholic-deactivate-body">\
436
  <div class="shareaholic-deactivate-body-foreword">' +
437
+ yarpp_messages.alert_message +
438
+ '</div>\
439
  <div class="shareaholic-deactivate-dialog-footer">\
440
  <input type="submit" class="button confirm button-secondary" id="yarpp-clear-cache-submit" value="Delete"/>\
441
  <button data-remodal-action="cancel" class="button button-secondary">Cancel</button>\
443
  </div>\
444
  </div>\
445
  ',
446
+ )[0];
447
+ $('#yarpp-clear-cache').click(function () {
448
+ var inst = $(yarpp_model).remodal({
449
+ hashTracking: false,
450
+ closeOnOutsideClick: false,
451
+ });
452
+ inst.open();
453
+ event.preventDefault();
454
+ });
455
+ $(document.body).on('click', '#yarpp-clear-cache-submit', function () {
456
+ var inst = $(yarpp_model).remodal();
457
+ /**
458
+ * Closes the modal window
459
+ */
460
+ inst.close();
461
+ var cache_button = '#yarpp-clear-cache';
462
+ var display_notices = '#display_notices';
463
+ var notice_class = 'notice notice-error is-dismissible';
464
+ $(cache_button).prop('disabled', true);
465
+ $.ajax({
466
+ type: 'POST',
467
+ url: ajaxurl,
468
+ data: {
469
+ action: 'yarpp_clear_cache',
470
+ _ajax_nonce: $('#clear_cache-nonce').val(),
471
+ },
472
+ beforeSend: function () {
473
+ $(cache_button).siblings('.spinner').addClass('is-active');
474
+ },
475
+ success: function (data) {
476
+ $(cache_button).siblings('.spinner').removeClass('is-active');
477
+ $(display_notices).show();
478
+ if ('success' == data) {
479
+ var message = yarpp_messages.success;
480
+ notice_class = 'notice notice-success is-dismissible';
481
+ $(cache_button).prop('disabled', false);
482
+ } else if ('forbidden' == data) {
483
+ var message = yarpp_messages.forbidden;
484
+ } else if ('nonce_fail' == data) {
485
+ var message = yarpp_messages.nonce_fail;
486
+ } else {
487
+ var message = yarpp_messages.error;
488
+ }
489
+ $(display_notices).addClass(notice_class);
490
+ $(display_notices).html('<p>' + message + '</p>');
491
+ },
492
+ error: function (data) {
493
+ $(display_notices).show();
494
+ $(display_notices).addClass(notice_class);
495
+ $(cache_button).siblings('.spinner').removeClass('is-active');
496
+ $(display_notices).html('<p>' + yarpp_messages.error + '</p>');
497
+ },
498
+ });
499
+ $(display_notices).delay(5000).fadeOut(1000);
500
+ });
501
  });
src/js/options_switch.js CHANGED
@@ -1,79 +1,79 @@
1
  function yarppMakeTheSwitch($, data, url) {
2
- $.get(url, data, function (resp) {
3
- if (resp === 'ok') {
4
- window.location.href = './options-general.php?page=yarpp';
5
- }
6
- });
7
  }
8
 
9
  jQuery(document).ready(function ($) {
10
- $('.yarpp_switch_button').on('click', function (e) {
11
- e.preventDefault();
12
- var url = ajaxurl,
13
- data = {
14
- action: 'yarpp_switch',
15
- go: $(this).data('go'),
16
- _ajax_nonce: $('#yarpp_switch-nonce').val(),
17
- };
18
 
19
- if (data.go === 'basic') {
20
- $('#wpwrap').after(
21
- '<div id="yarpp_pro_disable_overlay">' +
22
- '</div>' +
23
- '<div id="yarpp_pro_disable_confirm">' +
24
- '<p>' +
25
- 'Are you sure you would like to deactivate YARPP Pro? ' +
26
- 'Doing so will remove all <strong>YARPP Pro</strong> ' +
27
- 'content from your site, including sidebar widgets.' +
28
- '</p>' +
29
- '<br/>' +
30
- '<a id="yarpp_proceed_deactivation" class="button">Deactivate YARPP Pro</a>' +
31
- '&nbsp;&nbsp;&nbsp;&nbsp;' +
32
- '<a id="yarpp_cancel_deactivation" class="button-primary">Cancel Deactivation</a>' +
33
- '</div>',
34
- );
35
- $('#yarpp_proceed_deactivation').on('click', function () {
36
- yarppMakeTheSwitch($, data, url);
37
- });
38
 
39
- $('#yarpp_cancel_deactivation').on('click', function () {
40
- window.location.reload();
41
- });
42
- } else {
43
- yarppMakeTheSwitch($, data, url);
44
- }
45
- });
46
 
47
- $('#yarpp-display-mode-save').on('click', function (e) {
48
- e.preventDefault();
49
- var url = $(this).attr('href'),
50
- data = {
51
- ypsdt: true,
52
- types: [],
53
- };
54
 
55
- $(this).after($('<span class="spinner"></span>'));
56
 
57
- var i = 0;
58
- $('input', '#yarpp-display-mode').each(function (idx, val) {
59
- if (val.checked) {
60
- data.types[i] = val.value;
61
- i++;
62
- }
63
- });
64
 
65
- $.get(url, data, function (resp) {
66
- setTimeout(function () {
67
- if (resp === 'ok') {
68
- $('.spinner', '#yarpp-display-mode').remove();
69
- } else {
70
- $('#yarpp-display-mode').append(
71
- $(
72
- '<span style="vertical-align: middle" class="error-message">Something went wrong saving your settings. Please refresh the page and try again.</span>',
73
- ),
74
- );
75
- }
76
- }, 1000);
77
- });
78
- });
79
  });
1
  function yarppMakeTheSwitch($, data, url) {
2
+ $.get(url, data, function (resp) {
3
+ if (resp === 'ok') {
4
+ window.location.href = './options-general.php?page=yarpp';
5
+ }
6
+ });
7
  }
8
 
9
  jQuery(document).ready(function ($) {
10
+ $('.yarpp_switch_button').on('click', function (e) {
11
+ e.preventDefault();
12
+ var url = ajaxurl,
13
+ data = {
14
+ action: 'yarpp_switch',
15
+ go: $(this).data('go'),
16
+ _ajax_nonce: $('#yarpp_switch-nonce').val(),
17
+ };
18
 
19
+ if (data.go === 'basic') {
20
+ $('#wpwrap').after(
21
+ '<div id="yarpp_pro_disable_overlay">' +
22
+ '</div>' +
23
+ '<div id="yarpp_pro_disable_confirm">' +
24
+ '<p>' +
25
+ 'Are you sure you would like to deactivate YARPP Pro? ' +
26
+ 'Doing so will remove all <strong>YARPP Pro</strong> ' +
27
+ 'content from your site, including sidebar widgets.' +
28
+ '</p>' +
29
+ '<br/>' +
30
+ '<a id="yarpp_proceed_deactivation" class="button">Deactivate YARPP Pro</a>' +
31
+ '&nbsp;&nbsp;&nbsp;&nbsp;' +
32
+ '<a id="yarpp_cancel_deactivation" class="button-primary">Cancel Deactivation</a>' +
33
+ '</div>',
34
+ );
35
+ $('#yarpp_proceed_deactivation').on('click', function () {
36
+ yarppMakeTheSwitch($, data, url);
37
+ });
38
 
39
+ $('#yarpp_cancel_deactivation').on('click', function () {
40
+ window.location.reload();
41
+ });
42
+ } else {
43
+ yarppMakeTheSwitch($, data, url);
44
+ }
45
+ });
46
 
47
+ $('#yarpp-display-mode-save').on('click', function (e) {
48
+ e.preventDefault();
49
+ var url = $(this).attr('href'),
50
+ data = {
51
+ ypsdt: true,
52
+ types: [],
53
+ };
54
 
55
+ $(this).after($('<span class="spinner"></span>'));
56
 
57
+ var i = 0;
58
+ $('input', '#yarpp-display-mode').each(function (idx, val) {
59
+ if (val.checked) {
60
+ data.types[i] = val.value;
61
+ i++;
62
+ }
63
+ });
64
 
65
+ $.get(url, data, function (resp) {
66
+ setTimeout(function () {
67
+ if (resp === 'ok') {
68
+ $('.spinner', '#yarpp-display-mode').remove();
69
+ } else {
70
+ $('#yarpp-display-mode').append(
71
+ $(
72
+ '<span style="vertical-align: middle" class="error-message">Something went wrong saving your settings. Please refresh the page and try again.</span>',
73
+ ),
74
+ );
75
+ }
76
+ }, 1000);
77
+ });
78
+ });
79
  });
uninstall.php CHANGED
@@ -8,8 +8,8 @@
8
  */
9
 
10
  /* Exit if plugin delete hasn't be called */
11
- if (!defined('WP_UNINSTALL_PLUGIN')) {
12
- exit();
13
  }
14
 
15
  global $wpdb;
@@ -26,29 +26,29 @@ $optNames = array(
26
  'yarpp_activated',
27
  'widget_yarpp_widget',
28
  'yarpp_upgraded',
29
- 'yarpp_activate_timestamp'
30
  );
31
 
32
  /* Select right procedure for single or multi site */
33
- if (is_multisite()) {
34
 
35
  /* Get sites ids */
36
- $blog_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
37
 
38
  /* Get main site id */
39
  $original_blog_id = get_current_blog_id();
40
 
41
  /* loop through all sites */
42
- foreach ($blog_ids as $blog_id) {
43
- switch_to_blog($blog_id);
44
- clean($optNames, $wpdb);
45
  }/*end foreach*/
46
 
47
- switch_to_blog($original_blog_id);
48
 
49
  } else {
50
 
51
- clean($optNames, $wpdb);
52
 
53
  }/*end if*/
54
 
@@ -56,22 +56,23 @@ if (is_multisite()) {
56
  /**
57
  * Loop through option array and delete the option and clear and drop cache tables.
58
  *
59
- * @param array $opts Array of yarpp's options
60
  * @param object $wpdb WordPress db global
61
  */
62
- function clean( array $opts, $wpdb) {
63
 
64
- foreach ($opts as $opt) {
65
- delete_option($opt);
66
  }
67
-
68
  /* Truncate, clear and drop yarpp cache */
69
- $wpdb->query('DELETE FROM `' . $wpdb->prefix . 'postmeta` WHERE meta_key LIKE "%yarpp%"');
70
- $wpdb->query('TRUNCATE TABLE `' . $wpdb->prefix . 'yarpp_related_cache`');
71
  wp_cache_flush();
72
- $wpdb->query('DROP TABLE `' . $wpdb->prefix . 'yarpp_related_cache`');
73
 
74
  /* Delete users yarpp related data */
75
- $wpdb->query('DELETE FROM `' . $wpdb->prefix . 'usermeta` WHERE meta_key LIKE "%yarpp%"');
 
 
76
 
77
- }/*end clean */
8
  */
9
 
10
  /* Exit if plugin delete hasn't be called */
11
+ if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
12
+ exit();
13
  }
14
 
15
  global $wpdb;
26
  'yarpp_activated',
27
  'widget_yarpp_widget',
28
  'yarpp_upgraded',
29
+ 'yarpp_activate_timestamp',
30
  );
31
 
32
  /* Select right procedure for single or multi site */
33
+ if ( is_multisite() ) {
34
 
35
  /* Get sites ids */
36
+ $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
37
 
38
  /* Get main site id */
39
  $original_blog_id = get_current_blog_id();
40
 
41
  /* loop through all sites */
42
+ foreach ( $blog_ids as $blog_id ) {
43
+ switch_to_blog( $blog_id );
44
+ clean( $optNames, $wpdb );
45
  }/*end foreach*/
46
 
47
+ switch_to_blog( $original_blog_id );
48
 
49
  } else {
50
 
51
+ clean( $optNames, $wpdb );
52
 
53
  }/*end if*/
54
 
56
  /**
57
  * Loop through option array and delete the option and clear and drop cache tables.
58
  *
59
+ * @param array $opts Array of yarpp's options
60
  * @param object $wpdb WordPress db global
61
  */
62
+ function clean( array $opts, $wpdb ) {
63
 
64
+ foreach ( $opts as $opt ) {
65
+ delete_option( $opt );
66
  }
67
+
68
  /* Truncate, clear and drop yarpp cache */
69
+ $wpdb->query( 'DELETE FROM `' . $wpdb->prefix . 'postmeta` WHERE meta_key LIKE "%yarpp%"' );
70
+ $wpdb->query( 'TRUNCATE TABLE `' . $wpdb->prefix . 'yarpp_related_cache`' );
71
  wp_cache_flush();
72
+ $wpdb->query( 'DROP TABLE `' . $wpdb->prefix . 'yarpp_related_cache`' );
73
 
74
  /* Delete users yarpp related data */
75
+ $wpdb->query( 'DELETE FROM `' . $wpdb->prefix . 'usermeta` WHERE meta_key LIKE "%yarpp%"' );
76
+
77
+ }//end clean()
78
 
 
yarpp-templates/yarpp-template-example.php CHANGED
@@ -1,4 +1,4 @@
1
- <?php
2
  /*
3
  YARPP Template: Starter Template
4
  Description: A simple starter example template that you can edit.
@@ -28,9 +28,9 @@ Notes:
28
  <h3>Related Posts</h3>
29
  <?php if ( have_posts() ) : ?>
30
  <ul>
31
- <?php
32
  while ( have_posts() ) :
33
- the_post();
34
  ?>
35
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>" ><?php the_title(); ?></a><!-- (<?php the_score(); ?>)--></li>
36
  <?php endwhile; ?>
@@ -38,4 +38,3 @@ Notes:
38
  <?php else : ?>
39
  <p>No related posts.</p>
40
  <?php endif; ?>
41
-
1
+ <?php
2
  /*
3
  YARPP Template: Starter Template
4
  Description: A simple starter example template that you can edit.
28
  <h3>Related Posts</h3>
29
  <?php if ( have_posts() ) : ?>
30
  <ul>
31
+ <?php
32
  while ( have_posts() ) :
33
+ the_post();
34
  ?>
35
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>" ><?php the_title(); ?></a><!-- (<?php the_score(); ?>)--></li>
36
  <?php endwhile; ?>
38
  <?php else : ?>
39
  <p>No related posts.</p>
40
  <?php endif; ?>
 
yarpp-templates/yarpp-template-list.php CHANGED
@@ -26,7 +26,7 @@ Notes:
26
  ?>
27
 
28
  <h3>Related Posts</h3>
29
- <?php
30
  if ( have_posts() ) :
31
  $postsArray = array();
32
  while ( have_posts() ) :
26
  ?>
27
 
28
  <h3>Related Posts</h3>
29
+ <?php
30
  if ( have_posts() ) :
31
  $postsArray = array();
32
  while ( have_posts() ) :
yarpp-templates/yarpp-template-multilingual.php CHANGED
@@ -35,9 +35,9 @@ if ( function_exists( 'icl_register_string' ) ) {
35
  <h3><?php echo ( function_exists( 'icl_t' ) ? icl_t( 'Yet Another Related Posts Plugin', 'related posts header', 'Related Posts' ) : 'Related Posts' ); ?></h3>
36
  <?php if ( have_posts() ) : ?>
37
  <ol>
38
- <?php
39
  while ( have_posts() ) :
40
- the_post();
41
  ?>
42
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
43
  <?php endwhile; ?>
35
  <h3><?php echo ( function_exists( 'icl_t' ) ? icl_t( 'Yet Another Related Posts Plugin', 'related posts header', 'Related Posts' ) : 'Related Posts' ); ?></h3>
36
  <?php if ( have_posts() ) : ?>
37
  <ol>
38
+ <?php
39
  while ( have_posts() ) :
40
+ the_post();
41
  ?>
42
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
43
  <?php endwhile; ?>
yarpp-templates/yarpp-template-random.php CHANGED
@@ -28,15 +28,15 @@ Notes:
28
  <h3>Related Posts</h3>
29
  <?php if ( have_posts() ) : ?>
30
  <ol>
31
- <?php
32
  while ( have_posts() ) :
33
- the_post();
34
  ?>
35
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><!-- (<?php the_score(); ?>)--></li>
36
  <?php endwhile; ?>
37
  </ol>
38
 
39
- <?php
40
  else :
41
  query_posts( 'orderby=rand&order=asc&limit=1' );
42
  the_post();
28
  <h3>Related Posts</h3>
29
  <?php if ( have_posts() ) : ?>
30
  <ol>
31
+ <?php
32
  while ( have_posts() ) :
33
+ the_post();
34
  ?>
35
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><!-- (<?php the_score(); ?>)--></li>
36
  <?php endwhile; ?>
37
  </ol>
38
 
39
+ <?php
40
  else :
41
  query_posts( 'orderby=rand&order=asc&limit=1' );
42
  the_post();
yarpp-templates/yarpp-template-simple.php CHANGED
@@ -1,4 +1,4 @@
1
- <?php
2
  /*
3
  YARPP Template: Simple List
4
  Description: This template returns posts in an unordered list.
@@ -28,9 +28,9 @@ Notes:
28
  <h3>Related Posts</h3>
29
  <?php if ( have_posts() ) : ?>
30
  <ul>
31
- <?php
32
  while ( have_posts() ) :
33
- the_post();
34
  ?>
35
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>" ><?php the_title(); ?></a><!-- (<?php the_score(); ?>)--></li>
36
  <?php endwhile; ?>
1
+ <?php
2
  /*
3
  YARPP Template: Simple List
4
  Description: This template returns posts in an unordered list.
28
  <h3>Related Posts</h3>
29
  <?php if ( have_posts() ) : ?>
30
  <ul>
31
+ <?php
32
  while ( have_posts() ) :
33
+ the_post();
34
  ?>
35
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>" ><?php the_title(); ?></a><!-- (<?php the_score(); ?>)--></li>
36
  <?php endwhile; ?>
yarpp-templates/yarpp-template-thumbnail.php CHANGED
@@ -38,9 +38,9 @@ if ( isset( $_wp_additional_image_sizes['yarpp-thumbnail'] ) ) {
38
  <h3>Related Photos</h3>
39
  <?php if ( have_posts() ) : ?>
40
  <ul>
41
- <?php
42
  while ( have_posts() ) :
43
- the_post();
44
  ?>
45
  <?php if ( has_post_thumbnail() ) : ?>
46
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( $dimensions['size'], array( 'data-pin-nopin' => 'true' ) ); ?></a></li>
38
  <h3>Related Photos</h3>
39
  <?php if ( have_posts() ) : ?>
40
  <ul>
41
+ <?php
42
  while ( have_posts() ) :
43
+ the_post();
44
  ?>
45
  <?php if ( has_post_thumbnail() ) : ?>
46
  <li><a href="<?php the_permalink(); ?>" rel="bookmark norewrite" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( $dimensions['size'], array( 'data-pin-nopin' => 'true' ) ); ?></a></li>
yarpp.php CHANGED
@@ -2,7 +2,7 @@
2
  /*
3
  Plugin Name: Yet Another Related Posts Plugin (YARPP)
4
  Description: Adds related posts to your site and in RSS feeds, based on a powerful, customizable algorithm.
5
- Version: 5.23.0
6
  Author: YARPP
7
  Author URI: https://yarpp.com/
8
  Plugin URI: https://yarpp.com/
@@ -11,76 +11,82 @@ Text Domain: yarpp
11
 
12
  /**
13
  * Make sure we don't expose any info if called directly
14
- *
15
  */
16
- if ( !function_exists( 'add_action' ) ) {
17
- echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
18
- exit;
19
  }
20
 
21
- if(!defined('WP_CONTENT_URL')) define('WP_CONTENT_URL', get_option('siteurl').'/wp-content');
22
- if(!defined('WP_CONTENT_DIR')){
23
- $tr = get_theme_root();
24
- define('WP_CONTENT_DIR', substr($tr,0,strrpos($tr,'/')));
 
 
25
  }
26
 
27
- define('YARPP_VERSION', '5.23.0');
28
 
29
- define('YARPP_DIR', dirname(__FILE__));
30
  /**
31
  * @deprecated Instead use plugins_url(...,YARPP_MAIN_FILE);. See https://wordpress.org/support/topic/support-for-multilingual-2/
32
  * This may be removed after October 2020.
33
  */
34
- define('YARPP_URL', plugins_url('',__FILE__));
35
- define('YARPP_MAIN_FILE',__FILE__);
36
 
37
- define('YARPP_NO_RELATED', ':(');
38
- define('YARPP_RELATED', ':)');
39
- define('YARPP_NOT_CACHED', ':/');
40
- define('YARPP_DONT_RUN', 'X(');
41
 
42
  /*
43
  Since v3.2: YARPP uses it own cache engine, which uses custom db tables by default.
44
  Use postmeta instead to avoid custom tables by un-commenting postmeta line and comment out the tables one.
45
  */
46
 
47
- /* Enable postmeta cache: */
48
- //if(!defined('YARPP_CACHE_TYPE')) define('YARPP_CACHE_TYPE', 'postmeta');
 
49
 
50
  /* Enable Yarpp cache engine - Default: */
51
- if(!defined('YARPP_CACHE_TYPE')) define('YARPP_CACHE_TYPE', 'tables');
 
 
52
 
53
  /* Load proper cache constants */
54
- switch(YARPP_CACHE_TYPE){
55
- case 'tables':
56
- define('YARPP_TABLES_RELATED_TABLE', 'yarpp_related_cache');
57
- break;
58
- case 'postmeta':
59
- define('YARPP_POSTMETA_KEYWORDS_KEY', '_yarpp_keywords');
60
- define('YARPP_POSTMETA_RELATED_KEY', '_yarpp_related');
61
- break;
62
  }
63
 
64
  /* New in 3.5: Set YARPP extra weight multiplier */
65
- if(!defined('YARPP_EXTRA_WEIGHT')) define('YARPP_EXTRA_WEIGHT', 3);
 
 
66
 
67
  /* Includes ----------------------------------------------------------------------------------------------------------*/
68
- include_once(YARPP_DIR.'/includes/compat.php');
69
- include_once(YARPP_DIR.'/includes/init_functions.php');
70
- include_once(YARPP_DIR.'/includes/related_functions.php');
71
- include_once(YARPP_DIR.'/includes/template_functions.php');
72
 
73
- include_once(YARPP_DIR.'/classes/YARPP_Core.php');
74
- include_once( YARPP_DIR.'/classes/YARPP_Block.php' );
75
- include_once(YARPP_DIR.'/classes/YARPP_Widget.php');
76
- include_once(YARPP_DIR.'/classes/YARPP_Cache.php');
77
- include_once(YARPP_DIR.'/classes/YARPP_Cache_Bypass.php');
78
- include_once(YARPP_DIR.'/classes/YARPP_Cache_'.ucfirst(YARPP_CACHE_TYPE).'.php');
79
- include_once( YARPP_DIR . '/lib/plugin-deactivation-survey/deactivate-feedback-form.php' );
80
- include_once(YARPP_DIR.'/classes/YARPP_DB_Schema.php');
81
- include_once(YARPP_DIR.'/classes/YARPP_DB_Options.php');
82
- include_once(YARPP_DIR.'/classes/YARPP_Shortcode.php');
83
 
84
  /* WP hooks ----------------------------------------------------------------------------------------------------------*/
85
- add_action('init', 'yarpp_init');
86
- add_action('activate_'.plugin_basename(__FILE__), 'yarpp_plugin_activate', 10, 1);
2
  /*
3
  Plugin Name: Yet Another Related Posts Plugin (YARPP)
4
  Description: Adds related posts to your site and in RSS feeds, based on a powerful, customizable algorithm.
5
+ Version: 5.24.0
6
  Author: YARPP
7
  Author URI: https://yarpp.com/
8
  Plugin URI: https://yarpp.com/
11
 
12
  /**
13
  * Make sure we don't expose any info if called directly
 
14
  */
15
+ if ( ! function_exists( 'add_action' ) ) {
16
+ echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
17
+ exit;
18
  }
19
 
20
+ if ( ! defined( 'WP_CONTENT_URL' ) ) {
21
+ define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
22
+ }
23
+ if ( ! defined( 'WP_CONTENT_DIR' ) ) {
24
+ $tr = get_theme_root();
25
+ define( 'WP_CONTENT_DIR', substr( $tr, 0, strrpos( $tr, '/' ) ) );
26
  }
27
 
28
+ define( 'YARPP_VERSION', '5.24.0' );
29
 
30
+ define( 'YARPP_DIR', dirname( __FILE__ ) );
31
  /**
32
  * @deprecated Instead use plugins_url(...,YARPP_MAIN_FILE);. See https://wordpress.org/support/topic/support-for-multilingual-2/
33
  * This may be removed after October 2020.
34
  */
35
+ define( 'YARPP_URL', plugins_url( '', __FILE__ ) );
36
+ define( 'YARPP_MAIN_FILE', __FILE__ );
37
 
38
+ define( 'YARPP_NO_RELATED', ':(' );
39
+ define( 'YARPP_RELATED', ':)' );
40
+ define( 'YARPP_NOT_CACHED', ':/' );
41
+ define( 'YARPP_DONT_RUN', 'X(' );
42
 
43
  /*
44
  Since v3.2: YARPP uses it own cache engine, which uses custom db tables by default.
45
  Use postmeta instead to avoid custom tables by un-commenting postmeta line and comment out the tables one.
46
  */
47
 
48
+ /*
49
+ Enable postmeta cache: */
50
+ // if(!defined('YARPP_CACHE_TYPE')) define('YARPP_CACHE_TYPE', 'postmeta');
51
 
52
  /* Enable Yarpp cache engine - Default: */
53
+ if ( ! defined( 'YARPP_CACHE_TYPE' ) ) {
54
+ define( 'YARPP_CACHE_TYPE', 'tables' );
55
+ }
56
 
57
  /* Load proper cache constants */
58
+ switch ( YARPP_CACHE_TYPE ) {
59
+ case 'tables':
60
+ define( 'YARPP_TABLES_RELATED_TABLE', 'yarpp_related_cache' );
61
+ break;
62
+ case 'postmeta':
63
+ define( 'YARPP_POSTMETA_KEYWORDS_KEY', '_yarpp_keywords' );
64
+ define( 'YARPP_POSTMETA_RELATED_KEY', '_yarpp_related' );
65
+ break;
66
  }
67
 
68
  /* New in 3.5: Set YARPP extra weight multiplier */
69
+ if ( ! defined( 'YARPP_EXTRA_WEIGHT' ) ) {
70
+ define( 'YARPP_EXTRA_WEIGHT', 3 );
71
+ }
72
 
73
  /* Includes ----------------------------------------------------------------------------------------------------------*/
74
+ require_once YARPP_DIR . '/includes/compat.php';
75
+ require_once YARPP_DIR . '/includes/init_functions.php';
76
+ require_once YARPP_DIR . '/includes/related_functions.php';
77
+ require_once YARPP_DIR . '/includes/template_functions.php';
78
 
79
+ require_once YARPP_DIR . '/classes/YARPP_Core.php';
80
+ require_once YARPP_DIR . '/classes/YARPP_Block.php';
81
+ require_once YARPP_DIR . '/classes/YARPP_Widget.php';
82
+ require_once YARPP_DIR . '/classes/YARPP_Cache.php';
83
+ require_once YARPP_DIR . '/classes/YARPP_Cache_Bypass.php';
84
+ require_once YARPP_DIR . '/classes/YARPP_Cache_' . ucfirst( YARPP_CACHE_TYPE ) . '.php';
85
+ require_once YARPP_DIR . '/lib/plugin-deactivation-survey/deactivate-feedback-form.php';
86
+ require_once YARPP_DIR . '/classes/YARPP_DB_Schema.php';
87
+ require_once YARPP_DIR . '/classes/YARPP_DB_Options.php';
88
+ require_once YARPP_DIR . '/classes/YARPP_Shortcode.php';
89
 
90
  /* WP hooks ----------------------------------------------------------------------------------------------------------*/
91
+ add_action( 'init', 'yarpp_init' );
92
+ add_action( 'activate_' . plugin_basename( __FILE__ ), 'yarpp_plugin_activate', 10, 1 );