PluginProbe
Parse.ly / 3.14.1
Parse.ly v3.14.1
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
← All changes | src/class-parsely.php +565 -810 3.2.03.14.1 View file →
@@ -2,9 +2,9 @@
2 2 /**
3 3 * Parsely class
4 4 *
5 5 * @package Parsely
6 - * @since 2.5.0
6 + * @since 2.5.0
7 7 */
8 8
9 9 declare(strict_types=1);
10 10
@@ -9,10 +9,11 @@
9 9 declare(strict_types=1);
10 10
11 11 namespace Parsely;
12 12
13 +use Parsely\UI\Metadata_Renderer;
14 +use Parsely\UI\Settings_Page;
13 15 use WP_Post;
14 -use WP_User;
15 16
16 17 /**
17 18 * Holds most of the logic for the plugin.
18 19 *
@@ -17,52 +18,91 @@
17 18 * Holds most of the logic for the plugin.
18 19 *
19 20 * @since 1.0.0
20 21 * @since 2.5.0 Moved from plugin root file to this file.
22 + *
23 + * @phpstan-type Parsely_Options array{
24 + * apikey: string,
25 + * content_id_prefix: string,
26 + * api_secret: string,
27 + * use_top_level_cats: bool,
28 + * custom_taxonomy_section: string,
29 + * cats_as_tags: bool,
30 + * track_authenticated_users: bool,
31 + * lowercase_tags: bool,
32 + * force_https_canonicals: bool,
33 + * track_post_types: string[],
34 + * track_page_types: string[],
35 + * track_post_types_as?: array<string, string>,
36 + * full_metadata_in_non_posts: ?bool,
37 + * disable_javascript: bool,
38 + * disable_amp: bool,
39 + * meta_type: string,
40 + * logo: string,
41 + * metadata_secret: string,
42 + * disable_autotrack: bool,
43 + * plugin_version: string,
44 + * }
45 + *
46 + * @phpstan-type WP_HTTP_Request_Args array{
47 + * method: string,
48 + * timeout: float,
49 + * blocking: bool,
50 + * headers: array<string, string>,
51 + * body: string,
52 + * data_format: string,
53 + * }
54 + *
55 + * @phpstan-import-type Metadata_Attributes from Metadata
21 56 */
22 57 class Parsely {
23 58 /**
24 59 * Declare our constants
25 60 */
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.
61 + public const VERSION = PARSELY_VERSION;
62 + public const MENU_SLUG = 'parsely'; // The page param passed to options-general.php.
63 + public const OPTIONS_KEY = 'parsely'; // The key used to store options in the WP database.
64 + public const CAPABILITY = 'manage_options'; // The capability required to administer settings.
65 + public const DASHBOARD_BASE_URL = 'https://dash.parsely.com';
66 + public const PUBLIC_API_BASE_URL = 'https://api.parsely.com/v2';
67 + public const PUBLIC_SUGGESTIONS_API_BASE_URL = 'https://content-suggestions-api.parsely.net/prod';
30 68
31 69 /**
32 70 * Declare some class properties
33 71 *
34 - * @var array<string, mixed> $option_defaults The defaults we need for the class.
72 + * @var Parsely_Options $option_defaults The defaults we need for the class.
35 73 */
36 74 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,
75 + 'apikey' => '',
76 + 'content_id_prefix' => '',
77 + 'api_secret' => '',
78 + 'use_top_level_cats' => false,
79 + 'custom_taxonomy_section' => 'category',
80 + 'cats_as_tags' => false,
81 + 'track_authenticated_users' => false,
82 + 'lowercase_tags' => true,
83 + 'force_https_canonicals' => false,
84 + 'track_post_types' => array(),
85 + 'track_page_types' => array(),
86 + 'full_metadata_in_non_posts' => true,
87 + 'disable_javascript' => false,
88 + 'disable_amp' => false,
89 + 'meta_type' => 'json_ld',
90 + 'logo' => '',
91 + 'metadata_secret' => '',
92 + 'disable_autotrack' => false,
93 + 'plugin_version' => self::VERSION,
54 94 );
55 95
56 96 /**
57 97 * Declare post types that Parse.ly will process as "posts".
58 98 *
59 - * @link https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages
60 - *
61 99 * @since 2.5.0
62 100 * @var string[]
101 + *
102 + * @link https://docs.parse.ly/metadata-jsonld/#distinguishing-between-posts-and-non-posts-pages
63 103 */
64 - private $supported_jsonld_post_types = array(
104 + public const SUPPORTED_JSONLD_POST_TYPES = array(
65 105 'NewsArticle',
66 106 'Article',
67 107 'TechArticle',
68 108 'BlogPosting',
@@ -69,19 +109,28 @@
69 109 'LiveBlogPosting',
70 110 'Report',
71 111 'Review',
72 112 'CreativeWork',
113 + 'OpinionNewsArticle',
114 + 'AnalysisNewsArticle',
115 + 'BackgroundNewsArticle',
116 + 'ReviewNewsArticle',
117 + 'ReportageNewsArticle',
118 + 'Recipe',
119 + 'AdvertiserContentArticle',
120 + 'MedicalWebPage',
121 + 'PodcastEpisode',
73 122 );
74 123
75 124 /**
76 125 * Declare post types that Parse.ly will process as "non-posts".
77 126 *
78 - * @link https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages
79 - *
80 127 * @since 2.5.0
81 128 * @var string[]
129 + *
130 + * @link https://docs.parse.ly/metadata-jsonld/#distinguishing-between-posts-and-non-posts-pages
82 131 */
83 - private $supported_jsonld_non_post_types = array(
132 + public const SUPPORTED_JSONLD_NON_POST_TYPES = array(
84 133 'WebPage',
85 134 'Event',
86 135 'Hotel',
87 136 'Restaurant',
@@ -88,58 +137,89 @@
88 137 'Movie',
89 138 );
90 139
91 140 /**
92 - * Register action and filter hook callbacks.
141 + * Declare all supported types (both post and non-post types).
93 142 *
94 - * Also, immediately upgrade options if needed.
143 + * @since 3.7.0
144 + * @var string[]
145 + */
146 + private static $all_supported_types;
147 +
148 + /**
149 + * Returns whether credentials are being managed at the platform level.
95 150 *
96 - * @return void
151 + * This allows hosting providers to provide a more customized experience for
152 + * the plugin by handling credentials automatically.
153 + *
154 + * @since 3.9.0
155 + * @access private
156 + * @var bool
97 157 */
158 + public $are_credentials_managed;
159 +
160 + /**
161 + * Holds the managed options and their values.
162 + *
163 + * This allows hosting providers to provide a more customized experience for
164 + * the plugin by handling options automatically.
165 + *
166 + * @since 3.9.0
167 + * @access private
168 + * @var array<empty>|array<string, bool|string|null>
169 + */
170 + public $managed_options = array();
171 +
172 + /**
173 + * Constructor.
174 + */
175 + public function __construct() {
176 + self::$all_supported_types = array_merge( self::SUPPORTED_JSONLD_POST_TYPES, self::SUPPORTED_JSONLD_NON_POST_TYPES );
177 +
178 + $this->are_credentials_managed = $this->are_credentials_managed();
179 + $this->set_managed_options();
180 +
181 + $this->allow_parsely_remote_requests();
182 + }
183 +
184 + /**
185 + * Registers action and filter hook callbacks, and immediately upgrades
186 + * options if needed.
187 + */
98 188 public function run(): void {
99 189 // Run upgrade options if they exist for the version currently defined.
100 190 $options = $this->get_options();
101 - if ( empty( $options['plugin_version'] ) || self::VERSION !== $options['plugin_version'] ) {
191 + if ( self::VERSION !== $options['plugin_version'] ) {
102 192 $method = 'upgrade_plugin_to_version_' . str_replace( '.', '_', self::VERSION );
103 193 if ( method_exists( $this, $method ) ) {
104 - call_user_func_array( array( $this, $method ), array( $options ) );
194 + /**
195 + * Variable.
196 + *
197 + * @var callable
198 + */
199 + $callable = array( $this, $method );
200 + call_user_func_array( $callable, array( $options ) );
105 201 }
202 +
106 203 // Update our version info.
107 204 $options['plugin_version'] = self::VERSION;
108 205 update_option( self::OPTIONS_KEY, $options );
109 206 }
110 207
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 208 add_action( 'save_post', array( $this, 'update_metadata_endpoint' ) );
115 - add_action( 'wp_head', array( $this, 'insert_page_header_metadata' ) );
116 209 }
117 210
118 211 /**
119 - * Adds 10 minute cron interval.
212 + * Gets the full URL of the JavaScript tracker file for the site. If an API
213 + * key is not set, return an empty string.
120 214 *
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 215 * @since 3.2.0
136 216 *
137 217 * @return string
138 218 */
139 219 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';
220 + if ( $this->site_id_is_set() ) {
221 + $tracker_url = 'https://cdn.parsely.com/keys/' . $this->get_site_id() . '/p.js';
142 222 return esc_url( $tracker_url );
143 223 }
144 224 return '';
145 225 }
@@ -144,155 +224,50 @@
144 224 return '';
145 225 }
146 226
147 227 /**
148 - * Insert the code for the <meta name='parsely-page'> parameter within the <head></head> tag.
228 + * Deprecated.
229 + * Inserts the code for the <meta name='parsely-page'> parameter within the
230 + * head tag.
149 231 *
150 232 * @since 3.2.0
233 + * @deprecated 3.3.0
234 + * @see Metadata_Renderer::render_metadata
151 235 *
152 236 * @param string $meta_type `json_ld` or `repeated_metas`.
153 - * @return void
154 237 */
155 238 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 - }
239 + _deprecated_function( __FUNCTION__, '3.3', 'Metadata_Renderer::render_metadata()' );
240 + $metadata_renderer = new Metadata_Renderer( $this );
241 + $metadata_renderer->render_metadata( $meta_type );
237 242 }
238 243
239 244 /**
240 - * Insert the code for the <meta name='parsely-page'> parameter within the <head></head> tag.
245 + * Deprecated.
246 + * Insert the code for the <meta name='parsely-page'> parameter within the
247 + * head tag.
241 248 *
242 249 * @since 3.0.0
243 - *
244 - * @return void
250 + * @deprecated 3.3.0
251 + * @see Metadata_Renderer::render_metadata
245 252 */
246 253 public function insert_page_header_metadata(): void {
247 - $parsely_options = $this->get_options();
248 - $this->render_metadata( $parsely_options['meta_type'] );
254 + _deprecated_function( __FUNCTION__, '3.3', 'Metadata_Renderer::render_metadata()' );
255 + $parsely_options = $this->get_options();
256 + $metadata_renderer = new Metadata_Renderer( $this );
257 + $metadata_renderer->render_metadata( $parsely_options['meta_type'] );
249 258 }
250 259
251 260 /**
252 - * Deprecated. Echo the metadata into the page, and return the inserted values.
261 + * Compares the post_status key against an allowed list.
253 262 *
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.
263 + * By default, only 'publish'ed content includes tracking data.
256 264 *
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 265 * @since 2.5.0
292 266 *
293 267 * @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.
268 + * @return bool Should the post status be tracked for the provided post's post_type.
269 + * By default,only 'publish' is allowed.
295 270 */
296 271 public static function post_has_trackable_status( $post ): bool {
297 272 static $cache = array();
298 273 $post_id = is_int( $post ) ? $post : $post->ID;
@@ -300,9 +275,10 @@
300 275 return $cache[ $post_id ];
301 276 }
302 277
303 278 /**
304 - * Filters whether the post password check should be skipped when getting the post trackable status.
279 + * Filters whether the post password check should be skipped when getting
280 + * the post trackable status.
305 281 *
306 282 * @since 3.0.1
307 283 *
308 284 * @param bool $skip True if the password check should be skipped.
@@ -307,9 +283,9 @@
307 283 *
308 284 * @param bool $skip True if the password check should be skipped.
309 285 * @param int|WP_Post $post Which post object or ID is being checked.
310 286 *
311 - * @returns bool
287 + * @return bool
312 288 */
313 289 $skip_password_check = apply_filters( 'wp_parsely_skip_post_password_check', false, $post );
314 290 if ( ! $skip_password_check && post_password_required( $post ) ) {
315 291 $cache[ $post_id ] = false;
@@ -318,9 +294,10 @@
318 294
319 295 /**
320 296 * Filters the statuses that are permitted to be tracked.
321 297 *
322 - * By default, the only status tracked is 'publish'. Use this filter if you have other published content that has a different (custom) status.
298 + * By default, the only status tracked is 'publish'. Use this filter if
299 + * you have other published content that has a different (custom) status.
323 300 *
324 301 * @since 2.5.0
325 302 *
326 303 * @param string[] $trackable_statuses The list of post statuses that are allowed to be tracked.
@@ -331,268 +308,81 @@
331 308 return $cache[ $post_id ];
332 309 }
333 310
334 311 /**
312 + * Deprecated. Please use the `Metadata` class instead.
313 + *
335 314 * Creates parsely metadata object from post metadata.
336 315 *
316 + * @deprecated 3.3.0
317 + * @see \Parsely\Metadata::construct_metadata
318 + *
337 319 * @param array<string, mixed> $parsely_options parsely_options array.
338 320 * @param WP_Post $post object.
339 - * @return array<string, mixed>
321 + * @return Metadata_Attributes
340 322 */
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();
323 + public function construct_parsely_metadata( array $parsely_options, WP_Post $post ) {
324 + _deprecated_function( __FUNCTION__, '3.3', 'Metadata::construct_metadata()' );
325 + $metadata = new Metadata( $this );
326 + return $metadata->construct_metadata( $post );
515 327 }
516 328
517 329 /**
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 330 * Updates the Parsely metadata endpoint with the new metadata of the post.
547 331 *
548 332 * @param int $post_id id of the post to update.
549 - * @return void
550 333 */
551 334 public function update_metadata_endpoint( int $post_id ): void {
552 335 $parsely_options = $this->get_options();
336 + if ( $this->site_id_is_missing() || '' === $parsely_options['metadata_secret'] ) {
337 + return;
338 + }
553 339
554 - if ( $this->api_key_is_missing() || empty( $parsely_options['metadata_secret'] ) ) {
340 + $post = get_post( $post_id );
341 + if ( null === $post ) {
555 342 return;
556 343 }
557 344
558 - $post = get_post( $post_id );
559 - $metadata = $this->construct_parsely_metadata( $parsely_options, $post );
345 + $metadata = ( new Metadata( $this ) )->construct_metadata( $post );
560 346
561 347 $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'],
348 + 'canonical_url' => $metadata['url'] ?? '',
349 + 'page_type' => $this->convert_jsonld_to_parsely_type( $metadata['@type'] ?? '' ),
350 + 'title' => $metadata['headline'] ?? '',
351 + 'image_url' => $metadata['image']['url'] ?? '',
352 + 'pub_date_tmsp' => $metadata['datePublished'] ?? '',
353 + 'section' => $metadata['articleSection'] ?? '',
354 + 'authors' => $metadata['creator'] ?? '',
355 + 'tags' => $metadata['keywords'] ?? '',
570 356 );
571 357
572 - $parsely_api_endpoint = 'https://api.parsely.com/v2/metadata/posts';
358 + $parsely_api_endpoint = self::PUBLIC_API_BASE_URL . '/metadata/posts';
573 359 $parsely_metadata_secret = $parsely_options['metadata_secret'];
574 - $headers = array(
575 - 'Content-Type' => 'application/json',
576 - );
577 - $body = wp_json_encode(
360 +
361 + $headers = array( 'Content-Type' => 'application/json' );
362 + $body = wp_json_encode(
578 363 array(
579 364 'secret' => $parsely_metadata_secret,
580 - 'apikey' => $parsely_options['apikey'],
365 + 'apikey' => $this->get_site_id(),
581 366 'metadata' => $endpoint_metadata,
582 367 )
583 368 );
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 - )
369 +
370 + /**
371 + * POST request options.
372 + *
373 + * @var WP_HTTP_Request_Args $options
374 + */
375 + $options = array(
376 + 'method' => 'POST',
377 + 'headers' => $headers,
378 + 'blocking' => false,
379 + 'body' => $body,
380 + 'data_format' => 'body',
593 381 );
594 382
383 + $response = wp_remote_post( $parsely_api_endpoint, $options );
384 +
595 385 if ( ! is_wp_error( $response ) ) {
596 386 $current_timestamp = time();
597 387 update_post_meta( $post_id, 'parsely_metadata_last_updated', $current_timestamp );
598 388 }
@@ -598,532 +388,497 @@
598 388 }
599 389 }
600 390
601 391 /**
602 - * Updates posts with Parsely metadata api in bulk.
392 + * Safely returns options for the plugin by assigning defaults contained in
393 + * optionDefaults.
603 394 *
604 - * @return void
395 + * As soon as actual options are saved, they override the defaults. This
396 + * prevents us from having to do a lot of isset() checking on variables.
397 + *
398 + * @return Parsely_Options
605 399 */
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 );
400 + public function get_options() {
401 + /**
402 + * Variable.
403 + *
404 + * @var Parsely_Options|null
405 + */
406 + $options = get_option( self::OPTIONS_KEY, null );
407 +
408 + if ( is_array( $options ) && ! isset( $options['full_metadata_in_non_posts'] ) ) {
409 + $this->set_default_full_metadata_in_non_posts();
631 410 }
632 411
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 );
412 + if ( ! is_array( $options ) ) {
413 + $this->set_default_track_as_values();
414 + $this->set_default_full_metadata_in_non_posts();
415 + $options = $this->option_defaults;
640 416 }
417 +
418 + /**
419 + * Final options including managed credentials and options.
420 + *
421 + * @var Parsely_Options
422 + */
423 + return array_merge(
424 + $this->option_defaults,
425 + $options,
426 + $this->get_managed_credentials(),
427 + $this->managed_options
428 + );
641 429 }
642 430
643 431 /**
644 - * Get the cache buster value for script and styles.
432 + * Sets the default values for the track_post_types and track_page_types
433 + * options.
645 434 *
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.
435 + * @since 3.9.0
653 436 */
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 - }
437 + public function set_default_track_as_values(): void {
438 + $this->option_defaults['track_page_types'] = array();
439 + $this->option_defaults['track_post_types'] = array();
660 440
661 - $cache_buster = defined( 'WP_DEBUG' ) && WP_DEBUG && empty( 'WP_TESTS_DOMAIN' ) ? wp_rand() : PARSELY_VERSION;
441 + $post_types = get_post_types( array( 'public' => true ) );
662 442
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' );
443 + foreach ( $post_types as $post_type ) {
444 + if ( ! post_type_supports( $post_type, 'editor' ) ) {
445 + continue;
446 + }
671 447
672 - return $cache_buster;
448 + if ( is_post_type_hierarchical( $post_type ) ) {
449 + $this->option_defaults['track_page_types'][] = $post_type;
450 + } else {
451 + $this->option_defaults['track_post_types'][] = $post_type;
452 + }
453 + }
673 454 }
674 455
675 456 /**
676 - * Returns the tags associated with this page or post
457 + * Sets the default value for the full_metadata_in_non_posts option.
677 458 *
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.
459 + * @since 3.14.0
680 460 */
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;
461 + public function set_default_full_metadata_in_non_posts(): void {
462 + $this->option_defaults['full_metadata_in_non_posts'] = true;
463 +
464 + // Usage of any of these filters will result in the setting being set
465 + // to false.
466 + $filter_tags = array(
467 + 'wp_parsely_metadata',
468 + 'wp_parsely_post_tags',
469 + 'wp_parsely_permalink',
470 + 'wp_parsely_post_category',
471 + 'wp_parsely_pre_authors',
472 + 'wp_parsely_post_authors',
473 + 'wp_parsely_custom_taxonomies',
474 + 'wp_parsely_post_type',
475 + );
476 +
477 + foreach ( $filter_tags as $filter_tag ) {
478 + if ( has_filter( $filter_tag ) ) {
479 + $this->option_defaults['full_metadata_in_non_posts'] = false;
480 + break;
687 481 }
688 482 }
689 - return $tags;
690 483 }
691 484
692 485 /**
693 - * Returns an array of all the child categories for the current post
486 + * Gets the URL of the plugin's settings page.
694 487 *
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.
488 + * @param int|null $_blog_id The Blog ID for the multisite subsite to use
489 + * for context (Default null for current).
490 + * @return string
698 491 */
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 ) );
492 + public static function get_settings_url( int $_blog_id = null ): string {
493 + return get_admin_url( $_blog_id, 'options-general.php?page=' . self::MENU_SLUG );
717 494 }
718 495
719 496 /**
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.
497 + * Returns the URL of the Parse.ly dashboard for a specific page. If a page
498 + * is not specified, the home dashboard URL for the specified Site ID is
499 + * returned.
723 500 *
724 - * @return array
501 + * @since 3.7.0
502 + *
503 + * @param string $site_id The Site ID for which to get the URL.
504 + * @param string $page_url Optional. The page for which to get the URL.
505 + * @return string The complete dashboard URL.
725 506 */
726 - public function get_options(): array {
727 - $options = get_option( self::OPTIONS_KEY, $this->option_defaults );
507 + public static function get_dash_url( string $site_id, string $page_url = '' ): string {
508 + $result = trailingslashit( self::DASHBOARD_BASE_URL . '/' . $site_id ) . 'find';
728 509
729 - if ( ! is_array( $options ) ) {
730 - return $this->option_defaults;
510 + if ( '' !== $page_url ) {
511 + $page_url = self::get_url_with_itm_source( $page_url, null );
512 + $result .= '?url=' . rawurlencode( $page_url );
731 513 }
732 514
733 - return array_merge( $this->option_defaults, $options );
515 + return $result;
734 516 }
735 517
736 518 /**
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.
519 + * Adds or replaces the itm_source parameter in the URL. Removes the
520 + * parameter if the passed value is null or an empty string.
739 521 *
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.
522 + * @since 3.9.0
523 + *
524 + * @param string $url The URL to modify.
525 + * @param string|null $itm_source The value of the itm_source parameter.
526 + * @return string The resulting URL.
743 527 */
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 - }
528 + public static function get_url_with_itm_source( string $url, $itm_source ): string {
529 + if ( null === $itm_source || '' === $itm_source ) {
530 + return remove_query_arg( 'itm_source', $url );
761 531 }
762 532
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 );
533 + $itm_source = rawurlencode( $itm_source );
773 534
774 - return $this->get_clean_parsely_page_value( $category_name );
535 + return add_query_arg( 'itm_source', $itm_source, $url );
775 536 }
776 537
777 538 /**
778 - * Return the top-most category/taxonomy value in a hierarcy given a taxonomy value's ID
779 - * ( WordPress calls taxonomy values 'terms' ).
539 + * Checks to see if the current user is a member of the current blog.
780 540 *
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.
541 + * @return bool
784 542 */
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;
543 + public function is_blog_member_logged_in(): bool {
544 + // Can't use $blog_id here because it futzes with the global $blog_id.
545 + $current_blog_id = get_current_blog_id();
546 + $current_user_id = get_current_user_id();
547 +
548 + return is_user_member_of_blog( $current_user_id, $current_blog_id );
791 549 }
792 550
793 551 /**
794 - * Return the bottom-most category/taxonomy value in a hierarcy given a post ID
795 - * ( WordPress calls taxonomy values 'terms' ).
552 + * Converts JSON-LD type to respective Parse.ly page type.
796 553 *
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.
554 + * If the JSON-LD type is one of the types Parse.ly supports as a "post",
555 + * then "post" will be returned. Otherwise, for "non-posts" and unknown
556 + * types, "index" is returned.
557 + *
558 + * @since 2.5.0
559 + *
560 + * @see https://docs.parse.ly/metatags/#h-field-description
561 + *
562 + * @param string $type JSON-LD type.
563 + * @return string "post" or "index".
800 564 */
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 '';
565 + public function convert_jsonld_to_parsely_type( string $type ): string {
566 + return in_array( $type, self::SUPPORTED_JSONLD_POST_TYPES, true ) ? 'post' : 'index';
827 567 }
828 568
829 569 /**
830 - * Get all term values from custom taxonomies.
570 + * Determines if a Site ID is saved in the options.
831 571 *
832 - * @param WP_Post $post_obj The post object.
833 - * @return array<string>
572 + * @since 2.6.0
573 + * @since 3.7.0 renamed from api_key_is_set.
574 + *
575 + * @return bool True is Site ID is set, false if it is missing.
834 576 */
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();
577 + public function site_id_is_set(): bool {
578 + $options = $this->get_options();
839 579
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;
580 + return '' !== $options['apikey'];
850 581 }
851 582
852 583 /**
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
584 + * Determines if a Site ID is not saved in the options.
856 585 *
857 - * @param int $post_id The id of the post.
858 - * @return array<WP_User>
586 + * @since 2.6.0
587 + * @since 3.7.0 renamed from api_key_is_missing.
588 + *
589 + * @return bool True if Site ID is missing, false if it is set.
859 590 */
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;
591 + public function site_id_is_missing(): bool {
592 + return ! $this->site_id_is_set();
896 593 }
897 594
898 595 /**
899 - * Determine author name from display name, falling back to firstname
900 - * lastname, then nickname and finally the nicename.
596 + * Gets the Site ID if set.
901 597 *
902 - * @param ?WP_User $author The author of the post.
903 - * @return string
598 + * @since 2.6.0
599 + * @since 3.7.0 renamed from get_site_id.
600 + *
601 + * @return string Site ID if set, or empty string if not.
904 602 */
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 - }
603 + public function get_site_id(): string {
604 + $options = $this->get_options();
910 605
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 '';
606 + return $this->site_id_is_set() ? $options['apikey'] : '';
929 607 }
930 608
931 609 /**
932 - * Retrieve all the authors for a post as an array. Can include multiple
933 - * authors if coauthors plugin is in use.
610 + * Returns whether the API Secret is set in the plugin's options.
934 611 *
935 - * @param WP_Post $post The post object.
936 - * @return array<string>
612 + * @since 3.4.0
613 + *
614 + * @return bool True if the API Secret is set, false if not set.
937 615 */
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 - }
616 + public function api_secret_is_set(): bool {
617 + $options = $this->get_options();
946 618
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 );
619 + return '' !== $options['api_secret'];
971 620 }
972 621
973 622 /**
974 - * Sanitize content
623 + * Returns the API Secret stored in the plugin's options.
975 624 *
976 - * @since 2.6.0
625 + * @since 3.4.0
977 626 *
978 - * @param string|null $val The content you'd like sanitized.
979 - * @return string
627 + * @return string The API Secret, empty string if the API secret is not set.
980 628 */
981 - public function get_clean_parsely_page_value( ?string $val ): string {
982 - if ( null === $val ) {
983 - return '';
984 - }
629 + public function get_api_secret(): string {
630 + $options = $this->get_options();
985 631
986 - $val = str_replace( "\n", '', $val );
987 - $val = str_replace( "\r", '', $val );
988 - $val = wp_strip_all_tags( $val );
989 - return trim( $val );
632 + return $this->api_secret_is_set() ? $options['api_secret'] : '';
990 633 }
991 634
992 635 /**
993 - * Get the URL of the plugin settings page.
636 + * Returns all supported post and non-post types.
994 637 *
995 - * @param int $_blog_id The Blog ID for the multisite subsite to use for context (Default null for current).
638 + * @since 3.7.0
996 639 *
997 - * @return string
640 + * @return string[] all supported types
998 641 */
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 );
642 + public function get_all_supported_types(): array {
643 + return self::$all_supported_types;
1001 644 }
1002 645
1003 646 /**
1004 - * Get the URL of the current PHP script.
1005 - * A fall-back implementation to determine permalink
647 + * Gets all tracked post types.
1006 648 *
1007 - * @since 3.0.0 $parsely_type Default parameter changed to `non-post`.
649 + * @since 3.7.0
1008 650 *
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
651 + * @return array<string>
1012 652 */
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 );
653 + public function get_all_track_types(): array {
654 + $options = $this->get_options();
1016 655
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 );
656 + return array_unique( array_merge( $options['track_post_types'], $options['track_page_types'] ) );
1041 657 }
1042 658
1043 659 /**
1044 - * Get the first image from a post
1045 - * https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
660 + * Gets default options.
1046 661 *
1047 - * @param WP_Post $post The post object you're interested in.
1048 - * @return string
662 + * @since 3.8.0
663 + *
664 + * @return Parsely_Options
1049 665 */
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 '';
666 + public function get_default_options() {
667 + return $this->option_defaults;
1057 668 }
1058 669
1059 670 /**
1060 - * Check to see if parsely user is logged in.
671 + * Returns the credentials that are being managed at the platform level.
1061 672 *
1062 - * @return bool
673 + * @since 3.9.0
674 + * @access private
675 + *
676 + * @return Parsely_Options|array<empty> The managed credentials.
1063 677 */
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 );
678 + private function get_managed_credentials() {
679 + if ( true !== $this->are_credentials_managed ) {
680 + return array();
681 + }
682 +
683 + $credentials = apply_filters( 'wp_parsely_credentials', array() );
684 +
685 + if ( ! is_array( $credentials ) || 0 === count( $credentials ) ) {
686 + return array();
687 + }
688 +
689 + $result = array();
690 +
691 + if ( isset( $credentials['site_id'] ) ) {
692 + $result['apikey'] = $credentials['site_id'];
693 + }
694 +
695 + if ( isset( $credentials['api_secret'] ) ) {
696 + $result['api_secret'] = $credentials['api_secret'];
697 + }
698 +
699 + if ( isset( $credentials['metadata_secret'] ) ) {
700 + $result['metadata_secret'] = $credentials['metadata_secret'];
701 + }
702 +
703 + return $result;
1069 704 }
1070 705
1071 706 /**
1072 - * Convert JSON-LD type to respective Parse.ly page type.
707 + * Returns whether credentials are being managed at the platform level.
1073 708 *
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.
709 + * @since 3.9.0
710 + * @access private
1076 711 *
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".
712 + * @return bool Whether credentials are being managed at the platform level.
1084 713 */
1085 - private function convert_jsonld_to_parsely_type( string $type ): string {
1086 - return in_array( $type, $this->supported_jsonld_post_types, true ) ? 'post' : 'index';
714 + private function are_credentials_managed(): bool {
715 + $credentials = apply_filters( 'wp_parsely_credentials', array() );
716 +
717 + if ( ! is_array( $credentials ) || 0 === count( $credentials ) ) {
718 + return false;
719 + }
720 +
721 + return $credentials['is_managed'] ?? false;
1087 722 }
1088 723
1089 724 /**
1090 - * Determine if an API key is saved in the options.
725 + * Sets the values of managed options.
1091 726 *
1092 - * @since 2.6.0
727 + * This function won't accept managing credentials or certain plugin options
728 + * that are being managed through other means. For managing credentials,
729 + * please use the `wp_parsely_credentials` filter.
1093 730 *
1094 - * @return bool True is API key is set, false if it is missing.
731 + * @since 3.9.0
732 + * @access private
1095 733 */
1096 - public function api_key_is_set(): bool {
1097 - $options = $this->get_options();
734 + private function set_managed_options(): void {
735 + $managed_options = apply_filters( 'wp_parsely_managed_options', false );
1098 736
1099 - return (
1100 - isset( $options['apikey'] ) &&
1101 - is_string( $options['apikey'] ) &&
1102 - '' !== $options['apikey']
737 + if ( ! is_array( $managed_options ) ) {
738 + return;
739 + }
740 +
741 + // Don't allow certain options to be set as managed.
742 + unset(
743 + $managed_options['apikey'],
744 + $managed_options['api_secret'],
745 + $managed_options['metadata_secret'],
746 + $managed_options['track_post_types'],
747 + $managed_options['track_page_types'],
748 + $managed_options['plugin_version']
1103 749 );
750 +
751 + if ( 0 === count( $managed_options ) ) {
752 + return;
753 + }
754 +
755 + /**
756 + * Current options.
757 + *
758 + * @var Parsely_Options $current_options
759 + */
760 + $current_options = get_option( self::OPTIONS_KEY, array() );
761 +
762 + // Set managed options values.
763 + foreach ( $managed_options as $key => $value ) {
764 + $is_option_valid = isset( $this->option_defaults[ $key ] );
765 +
766 + if ( $is_option_valid ) {
767 + if ( null === $value ) {
768 + // When null, the option gets its value from the database.
769 + $this->managed_options[ $key ] =
770 + $current_options[ $key ] ?? $this->option_defaults[ $key ];
771 + } else {
772 + $this->managed_options[ $key ] =
773 + $this->sanitize_managed_option( $key, $value );
774 + }
775 + }
776 + }
1104 777 }
1105 778
1106 779 /**
1107 - * Determine if an API key is not saved in the options.
780 + * Sanitizes the value of the passed managed option.
1108 781 *
1109 - * @since 2.6.0
782 + * @since 3.9.0
783 + * @access private
1110 784 *
1111 - * @return bool True if API key is missing, false if it is set.
785 + * @param string $option_id The option's ID.
786 + * @param bool|string $value The option's value.
787 + * @return bool|string The sanitized option value.
1112 788 */
1113 - public function api_key_is_missing(): bool {
1114 - return ! $this->api_key_is_set();
789 + private function sanitize_managed_option( string $option_id, $value ) {
790 + $option_value_type = gettype( $this->option_defaults[ $option_id ] );
791 +
792 + if ( 'boolean' === $option_value_type && ! is_bool( $value ) ) {
793 + _doing_it_wrong(
794 + __FUNCTION__,
795 + esc_html(
796 + sprintf( /* translators: 1: Option ID */
797 + __( 'The value of the managed option `%1$s` must be of type `boolean`.', 'wp-parsely' ),
798 + $option_id
799 + )
800 + ),
801 + ''
802 + );
803 +
804 + return false;
805 + }
806 +
807 + if ( 'string' === $option_value_type ) {
808 + if ( ! is_string( $value ) ) {
809 + _doing_it_wrong(
810 + __FUNCTION__,
811 + esc_html(
812 + sprintf( /* translators: 1: Option ID */
813 + __( 'The value of the managed option `%1$s` must be of type `string`.', 'wp-parsely' ),
814 + $option_id
815 + )
816 + ),
817 + ''
818 + );
819 +
820 + $value = strval( $value );
821 + }
822 +
823 + // String options that are restricted to specific values.
824 + $restricted_value_options = array(
825 + 'custom_taxonomy_section' => Settings_Page::get_section_taxonomies(),
826 + 'meta_type' => array( 'json_ld', 'repeated_metas' ),
827 + );
828 +
829 + // Verify that the above values are respected.
830 + foreach ( $restricted_value_options as $option_key => $valid_values ) {
831 + if ( $option_id === $option_key ) {
832 + if ( ! in_array( $value, $valid_values, true ) ) {
833 + _doing_it_wrong(
834 + __FUNCTION__,
835 + esc_html(
836 + sprintf( /* translators: 1: Option value 2: Option ID */
837 + __( 'The value `%1$s` is not allowed for the managed option `%2$s`.', 'wp-parsely' ),
838 + $value,
839 + $option_id
840 + )
841 + ),
842 + ''
843 + );
844 +
845 + $value = $this->option_defaults[ $option_id ];
846 + }
847 + }
848 + }
849 + }
850 +
851 + return $value;
1115 852 }
1116 853
1117 854 /**
1118 - * Get the API key if set.
855 + * Allows remote requests to Parse.ly.
1119 856 *
1120 - * @since 2.6.0
857 + * This is needed for environments, such as wp-now, that block remote requests.
1121 858 *
1122 - * @return string API key if set, or empty string if not.
859 + * @since 3.13.0
860 + * @access private
1123 861 */
1124 - public function get_api_key(): string {
1125 - $options = $this->get_options();
862 + private function allow_parsely_remote_requests(): void {
863 + $allowed_urls = array(
864 + self::DASHBOARD_BASE_URL,
865 + self::PUBLIC_API_BASE_URL,
866 + self::PUBLIC_SUGGESTIONS_API_BASE_URL,
867 + );
1126 868
1127 - return $this->api_key_is_set() ? $options['apikey'] : '';
869 + add_filter(
870 + 'http_request_host_is_external',
871 + function ( $external, $host, $url ) use ( $allowed_urls ) {
872 + // Check if the URL matches any URLs on the allowed list.
873 + foreach ( $allowed_urls as $allowed_url ) {
874 + if ( \Parsely\Utils\str_starts_with( $url, $allowed_url ) ) {
875 + return true;
876 + }
877 + }
878 + return $external;
879 + },
880 + 10,
881 + 3
882 + );
1128 883 }
1129 884 }