PluginProbe
Parse.ly / 3.0.0
Parse.ly v3.0.0
3.24.1 3.24.0 3.23.7 3.23.6 3.23.5 3.23.4 3.23.3 3.16.0 3.16.1 3.16.2 3.16.3 3.16.4 3.17.0 3.18.0 3.18.1 3.19.0 3.19.1 3.19.2 3.19.3 3.2.0 3.2.1 3.20.0 3.20.1 3.20.2 3.20.3 All 105 releases
wp-parsely / src / class-parsely.php

class-parsely.php in Parse.ly 3.0.0, at src/class-parsely.php

1,035 lines 35.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Parsely class
4 *
5 * @package Parsely
6 * @since 2.5.0
7 */
8
9 declare(strict_types=1);
10
11 namespace Parsely;
12
13 use WP_Post;
14 use WP_User;
15
16 /**
17 * Holds most of the logic for the plugin.
18 *
19 * @since 1.0.0
20 * @since 2.5.0 Moved from plugin root file to this file.
21 */
22 class Parsely {
23 /**
24 * Declare our constants
25 */
26 public const VERSION = PARSELY_VERSION;
27 public const MENU_SLUG = 'parsely'; // Defines the page param passed to options-general.php.
28 public const OPTIONS_KEY = 'parsely'; // Defines the key used to store options in the WP database.
29 public const CAPABILITY = 'manage_options'; // The capability required for the user to administer settings.
30
31 /**
32 * Declare some class properties
33 *
34 * @var array $option_defaults The defaults we need for the class.
35 */
36 private $option_defaults = array(
37 'apikey' => '',
38 'content_id_prefix' => '',
39 'api_secret' => '',
40 'use_top_level_cats' => false,
41 'custom_taxonomy_section' => 'category',
42 'cats_as_tags' => false,
43 'track_authenticated_users' => true,
44 'lowercase_tags' => true,
45 'force_https_canonicals' => false,
46 'track_post_types' => array( 'post' ),
47 'track_page_types' => array( 'page' ),
48 'disable_javascript' => false,
49 'disable_amp' => false,
50 'meta_type' => 'json_ld',
51 'logo' => '',
52 'metadata_secret' => '',
53 'parsely_wipe_metadata_cache' => false,
54 );
55
56 /**
57 * Declare post types that Parse.ly will process as "posts".
58 *
59 * @link https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages
60 *
61 * @since 2.5.0
62 * @var string[]
63 */
64 private $supported_jsonld_post_types = array(
65 'NewsArticle',
66 'Article',
67 'TechArticle',
68 'BlogPosting',
69 'LiveBlogPosting',
70 'Report',
71 'Review',
72 'CreativeWork',
73 );
74
75 /**
76 * Declare post types that Parse.ly will process as "non-posts".
77 *
78 * @link https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages
79 *
80 * @since 2.5.0
81 * @var string[]
82 */
83 private $supported_jsonld_non_post_types = array(
84 'WebPage',
85 'Event',
86 'Hotel',
87 'Restaurant',
88 'Movie',
89 );
90
91 /**
92 * Register action and filter hook callbacks.
93 *
94 * Also, immediately upgrade options if needed.
95 *
96 * @return void
97 */
98 public function run(): void {
99 // Run upgrade options if they exist for the version currently defined.
100 $options = $this->get_options();
101 if ( empty( $options['plugin_version'] ) || self::VERSION !== $options['plugin_version'] ) {
102 $method = 'upgrade_plugin_to_version_' . str_replace( '.', '_', self::VERSION );
103 if ( method_exists( $this, $method ) ) {
104 call_user_func_array( array( $this, $method ), array( $options ) );
105 }
106 // Update our version info.
107 $options['plugin_version'] = self::VERSION;
108 update_option( self::OPTIONS_KEY, $options );
109 }
110
111 // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval
112 add_filter( 'cron_schedules', array( $this, 'wpparsely_add_cron_interval' ) );
113 add_action( 'parsely_bulk_metas_update', array( $this, 'bulk_update_posts' ) );
114 add_action( 'save_post', array( $this, 'update_metadata_endpoint' ) );
115 add_action( 'wp_head', array( $this, 'insert_page_header_metadata' ) );
116 add_action( 'wp_enqueue_scripts', array( $this, 'wp_parsely_style_init' ) );
117 }
118
119 /**
120 * Adds 10 minute cron interval.
121 *
122 * @param array $schedules WP schedules array.
123 * @return array
124 */
125 public function wpparsely_add_cron_interval( array $schedules ): array {
126 $schedules['everytenminutes'] = array(
127 'interval' => 600, // time in seconds.
128 'display' => __( 'Every 10 Minutes', 'wp-parsely' ),
129 );
130 return $schedules;
131 }
132
133 /**
134 * Initialize Parse.ly WordPress style.
135 *
136 * @return void
137 */
138 public function wp_parsely_style_init(): void {
139 wp_register_style( 'wp-parsely-style', plugin_dir_url( PARSELY_FILE ) . 'wp-parsely.css', array(), self::VERSION );
140 }
141
142 /**
143 * Actually inserts the code for the <meta name='parsely-page'> parameter within the <head></head> tag.
144 *
145 * @since 3.0.0
146 *
147 * @return void
148 */
149 public function insert_page_header_metadata(): void {
150 /**
151 * Filters whether the Parse.ly meta tags should be inserted in the page.
152 *
153 * By default, the tags are inserted.
154 *
155 * @since 3.0.0
156 *
157 * @param bool $insert_metadata True to insert the metadata, false otherwise.
158 */
159 if ( ! apply_filters( 'wp_parsely_should_insert_metadata', true ) ) {
160 return;
161 }
162
163 $parsely_options = $this->get_options();
164
165 if (
166 $this->api_key_is_missing() ||
167
168 // Chosen not to track logged-in users.
169 ( ! $parsely_options['track_authenticated_users'] && $this->parsely_is_user_logged_in() ) ||
170
171 // 404 pages are not tracked.
172 is_404() ||
173
174 // Search pages are not tracked.
175 is_search()
176 ) {
177 return;
178 }
179
180 global $post;
181
182 // We can't construct the metadata without a valid post object.
183 if ( empty( $post ) ) {
184 return;
185 }
186
187 // Assign default values for LD+JSON
188 // TODO: Mapping of an install's post types to Parse.ly post types (namely page/post).
189 $parsely_page = $this->construct_parsely_metadata( $parsely_options, $post );
190
191 // Something went wrong - abort.
192 if ( empty( $parsely_page ) || ! isset( $parsely_page['headline'] ) ) {
193 return;
194 }
195
196 echo "\n" . '<!-- BEGIN Parse.ly ' . esc_html( self::VERSION ) . ' -->' . "\n";
197
198 // Insert JSON-LD or repeated metas.
199 if ( 'json_ld' === $parsely_options['meta_type'] ) {
200 include plugin_dir_path( PARSELY_FILE ) . 'views/json-ld.php';
201 } else {
202 // Assume `meta_type` is `repeated_metas`.
203 $parsely_post_type = $this->convert_jsonld_to_parsely_type( $parsely_page['@type'] );
204 if ( isset( $parsely_page['keywords'] ) && is_array( $parsely_page['keywords'] ) ) {
205 $parsely_page['keywords'] = implode( ',', $parsely_page['keywords'] );
206 }
207
208 $parsely_metas = array(
209 'title' => $parsely_page['headline'] ?? null,
210 'link' => $parsely_page['url'] ?? null,
211 'type' => $parsely_post_type,
212 'image-url' => $parsely_page['thumbnailUrl'] ?? null,
213 'pub-date' => $parsely_page['datePublished'] ?? null,
214 'section' => $parsely_page['articleSection'] ?? null,
215 'tags' => $parsely_page['keywords'] ?? null,
216 'author' => isset( $parsely_page['author'] ),
217 );
218 $parsely_metas = array_filter( $parsely_metas, array( $this, 'filter_empty_and_not_string_from_array' ) );
219
220 if ( isset( $parsely_page['author'] ) ) {
221 $parsely_page_authors = wp_list_pluck( $parsely_page['author'], 'name' );
222 $parsely_page_authors = array_filter( $parsely_page_authors, array( $this, 'filter_empty_and_not_string_from_array' ) );
223 }
224
225 include plugin_dir_path( PARSELY_FILE ) . 'views/repeated-metas.php';
226 }
227
228 // Add any custom metadata.
229 if ( isset( $parsely_page['custom_metadata'] ) ) {
230 include plugin_dir_path( PARSELY_FILE ) . 'views/custom-metadata.php';
231 }
232
233 echo '<!-- END Parse.ly -->' . "\n\n";
234 }
235
236 /**
237 * Deprecated. Echoes the metadata into the page, and returns the inserted values.
238 *
239 * To just echo the metadata, use the `insert_page_header_metadata()` method.
240 * To get the metadata to be inserted, use the `construct_parsely_metadata()` method.
241 *
242 * @deprecated 3.0.0
243 * @see construct_parsely_metadata()
244 *
245 * @return array
246 */
247 public function insert_parsely_page(): array {
248 _deprecated_function( __FUNCTION__, '3.0', 'construct_parsely_metadata()' );
249 $this->insert_page_header_metadata();
250
251 global $post;
252 return $this->construct_parsely_metadata( $this->get_options(), $post );
253 }
254
255 /**
256 * Function to be used in `array_filter` to clean up repeated metas
257 *
258 * @param mixed $var Value to filter from the array.
259 * @return bool Returns true if the variable is not empty, and it's a string
260 */
261 private static function filter_empty_and_not_string_from_array( $var ): bool {
262 return ! empty( $var ) && is_string( $var );
263 }
264
265 /**
266 * Compare the post_status key against an allowed list (by default, only 'publish'ed content includes tracking data).
267 *
268 * @since 2.5.0
269 *
270 * @param int|WP_Post $post Which post object or ID to check.
271 * @return bool Should the post status be tracked for the provided post's post_type. By default, only 'publish' is allowed.
272 */
273 public static function post_has_trackable_status( $post ): bool {
274 static $cache = array();
275 $post_id = is_int( $post ) ? $post : $post->ID;
276 if ( isset( $cache[ $post_id ] ) ) {
277 return $cache[ $post_id ];
278 }
279
280 /**
281 * Filters the statuses that are permitted to be tracked.
282 *
283 * By default, the only status tracked is 'publish'. Use this filter if you have other published content that has a different (custom) status.
284 *
285 * @since 2.5.0
286 *
287 * @param string[] $trackable_statuses The list of post statuses that are allowed to be tracked.
288 * @param int|WP_Post $post Which post object or ID is being checked.
289 */
290 $statuses = apply_filters( 'wp_parsely_trackable_statuses', array( 'publish' ), $post );
291 $cache[ $post_id ] = in_array( get_post_status( $post ), $statuses, true );
292 return $cache[ $post_id ];
293 }
294
295 /**
296 * Creates parsely metadata object from post metadata.
297 *
298 * @param array $parsely_options parsely_options array.
299 * @param WP_Post $post object.
300 * @return array
301 */
302 public function construct_parsely_metadata( array $parsely_options, WP_Post $post ): array {
303 $parsely_page = array(
304 '@context' => 'http://schema.org',
305 '@type' => 'WebPage',
306 );
307 $current_url = $this->get_current_url();
308 $queried_object_id = get_queried_object_id();
309
310 if ( is_front_page() && ! is_paged() ) {
311 $parsely_page['headline'] = $this->get_clean_parsely_page_value( get_bloginfo( 'name', 'raw' ) );
312 $parsely_page['url'] = home_url();
313 } elseif ( is_front_page() && is_paged() ) {
314 $parsely_page['headline'] = $this->get_clean_parsely_page_value( get_bloginfo( 'name', 'raw' ) );
315 $parsely_page['url'] = $current_url;
316 } elseif (
317 is_home() && (
318 ! ( 'page' === get_option( 'show_on_front' ) && ! get_option( 'page_on_front' ) ) ||
319 $queried_object_id && (int) get_option( 'page_for_posts' ) === $queried_object_id
320 )
321 ) {
322 $parsely_page['headline'] = get_the_title( get_option( 'page_for_posts', true ) );
323 $parsely_page['url'] = $current_url;
324 } elseif ( is_author() ) {
325 // TODO: why can't we have something like a WP_User object for all the other cases? Much nicer to deal with than functions.
326 $author = ( get_query_var( 'author_name' ) ) ? get_user_by( 'slug', get_query_var( 'author_name' ) ) : get_userdata( get_query_var( 'author' ) );
327 $parsely_page['headline'] = $this->get_clean_parsely_page_value( 'Author - ' . $author->data->display_name );
328 $parsely_page['url'] = $current_url;
329 } elseif ( is_category() || is_post_type_archive() || is_tax() ) {
330 $category = get_queried_object();
331 $parsely_page['headline'] = $this->get_clean_parsely_page_value( $category->name );
332 $parsely_page['url'] = $current_url;
333 } elseif ( is_date() ) {
334 if ( is_year() ) {
335 /* translators: %s: Archive year */
336 $parsely_page['headline'] = sprintf( __( 'Yearly Archive - %s', 'wp-parsely' ), get_the_time( 'Y' ) );
337 } elseif ( is_month() ) {
338 /* translators: %s: Archive month, formatted as F, Y */
339 $parsely_page['headline'] = sprintf( __( 'Monthly Archive - %s', 'wp-parsely' ), get_the_time( 'F, Y' ) );
340 } elseif ( is_day() ) {
341 /* translators: %s: Archive day, formatted as F jS, Y */
342 $parsely_page['headline'] = sprintf( __( 'Daily Archive - %s', 'wp-parsely' ), get_the_time( 'F jS, Y' ) );
343 } elseif ( is_time() ) {
344 /* translators: %s: Archive time, formatted as F jS g:i:s A */
345 $parsely_page['headline'] = sprintf( __( 'Hourly, Minutely, or Secondly Archive - %s', 'wp-parsely' ), get_the_time( 'F jS g:i:s A' ) );
346 }
347 $parsely_page['url'] = $current_url;
348 } elseif ( is_tag() ) {
349 $tag = single_tag_title( '', false );
350 if ( empty( $tag ) ) {
351 $tag = single_term_title( '', false );
352 }
353 /* translators: %s: Tag name */
354 $parsely_page['headline'] = $this->get_clean_parsely_page_value( sprintf( __( 'Tagged - %s', 'wp-parsely' ), $tag ) );
355 $parsely_page['url'] = $current_url;
356 } elseif ( in_array( get_post_type( $post ), $parsely_options['track_post_types'], true ) && self::post_has_trackable_status( $post ) ) {
357 $authors = $this->get_author_names( $post );
358 $category = $this->get_category_name( $post, $parsely_options );
359
360 if ( has_post_thumbnail( $post ) ) {
361 $image_id = get_post_thumbnail_id( $post );
362 $image_url = wp_get_attachment_image_src( $image_id );
363 $image_url = $image_url[0];
364 } else {
365 $image_url = $this->get_first_image( $post );
366 }
367
368 $tags = $this->get_tags( $post->ID );
369 if ( $parsely_options['cats_as_tags'] ) {
370 $tags = array_merge( $tags, $this->get_categories( $post->ID ) );
371 // add custom taxonomy values.
372 $tags = array_merge( $tags, $this->get_custom_taxonomy_values( $post, $parsely_options ) );
373 }
374 // the function 'mb_strtolower' is not enabled by default in php, so this check
375 // falls back to the native php function 'strtolower' if necessary.
376 if ( function_exists( 'mb_strtolower' ) ) {
377 $lowercase_callback = 'mb_strtolower';
378 } else {
379 $lowercase_callback = 'strtolower';
380 }
381 if ( $parsely_options['lowercase_tags'] ) {
382 $tags = array_map( $lowercase_callback, $tags );
383 }
384
385 /**
386 * Filters the post tags that are used as metadata keywords.
387 *
388 * @since 1.8.0
389 *
390 * @param string[] $tags Post tags.
391 * @param int $ID Post ID.
392 */
393 $tags = apply_filters( 'wp_parsely_post_tags', $tags, $post->ID );
394 $tags = array_map( array( $this, 'get_clean_parsely_page_value' ), $tags );
395 $tags = array_values( array_unique( $tags ) );
396
397 /**
398 * Filters the JSON-LD @type.
399 *
400 * @since 2.5.0
401 *
402 * @param array $jsonld_type JSON-LD @type value, default is NewsArticle.
403 * @param int $id Post ID.
404 * @param string $post_type The Post type in WordPress.
405 */
406 $type = (string) apply_filters( 'wp_parsely_post_type', 'NewsArticle', $post->ID, $post->post_type );
407 $supported_types = array_merge( $this->supported_jsonld_post_types, $this->supported_jsonld_non_post_types );
408
409 // Validate type before passing it further as an invalid type will not be recognized by Parse.ly.
410 if ( ! in_array( $type, $supported_types ) ) {
411 $error = sprintf(
412 /* translators: 1: JSON @type like NewsArticle, 2: URL */
413 __( '@type %1$s is not supported by Parse.ly. Please use a type mentioned in %2$s', 'wp-parsely' ),
414 $type,
415 'https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages'
416 );
417 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
418 trigger_error( esc_html( $error ), E_USER_WARNING );
419 $type = 'NewsArticle';
420 }
421
422 $parsely_page['@type'] = $type;
423 $parsely_page['mainEntityOfPage'] = array(
424 '@type' => 'WebPage',
425 '@id' => $this->get_current_url( 'post' ),
426 );
427 $parsely_page['headline'] = $this->get_clean_parsely_page_value( get_the_title( $post ) );
428 $parsely_page['url'] = $this->get_current_url( 'post', $post->ID );
429 $parsely_page['thumbnailUrl'] = $image_url;
430 $parsely_page['image'] = array(
431 '@type' => 'ImageObject',
432 'url' => $image_url,
433 );
434 $parsely_page['dateCreated'] = gmdate( 'Y-m-d\TH:i:s\Z', get_post_time( 'U', true, $post ) );
435 $parsely_page['datePublished'] = gmdate( 'Y-m-d\TH:i:s\Z', get_post_time( 'U', true, $post ) );
436 if ( get_the_modified_date( 'U', true ) >= get_post_time( 'U', true, $post ) ) {
437 $parsely_page['dateModified'] = gmdate( 'Y-m-d\TH:i:s\Z', get_the_modified_date( 'U', true ) );
438 } else {
439 // Use the post time as the earliest possible modification date.
440 $parsely_page['dateModified'] = gmdate( 'Y-m-d\TH:i:s\Z', get_post_time( 'U', true, $post ) );
441 }
442 $parsely_page['articleSection'] = $category;
443 $author_objects = array();
444 foreach ( $authors as $author ) {
445 $author_tag = array(
446 '@type' => 'Person',
447 'name' => $author,
448 );
449 array_push( $author_objects, $author_tag );
450 }
451 $parsely_page['author'] = $author_objects;
452 $parsely_page['creator'] = $authors;
453 $parsely_page['publisher'] = array(
454 '@type' => 'Organization',
455 'name' => get_bloginfo( 'name' ),
456 'logo' => $parsely_options['logo'],
457 );
458 $parsely_page['keywords'] = $tags;
459 } elseif ( in_array( get_post_type(), $parsely_options['track_page_types'], true ) && self::post_has_trackable_status( $post ) ) {
460 $parsely_page['headline'] = $this->get_clean_parsely_page_value( get_the_title( $post ) );
461 $parsely_page['url'] = $this->get_current_url( 'post' );
462 } elseif ( 'page' === get_option( 'show_on_front' ) && ! get_option( 'page_on_front' ) ) {
463 $parsely_page['headline'] = $this->get_clean_parsely_page_value( get_bloginfo( 'name', 'raw' ) );
464 $parsely_page['url'] = home_url();
465 }
466
467 /**
468 * Filters the structured metadata.
469 *
470 * @since 2.5.0
471 *
472 * @param array $parsely_page Existing structured metadata for a page.
473 * @param WP_Post $post Post object.
474 * @param array $parsely_options The Parsely options.
475 */
476 return apply_filters( 'wp_parsely_metadata', $parsely_page, $post, $parsely_options );
477 }
478
479 /**
480 * Updates the Parsely metadata endpoint with the new metadata of the post.
481 *
482 * @param int $post_id id of the post to update.
483 * @return void
484 */
485 public function update_metadata_endpoint( int $post_id ): void {
486 $parsely_options = $this->get_options();
487
488 if ( $this->api_key_is_missing() || empty( $parsely_options['metadata_secret'] ) ) {
489 return;
490 }
491
492 $post = get_post( $post_id );
493 $metadata = $this->construct_parsely_metadata( $parsely_options, $post );
494
495 $endpoint_metadata = array(
496 'canonical_url' => $metadata['url'],
497 'page_type' => $this->convert_jsonld_to_parsely_type( $metadata['@type'] ),
498 'title' => $metadata['headline'],
499 'image_url' => $metadata['thumbnailUrl'],
500 'pub_date_tmsp' => $metadata['datePublished'],
501 'section' => $metadata['articleSection'],
502 'authors' => $metadata['creator'],
503 'tags' => $metadata['keywords'],
504 );
505
506 $parsely_api_endpoint = 'https://api.parsely.com/v2/metadata/posts';
507 $parsely_metadata_secret = $parsely_options['metadata_secret'];
508 $headers = array(
509 'Content-Type' => 'application/json',
510 );
511 $body = wp_json_encode(
512 array(
513 'secret' => $parsely_metadata_secret,
514 'apikey' => $parsely_options['apikey'],
515 'metadata' => $endpoint_metadata,
516 )
517 );
518 $response = wp_remote_post(
519 $parsely_api_endpoint,
520 array(
521 'method' => 'POST',
522 'headers' => $headers,
523 'blocking' => false,
524 'body' => $body,
525 'data_format' => 'body',
526 )
527 );
528
529 if ( ! is_wp_error( $response ) ) {
530 $current_timestamp = time();
531 update_post_meta( $post_id, 'parsely_metadata_last_updated', $current_timestamp );
532 }
533 }
534
535 /**
536 * Updates posts with Parsely metadata api in bulk.
537 *
538 * @return void
539 */
540 public function bulk_update_posts(): void {
541 global $wpdb;
542 $parsely_options = $this->get_options();
543 $allowed_types = array_merge( $parsely_options['track_post_types'], $parsely_options['track_page_types'] );
544 $allowed_types_string = implode(
545 ', ',
546 array_map(
547 function( $v ) {
548 return "'" . esc_sql( $v ) . "'";
549 },
550 $allowed_types
551 )
552 );
553 $ids = wp_cache_get( 'parsely_post_ids_need_meta_updating' );
554 if ( false === $ids ) {
555 $ids = array();
556 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
557 $results = $wpdb->get_results(
558 $wpdb->prepare( "SELECT DISTINCT(id) FROM {$wpdb->posts} WHERE post_type IN (\" . %s . \") AND id NOT IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'parsely_metadata_last_updated');", $allowed_types_string ),
559 ARRAY_N
560 );
561 foreach ( $results as $result ) {
562 array_push( $ids, $result[0] );
563 }
564 wp_cache_set( 'parsely_post_ids_need_meta_updating', $ids, '', 86400 );
565 }
566
567 for ( $i = 0; $i < 100; $i++ ) {
568 $post_id = array_pop( $ids );
569 if ( null === $post_id ) {
570 wp_clear_scheduled_hook( 'parsely_bulk_metas_update' );
571 break;
572 }
573 $this->update_metadata_endpoint( $post_id );
574 }
575 }
576
577 /**
578 * Get the cache buster value for script and styles.
579 *
580 * If WP_DEBUG is defined and truthy, and we're not running tests, then use a random number.
581 * Otherwise, use the plugin version.
582 *
583 * @since 2.5.0
584 *
585 * @return string Random number string or plugin version string.
586 */
587 public static function get_asset_cache_buster(): string {
588 static $cache_buster;
589 if ( isset( $cache_buster ) ) {
590 return $cache_buster;
591 }
592
593 $cache_buster = defined( 'WP_DEBUG' ) && WP_DEBUG && empty( 'WP_TESTS_DOMAIN' ) ? wp_rand() : PARSELY_VERSION;
594
595 /**
596 * Filters the cache buster value for linked scripts and styles.
597 *
598 * @since 2.5.0
599 *
600 * @param string $cache_buster Plugin version, unless WP_DEBUG is defined and truthy, and tests are not running.
601 */
602 return apply_filters( 'wp_parsely_cache_buster', (string) $cache_buster );
603 }
604
605 /**
606 * Returns the tags associated with this page or post
607 *
608 * @param int $post_id The id of the post you're trying to get tags for.
609 * @return array The tags of the post represented by the post id.
610 */
611 private function get_tags( int $post_id ): array {
612 $tags = array();
613 foreach ( wp_get_post_tags( $post_id ) as $wp_tag ) {
614 array_push( $tags, $wp_tag->name );
615 }
616
617 return $tags;
618 }
619
620 /**
621 * Returns an array of all the child categories for the current post
622 *
623 * @param int $post_id The id of the post you're trying to get categories for.
624 * @param string $delimiter What character will delimit the categories.
625 * @return array All the child categories of the current post.
626 */
627 private function get_categories( int $post_id, string $delimiter = '/' ): array {
628 $tags = array();
629 foreach ( get_the_category( $post_id ) as $category ) {
630 $hierarchy = get_category_parents( $category, false, $delimiter );
631 $hierarchy = rtrim( $hierarchy, '/' );
632 array_push( $tags, $hierarchy );
633 }
634 // take last element in the hierarchy, a string representing the full parent->child tree,
635 // and split it into individual category names.
636 $tags = explode( '/', end( $tags ) );
637 // remove uncategorized value from tags.
638 return array_diff( $tags, array( 'Uncategorized' ) );
639 }
640
641 /**
642 * Safely returns options for the plugin by assigning defaults contained in optionDefaults. As soon as actual
643 * options are saved, they override the defaults. This prevents us from having to do a lot of isset() checking
644 * on variables.
645 *
646 * @return array
647 */
648 public function get_options(): array {
649 $options = get_option( self::OPTIONS_KEY, $this->option_defaults );
650
651 if ( ! is_array( $options ) ) {
652 return $this->option_defaults;
653 }
654
655 return array_merge( $this->option_defaults, $options );
656 }
657
658 /**
659 * Returns a properly cleaned category/taxonomy value and will optionally use the top-level category/taxonomy value
660 * if so instructed via the `use_top_level_cats` option.
661 *
662 * @param WP_Post $post_obj The object for the post.
663 * @param array $parsely_options The parsely options.
664 * @return string Cleaned category name for the post in question.
665 */
666 private function get_category_name( WP_Post $post_obj, array $parsely_options ): string {
667 $taxonomy_dropdown_choice = get_the_terms( $post_obj->ID, $parsely_options['custom_taxonomy_section'] );
668 // Get top-level taxonomy name for chosen taxonomy and assign to $parent_name; it will be used
669 // as the category value if 'use_top_level_cats' option is checked.
670 // Assign as "Uncategorized" if no value is checked for the chosen taxonomy.
671 $category = 'Uncategorized';
672 if ( ! empty( $taxonomy_dropdown_choice ) ) {
673 if ( $parsely_options['use_top_level_cats'] ) {
674 $first_term = array_shift( $taxonomy_dropdown_choice );
675 $term_name = $this->get_top_level_term( $first_term->term_id, $first_term->taxonomy );
676 } else {
677 $term_name = $this->get_bottom_level_term( $post_obj->ID, $parsely_options['custom_taxonomy_section'] );
678 }
679
680 if ( $term_name ) {
681 $category = $term_name;
682 }
683 }
684
685 /**
686 * Filters the constructed category name that are used as metadata keywords.
687 *
688 * @since 1.8.0
689 *
690 * @param string $category Category name.
691 * @param WP_Post $post_obj Post object.
692 * @param array $parsely_options The Parsely options.
693 */
694 $category = apply_filters( 'wp_parsely_post_category', $category, $post_obj, $parsely_options );
695
696 return $this->get_clean_parsely_page_value( $category );
697 }
698
699 /**
700 * Return the top-most category/taxonomy value in a hierarcy given a taxonomy value's ID
701 * ( WordPress calls taxonomy values 'terms' ).
702 *
703 * @param int $term_id The id of the top level term.
704 * @param string $taxonomy_name The name of the taxonomy.
705 * @return string|false $parent The top level name of the category / taxonomy.
706 */
707 private function get_top_level_term( int $term_id, string $taxonomy_name ) {
708 $parent = get_term_by( 'id', $term_id, $taxonomy_name );
709 while ( false !== $parent && 0 !== $parent->parent ) {
710 $parent = get_term_by( 'id', $parent->parent, $taxonomy_name );
711 }
712 return $parent ? $parent->name : false;
713 }
714
715 /**
716 * Return the bottom-most category/taxonomy value in a hierarcy given a post ID
717 * ( WordPress calls taxonomy values 'terms' ).
718 *
719 * @param int $post_id The post id you're interested in.
720 * @param string $taxonomy_name The name of the taxonomy.
721 * @return string Name of the custom taxonomy.
722 */
723 private function get_bottom_level_term( int $post_id, string $taxonomy_name ): string {
724 $terms = get_the_terms( $post_id, $taxonomy_name );
725 $term_ids = is_array( $terms ) ? wp_list_pluck( $terms, 'term_id' ) : array();
726 $parents = is_array( $terms ) ? array_filter( wp_list_pluck( $terms, 'parent' ) ) : array();
727
728 // Get array of IDs of terms which are not parents.
729 $term_ids_not_parents = array_diff( $term_ids, $parents );
730 // Get corresponding term objects, which are mapped to array index keys.
731 $terms_not_parents = array_intersect_key( $terms, $term_ids_not_parents );
732 // remove array index keys.
733 $terms_not_parents_cleaned = array();
734 foreach ( $terms_not_parents as $index => $value ) {
735 array_push( $terms_not_parents_cleaned, $value );
736 }
737 // if you assign multiple child terms in a custom taxonomy, will only return the first.
738 return $terms_not_parents_cleaned[0]->name;
739 }
740
741 /**
742 * Get all term values from custom taxonomies.
743 *
744 * @param WP_Post $post_obj The post object.
745 * @param array $parsely_options Unused? The parsely options.
746 * @return array
747 */
748 private function get_custom_taxonomy_values( WP_Post $post_obj, array $parsely_options ): array {
749 // filter out default WordPress taxonomies.
750 $all_taxonomies = array_diff( get_taxonomies(), array( 'post_tag', 'nav_menu', 'author', 'link_category', 'post_format' ) );
751 $all_values = array();
752
753 if ( is_array( $all_taxonomies ) ) {
754 foreach ( $all_taxonomies as $taxonomy ) {
755 $custom_taxonomy_objects = get_the_terms( $post_obj->ID, $taxonomy );
756 if ( is_array( $custom_taxonomy_objects ) ) {
757 foreach ( $custom_taxonomy_objects as $custom_taxonomy_object ) {
758 array_push( $all_values, $custom_taxonomy_object->name );
759 }
760 }
761 }
762 }
763 return $all_values;
764 }
765
766 /**
767 * Returns a list of coauthors for a post assuming the Co-Authors Plus plugin is
768 * installed. Borrowed from
769 * https://github.com/Automattic/Co-Authors-Plus/blob/master/template-tags.php#L3-35
770 *
771 * @param int $post_id The id of the post.
772 * @return array
773 */
774 private function get_coauthor_names( int $post_id ): array {
775 $coauthors = array();
776 if ( class_exists( 'coauthors_plus' ) ) {
777 global $post, $post_ID, $coauthors_plus;
778
779 if ( ! $post_id && $post_ID ) {
780 $post_id = $post_ID;
781 }
782
783 if ( ! $post_id && $post ) {
784 $post_id = $post->ID;
785 }
786
787 if ( $post_id ) {
788 $coauthor_terms = get_the_terms( $post_id, $coauthors_plus->coauthor_taxonomy );
789
790 if ( is_array( $coauthor_terms ) && ! empty( $coauthor_terms ) ) {
791 foreach ( $coauthor_terms as $coauthor ) {
792 $coauthor_slug = preg_replace( '#^cap-#', '', $coauthor->slug );
793 $post_author = $coauthors_plus->get_coauthor_by( 'user_nicename', $coauthor_slug );
794 // In case the user has been deleted while plugin was deactivated.
795 if ( ! empty( $post_author ) ) {
796 $coauthors[] = new WP_User( $post_author );
797 }
798 }
799 } elseif ( ! $coauthors_plus->force_guest_authors ) {
800 if ( $post && $post_id === $post->ID ) {
801 $post_author = get_userdata( $post->post_author );
802 }
803 if ( ! empty( $post_author ) ) {
804 $coauthors[] = $post_author;
805 }
806 } // the empty else case is because if we force guest authors, we don't ever care what value wp_posts.post_author has.
807 }
808 }
809 return $coauthors;
810 }
811
812 /**
813 * Determine author name from display name, falling back to firstname
814 * lastname, then nickname and finally the nicename.
815 *
816 * @param ?WP_User $author The author of the post.
817 * @return string
818 */
819 private function get_author_name( ?WP_User $author ): string {
820 // gracefully handle situation where no author is available.
821 if ( empty( $author ) || ! is_object( $author ) ) {
822 return '';
823 }
824
825 $author_name = $author->display_name;
826 if ( ! empty( $author_name ) ) {
827 return $author_name;
828 }
829
830 $author_name = $author->user_firstname . ' ' . $author->user_lastname;
831 if ( ' ' !== $author_name ) {
832 return $author_name;
833 }
834
835 $author_name = $author->nickname;
836 if ( ! empty( $author_name ) ) {
837 return $author_name;
838 }
839
840 return $author->user_nicename;
841 }
842
843 /**
844 * Retrieve all the authors for a post as an array. Can include multiple
845 * authors if coauthors plugin is in use.
846 *
847 * @param WP_Post $post The post object.
848 * @return array
849 */
850 private function get_author_names( WP_Post $post ): array {
851 $authors = $this->get_coauthor_names( $post->ID );
852 if ( empty( $authors ) ) {
853 $post_author = get_user_by( 'id', $post->post_author );
854 if ( $post_author ) {
855 $authors = array( $post_author );
856 }
857 }
858
859 /**
860 * Filters the list of author WP_User objects for a post.
861 *
862 * @since 1.14.0
863 *
864 * @param WP_User[] $authors One or more authors as WP_User objects.
865 * @param WP_Post $post Post object.
866 */
867 $authors = apply_filters( 'wp_parsely_pre_authors', $authors, $post );
868
869 // Getting the author name for each author.
870 $authors = array_map( array( $this, 'get_author_name' ), $authors );
871
872 /**
873 * Filters the list of author names for a post.
874 *
875 * @since 1.14.0
876 *
877 * @param string[] $authors One or more author names.
878 * @param WP_Post $post Post object.
879 */
880 $authors = apply_filters( 'wp_parsely_post_authors', $authors, $post );
881 $authors = array_map( array( $this, 'get_clean_parsely_page_value' ), $authors );
882 return $authors;
883 }
884
885 /**
886 * Sanitize content
887 *
888 * @since 2.6.0
889 *
890 * @param string $val The content you'd like sanitized.
891 * @return string
892 */
893 public function get_clean_parsely_page_value( string $val ): string {
894 $val = str_replace( "\n", '', $val );
895 $val = str_replace( "\r", '', $val );
896 $val = wp_strip_all_tags( $val );
897 return trim( $val );
898 }
899
900 /**
901 * Get the URL of the plugin settings page.
902 *
903 * @return string
904 */
905 public static function get_settings_url(): string {
906 return admin_url( 'options-general.php?page=' . self::MENU_SLUG );
907 }
908
909 /**
910 * Get the URL of the current PHP script.
911 * A fall-back implementation to determine permalink
912 *
913 * @since 3.0.0 $parsely_type Default parameter changed to `non-post`.
914 *
915 * @param string $parsely_type Optional. Parse.ly post type you're interested in, either 'post' or 'non-post'. Default is 'non-post'.
916 * @param int $post_id Optional. ID of the post you want to get the URL for. Default is 0, which means the global `$post` is used.
917 * @return string
918 */
919 public function get_current_url( string $parsely_type = 'non-post', int $post_id = 0 ): string {
920 if ( 'post' === $parsely_type ) {
921 $permalink = (string) get_permalink( $post_id );
922
923 /**
924 * Filters the permalink for a post.
925 *
926 * @since 1.14.0
927 * @since 2.5.0 Added $post_id.
928 *
929 * @param string $permalink The permalink URL or false if post does not exist.
930 * @param string $parsely_type Parse.ly type ("post" or "non-post").
931 * @param int $post_id ID of the post you want to get the URL for. May be 0, so $permalink will be
932 * for the global $post.
933 */
934 $url = apply_filters( 'wp_parsely_permalink', $permalink, $parsely_type, $post_id );
935 } else {
936 $request_uri = isset( $_SERVER['REQUEST_URI'] )
937 ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) )
938 : '';
939
940 $url = home_url( $request_uri );
941 }
942
943 $options = $this->get_options();
944 return $options['force_https_canonicals']
945 ? str_replace( 'http://', 'https://', $url )
946 : str_replace( 'https://', 'http://', $url );
947 }
948
949 /**
950 * Get the first image from a post
951 * https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
952 *
953 * @param WP_Post $post The post object you're interested in.
954 * @return string
955 */
956 public function get_first_image( WP_Post $post ): string {
957 ob_start();
958 ob_end_clean();
959 if ( preg_match_all( '/<img.+src=[\'"]( [^\'"]+ )[\'"].*>/i', $post->post_content, $matches ) ) {
960 return $matches[1][0];
961 }
962 return '';
963 }
964
965 /**
966 * Check to see if parsely user is logged in.
967 *
968 * @return bool
969 */
970 public function parsely_is_user_logged_in(): bool {
971 // can't use $blog_id here because it futzes with the global $blog_id.
972 $current_blog_id = get_current_blog_id();
973 $current_user_id = get_current_user_id();
974 return is_user_member_of_blog( $current_user_id, $current_blog_id );
975 }
976
977 /**
978 * Convert JSON-LD type to respective Parse.ly page type.
979 *
980 * If the JSON-LD type is one of the types Parse.ly supports as a "post", then "post" will be returned.
981 * Otherwise, for "non-posts" and unknown types, "index" is returned.
982 *
983 * @since 2.5.0
984 *
985 * @see https://www.parse.ly/help/integration/metatags#field-description
986 *
987 * @param string $type JSON-LD type.
988 * @return string "post" or "index".
989 */
990 public function convert_jsonld_to_parsely_type( string $type ): string {
991 return in_array( $type, $this->supported_jsonld_post_types ) ? 'post' : 'index';
992 }
993
994 /**
995 * Determine if an API key is saved in the options.
996 *
997 * @since 2.6.0
998 *
999 * @return bool True is API key is set, false if it is missing.
1000 */
1001 public function api_key_is_set(): bool {
1002 $options = $this->get_options();
1003
1004 return (
1005 isset( $options['apikey'] ) &&
1006 is_string( $options['apikey'] ) &&
1007 '' !== $options['apikey']
1008 );
1009 }
1010
1011 /**
1012 * Determine if an API key is not saved in the options.
1013 *
1014 * @since 2.6.0
1015 *
1016 * @return bool True if API key is missing, false if it is set.
1017 */
1018 public function api_key_is_missing(): bool {
1019 return ! $this->api_key_is_set();
1020 }
1021
1022 /**
1023 * Get the API key if set.
1024 *
1025 * @since 2.6.0
1026 *
1027 * @return string API key if set, or empty string if not.
1028 */
1029 public function get_api_key(): string {
1030 $options = $this->get_options();
1031
1032 return $this->api_key_is_set() ? $options['apikey'] : '';
1033 }
1034 }
1035