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

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