PluginProbe
Parse.ly / 3.2.0
Parse.ly v3.2.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.2.0, at src/class-parsely.php

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