PluginProbe
Parse.ly / 3.24.2
Parse.ly v3.24.2
3.24.2 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 All 106 releases
← All changes | src/class-parsely.php +911 -804 3.2.0 → 3.24.2 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,15 @@
9 9 declare(strict_types=1);
10 10
11 11 namespace Parsely;
12 12
13 +use Parsely\Content_Helper\Suggestion_Defaults;
14 +use Parsely\REST_API\REST_API_Controller;
15 +use Parsely\Services\Content_API\Content_API_Service;
16 +use Parsely\Services\Suggestions_API\Suggestions_API_Service;
17 +use Parsely\UI\Metadata_Renderer;
18 +use Parsely\UI\Settings_Page;
13 19 use WP_Post;
14 -use WP_User;
15 20
16 21 /**
17 22 * Holds most of the logic for the plugin.
18 23 *
@@ -17,52 +22,171 @@
17 22 * Holds most of the logic for the plugin.
18 23 *
19 24 * @since 1.0.0
20 25 * @since 2.5.0 Moved from plugin root file to this file.
26 + *
27 + * @phpstan-type Parsely_Options array{
28 + * apikey: string,
29 + * content_id_prefix: string,
30 + * api_secret: string,
31 + * use_top_level_cats: bool,
32 + * custom_taxonomy_section: string,
33 + * cats_as_tags: bool,
34 + * content_helper: Parsely_Options_Content_Helper,
35 + * headline_testing: Parsely_Options_Headline_Testing,
36 + * track_authenticated_users: bool,
37 + * lowercase_tags: bool,
38 + * force_https_canonicals: bool,
39 + * track_post_types: string[],
40 + * track_page_types: string[],
41 + * track_post_types_as?: array<string, string>,
42 + * full_metadata_in_non_posts: bool,
43 + * disable_javascript: bool,
44 + * disable_amp: bool,
45 + * meta_type: string,
46 + * logo: string,
47 + * metadata_secret: string,
48 + * disable_autotrack: bool,
49 + * plugin_version: string,
50 + * }
51 + *
52 + * @phpstan-type Parsely_Options_Content_Helper array{
53 + * ai_features_enabled: bool,
54 + * smart_linking: Parsely_Options_Content_Helper_Feature,
55 + * title_suggestions: Parsely_Options_Content_Helper_Feature,
56 + * excerpt_suggestions: Parsely_Options_Content_Helper_Feature,
57 + * traffic_boost: Parsely_Options_Content_Helper_Feature,
58 + * }
59 + *
60 + * @phpstan-type Parsely_Options_Content_Helper_Feature array{
61 + * enabled: bool,
62 + * allowed_user_roles: string[],
63 + * default_length?: int,
64 + * default_tone?: string,
65 + * default_persona?: string,
66 + * }
67 + *
68 + * @phpstan-type Parsely_Options_Headline_Testing array{
69 + * enabled: bool,
70 + * installation_method: string,
71 + * enable_flicker_control: bool,
72 + * enable_live_updates: bool,
73 + * live_update_timeout: int,
74 + * allow_after_content_load: bool,
75 + * }
76 + *
77 + * @phpstan-type WP_HTTP_Request_Args array{
78 + * method?: string,
79 + * timeout?: float,
80 + * blocking?: bool,
81 + * headers?: array<string, string>,
82 + * body?: string,
83 + * data_format?: string,
84 + * }
85 + *
86 + * @phpstan-import-type Metadata_Attributes from Metadata
21 87 */
22 88 class Parsely {
23 89 /**
24 90 * Declare our constants
25 91 */
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.
92 + public const VERSION = PARSELY_VERSION;
93 + public const MENU_SLUG = 'parsely-settings'; // The page param passed to admin.php.
94 + public const OPTIONS_KEY = 'parsely'; // The key used to store options in the WP database.
95 + public const CAPABILITY = 'manage_options'; // The capability required to administer settings.
96 + public const DASHBOARD_BASE_URL = 'https://dash.parsely.com';
30 97
98 + private const PARSELY_CANONICAL_URL_META_KEY = '_parsely_canonical_url';
99 +
31 100 /**
101 + * The Content API service.
102 + *
103 + * @var ?Content_API_Service $content_api_service
104 + */
105 + private $content_api_service;
106 +
107 + /**
108 + * The Suggestions API service.
109 + *
110 + * @var ?Suggestions_API_Service $suggestions_api_service
111 + */
112 + private $suggestions_api_service;
113 +
114 + /**
115 + * The Parse.ly internal REST API controller.
116 + *
117 + * @var REST_API_Controller|null $rest_api_controller
118 + */
119 + private $rest_api_controller;
120 +
121 + /**
32 122 * Declare some class properties
33 123 *
34 - * @var array<string, mixed> $option_defaults The defaults we need for the class.
124 + * @var Parsely_Options $option_defaults The defaults we need for the class.
35 125 */
36 126 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,
127 + 'apikey' => '',
128 + 'content_id_prefix' => '',
129 + 'api_secret' => '',
130 + 'use_top_level_cats' => false,
131 + 'custom_taxonomy_section' => 'category',
132 + 'cats_as_tags' => false,
133 + 'content_helper' => array(
134 + 'ai_features_enabled' => true,
135 + 'smart_linking' => array(
136 + 'enabled' => true,
137 + 'allowed_user_roles' => array( 'administrator' ),
138 + ),
139 + 'title_suggestions' => array(
140 + 'enabled' => true,
141 + 'allowed_user_roles' => array( 'administrator' ),
142 + 'default_tone' => Suggestion_Defaults::DEFAULT_TONE,
143 + 'default_persona' => Suggestion_Defaults::DEFAULT_PERSONA,
144 + ),
145 + 'excerpt_suggestions' => array(
146 + 'enabled' => true,
147 + 'allowed_user_roles' => array( 'administrator' ),
148 + 'default_length' => Suggestion_Defaults::DEFAULT_LENGTH,
149 + 'default_tone' => Suggestion_Defaults::DEFAULT_TONE,
150 + 'default_persona' => Suggestion_Defaults::DEFAULT_PERSONA,
151 + ),
152 + 'traffic_boost' => array(
153 + 'enabled' => true,
154 + 'allowed_user_roles' => array( 'administrator' ),
155 + ),
156 + ),
157 + 'headline_testing' => array(
158 + 'enabled' => false,
159 + 'installation_method' => 'one_line',
160 + 'enable_flicker_control' => false,
161 + 'enable_live_updates' => false,
162 + 'live_update_timeout' => 30000,
163 + 'allow_after_content_load' => false,
164 + ),
165 + 'track_authenticated_users' => false,
166 + 'lowercase_tags' => true,
167 + 'force_https_canonicals' => false,
168 + 'track_post_types' => array(),
169 + 'track_page_types' => array(),
170 + 'full_metadata_in_non_posts' => true,
171 + 'disable_javascript' => false,
172 + 'disable_amp' => false,
173 + 'meta_type' => 'json_ld',
174 + 'logo' => '',
175 + 'metadata_secret' => '',
176 + 'disable_autotrack' => false,
177 + 'plugin_version' => self::VERSION,
54 178 );
55 179
56 180 /**
57 181 * Declare post types that Parse.ly will process as "posts".
58 182 *
59 - * @link https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages
60 - *
61 183 * @since 2.5.0
62 184 * @var string[]
185 + *
186 + * @link https://docs.parse.ly/metadata-jsonld/#distinguishing-between-posts-and-non-posts-pages
63 187 */
64 - private $supported_jsonld_post_types = array(
188 + public const SUPPORTED_JSONLD_POST_TYPES = array(
65 189 'NewsArticle',
66 190 'Article',
67 191 'TechArticle',
68 192 'BlogPosting',
@@ -69,19 +193,28 @@
69 193 'LiveBlogPosting',
70 194 'Report',
71 195 'Review',
72 196 'CreativeWork',
197 + 'OpinionNewsArticle',
198 + 'AnalysisNewsArticle',
199 + 'BackgroundNewsArticle',
200 + 'ReviewNewsArticle',
201 + 'ReportageNewsArticle',
202 + 'Recipe',
203 + 'AdvertiserContentArticle',
204 + 'MedicalWebPage',
205 + 'PodcastEpisode',
73 206 );
74 207
75 208 /**
76 209 * Declare post types that Parse.ly will process as "non-posts".
77 210 *
78 - * @link https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages
79 - *
80 211 * @since 2.5.0
81 212 * @var string[]
213 + *
214 + * @link https://docs.parse.ly/metadata-jsonld/#distinguishing-between-posts-and-non-posts-pages
82 215 */
83 - private $supported_jsonld_non_post_types = array(
216 + public const SUPPORTED_JSONLD_NON_POST_TYPES = array(
84 217 'WebPage',
85 218 'Event',
86 219 'Hotel',
87 220 'Restaurant',
@@ -88,221 +221,231 @@
88 221 'Movie',
89 222 );
90 223
91 224 /**
92 - * Register action and filter hook callbacks.
225 + * Declare all supported types (both post and non-post types).
93 226 *
94 - * Also, immediately upgrade options if needed.
95 - *
96 - * @return void
227 + * @since 3.7.0
228 + * @var string[]
97 229 */
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 - }
230 + private static $all_supported_types;
110 231
111 - // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval
112 - add_filter( 'cron_schedules', array( $this, 'wpparsely_add_cron_interval' ) );
113 - add_action( 'parsely_bulk_metas_update', array( $this, 'bulk_update_posts' ) );
114 - add_action( 'save_post', array( $this, 'update_metadata_endpoint' ) );
115 - add_action( 'wp_head', array( $this, 'insert_page_header_metadata' ) );
116 - }
117 -
118 232 /**
119 - * Adds 10 minute cron interval.
233 + * Returns whether credentials are being managed at the platform level.
120 234 *
121 - * @param array $schedules WP schedules array.
122 - * @return array
235 + * This allows hosting providers to provide a more customized experience for
236 + * the plugin by handling credentials automatically.
237 + *
238 + * @since 3.9.0
239 + * @access private
240 + * @var bool
123 241 */
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 - }
242 + public $are_credentials_managed;
131 243
132 244 /**
133 - * Get the full URL of the JavaScript tracker file for the site. If an API key is not set, return an empty string.
245 + * Holds the managed options and their values.
134 246 *
135 - * @since 3.2.0
247 + * This allows hosting providers to provide a more customized experience for
248 + * the plugin by handling options automatically.
136 249 *
137 - * @return string
250 + * @since 3.9.0
251 + * @access private
252 + * @var array<empty>|array<string, bool|string|null>
138 253 */
139 - public function get_tracker_url(): string {
140 - if ( $this->api_key_is_set() ) {
141 - $tracker_url = 'https://cdn.parsely.com/keys/' . $this->get_api_key() . '/p.js';
142 - return esc_url( $tracker_url );
143 - }
144 - return '';
254 + public $managed_options = array();
255 +
256 + /**
257 + * Constructor.
258 + */
259 + public function __construct() {
260 + self::$all_supported_types = array_merge( self::SUPPORTED_JSONLD_POST_TYPES, self::SUPPORTED_JSONLD_NON_POST_TYPES );
261 +
262 + $this->are_credentials_managed = $this->are_credentials_managed();
263 + $this->set_managed_options();
264 +
265 + $this->allow_parsely_remote_requests();
145 266 }
146 267
147 268 /**
148 - * Insert the code for the <meta name='parsely-page'> parameter within the <head></head> tag.
269 + * Gets the allowed post statuses for tracking.
149 270 *
150 - * @since 3.2.0
271 + * Uses the `wp_parsely_trackable_statuses` filter to determine which post statuses are allowed to be tracked.
151 272 *
152 - * @param string $meta_type `json_ld` or `repeated_metas`.
153 - * @return void
273 + * @since 3.17.0
274 + *
275 + * @param WP_Post|int|null $post The post object.
276 + * @return array<string> The allowed post statuses.
154 277 */
155 - public function render_metadata( string $meta_type ): void {
278 + public static function get_trackable_statuses( $post = null ): array {
156 279 /**
157 - * Filter whether the Parse.ly meta tags should be inserted in the page.
280 + * Filters the statuses that are permitted to be tracked.
158 281 *
159 - * By default, the tags are inserted.
282 + * By default, the only status tracked is 'publish'. Use this filter if
283 + * you have other published content that has a different (custom) status.
160 284 *
161 - * @since 3.0.0
285 + * @since 2.5.0
286 + * @since 3.17.0 Filter extracted to a separate method.
162 287 *
163 - * @param bool $insert_metadata True to insert the metadata, false otherwise.
288 + * @param string[] $trackable_statuses The list of post statuses that are allowed to be tracked.
289 + * @param WP_Post|int|null $post Which post object or ID is being checked.
164 290 */
165 - if ( ! apply_filters( 'wp_parsely_should_insert_metadata', true ) ) {
166 - return;
167 - }
291 + return apply_filters( 'wp_parsely_trackable_statuses', array( 'publish' ), $post );
292 + }
168 293
169 - $parsely_options = $this->get_options();
294 + /**
295 + * Registers action and filter hook callbacks, and immediately upgrades
296 + * options if needed.
297 + */
298 + public function run(): void {
299 + // Run upgrade options if they exist for the version currently defined.
300 + $options = $this->get_options();
301 + if ( self::VERSION !== $options['plugin_version'] ) {
302 + $method = 'upgrade_plugin_to_version_' . str_replace( '.', '_', self::VERSION );
303 + if ( method_exists( $this, $method ) ) {
304 + /**
305 + * Variable.
306 + *
307 + * @var callable
308 + */
309 + $callable = array( $this, $method );
310 + call_user_func_array( $callable, array( $options ) );
311 + }
170 312
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;
313 + // Update our version info.
314 + $options['plugin_version'] = self::VERSION;
315 + update_option( self::OPTIONS_KEY, $options );
184 316 }
185 317
186 - global $post;
318 + // @phpstan-ignore return.void
319 + add_action( 'save_post', array( $this, 'call_update_metadata_endpoint' ) );
320 + }
187 321
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;
322 + /**
323 + * Returns the Content API service.
324 + *
325 + * This method returns the Content API service, which is used to interact with the Parse.ly Content API.
326 + *
327 + * @since 3.17.0
328 + *
329 + * @return Content_API_Service
330 + */
331 + public function get_content_api(): Content_API_Service {
332 + if ( ! isset( $this->content_api_service ) ) {
333 + $this->content_api_service = new Content_API_Service( $this );
192 334 }
193 335
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 );
336 + return $this->content_api_service;
337 + }
197 338
198 - // Something went wrong - abort.
199 - if ( 0 === count( $parsely_page ) || ! isset( $parsely_page['headline'] ) ) {
200 - return;
339 + /**
340 + * Returns the Suggestions API service.
341 + *
342 + * This method returns the Suggestions API service, which is used to interact with the Parse.ly Suggestions API.
343 + *
344 + * @since 3.17.0
345 + *
346 + * @return Suggestions_API_Service
347 + */
348 + public function get_suggestions_api(): Suggestions_API_Service {
349 + if ( ! isset( $this->suggestions_api_service ) ) {
350 + $this->suggestions_api_service = new Suggestions_API_Service( $this );
201 351 }
202 352
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 - }
353 + return $this->suggestions_api_service;
237 354 }
238 355
239 356 /**
240 - * Insert the code for the <meta name='parsely-page'> parameter within the <head></head> tag.
357 + * Gets the REST API controller.
241 358 *
242 - * @since 3.0.0
359 + * If the controller is not set, a new instance is created.
243 360 *
244 - * @return void
361 + * @since 3.17.0
362 + *
363 + * @return REST_API_Controller
245 364 */
246 - public function insert_page_header_metadata(): void {
247 - $parsely_options = $this->get_options();
248 - $this->render_metadata( $parsely_options['meta_type'] );
365 + public function get_rest_api_controller(): REST_API_Controller {
366 + if ( ! isset( $this->rest_api_controller ) ) {
367 + $this->rest_api_controller = new REST_API_Controller( $this );
368 + }
369 +
370 + return $this->rest_api_controller;
249 371 }
250 372
251 373 /**
252 - * Deprecated. Echo the metadata into the page, and return the inserted values.
374 + * Gets the full URL of the JavaScript tracker file for the site. If an API
375 + * key is not set, return an empty string.
253 376 *
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.
377 + * @since 3.2.0
256 378 *
257 - * @deprecated 3.0.0
258 - * @see construct_parsely_metadata()
259 - *
260 - * @return array<string, mixed>
379 + * @return string
261 380 */
262 - public function insert_parsely_page(): array {
263 - _deprecated_function( __FUNCTION__, '3.0', 'construct_parsely_metadata()' );
264 - $this->insert_page_header_metadata();
381 + public function get_tracker_url(): string {
382 + if ( $this->site_id_is_set() ) {
383 + $tracker_url = 'https://cdn.parsely.com/keys/' . $this->get_site_id() . '/p.js';
265 384
266 - global $post;
267 -
268 - $parsed_post = get_post( $post );
269 - if ( ! $parsed_post instanceof WP_Post ) {
270 - return array();
385 + /**
386 + * Filters the URL of the Parse.ly tracker script.
387 + *
388 + * The filtered value gets sanitized with {@see esc_url_raw()}.
389 + *
390 + * @since 3.23.0
391 + *
392 + * @param string $tracker_url The URL of the tracker script.
393 + */
394 + return esc_url_raw( apply_filters( 'wp_parsely_tracker_url', $tracker_url ) );
271 395 }
272 396
273 - return $this->construct_parsely_metadata( $this->get_options(), $parsed_post );
397 + return '';
274 398 }
275 399
276 400 /**
277 - * Function to be used in `array_filter` to clean up repeated metas.
401 + * Deprecated.
402 + * Inserts the code for the <meta name='parsely-page'> parameter within the
403 + * head tag.
278 404 *
279 - * @since 2.6.0
405 + * @since 3.2.0
406 + * @deprecated 3.3.0
407 + * @see Metadata_Renderer::render_metadata
280 408 *
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.
409 + * @param string $meta_type `json_ld` or `repeated_metas`.
283 410 */
284 - private static function filter_empty_and_not_string_from_array( $var ): bool {
285 - return is_string( $var ) && '' !== $var;
411 + public function render_metadata( string $meta_type ): void {
412 + _deprecated_function( __FUNCTION__, '3.3', 'Metadata_Renderer::render_metadata()' );
413 + $metadata_renderer = new Metadata_Renderer( $this );
414 + $metadata_renderer->render_metadata( $meta_type );
286 415 }
287 416
288 417 /**
289 - * Compare the post_status key against an allowed list (by default, only 'publish'ed content includes tracking data).
418 + * Deprecated.
419 + * Insert the code for the <meta name='parsely-page'> parameter within the
420 + * head tag.
290 421 *
422 + * @since 3.0.0
423 + * @deprecated 3.3.0
424 + * @see Metadata_Renderer::render_metadata
425 + */
426 + public function insert_page_header_metadata(): void {
427 + _deprecated_function( __FUNCTION__, '3.3', 'Metadata_Renderer::render_metadata()' );
428 + $parsely_options = $this->get_options();
429 + $metadata_renderer = new Metadata_Renderer( $this );
430 + $metadata_renderer->render_metadata( $parsely_options['meta_type'] );
431 + }
432 +
433 + /**
434 + * Compares the post_status key against an allowed list.
435 + *
436 + * By default, only 'publish'ed content includes tracking data.
437 + *
291 438 * @since 2.5.0
292 439 *
293 440 * @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.
441 + * @return bool Should the post status be tracked for the provided post's post_type.
442 + * By default,only 'publish' is allowed.
295 443 */
296 444 public static function post_has_trackable_status( $post ): bool {
297 - static $cache = array();
298 - $post_id = is_int( $post ) ? $post : $post->ID;
299 - if ( isset( $cache[ $post_id ] ) ) {
300 - return $cache[ $post_id ];
301 - }
302 -
303 445 /**
304 - * Filters whether the post password check should be skipped when getting the post trackable status.
446 + * Filters whether the post password check should be skipped when getting
447 + * the post trackable status.
305 448 *
306 449 * @since 3.0.1
307 450 *
308 451 * @param bool $skip True if the password check should be skipped.
@@ -307,823 +450,787 @@
307 450 *
308 451 * @param bool $skip True if the password check should be skipped.
309 452 * @param int|WP_Post $post Which post object or ID is being checked.
310 453 *
311 - * @returns bool
454 + * @return bool
312 455 */
313 456 $skip_password_check = apply_filters( 'wp_parsely_skip_post_password_check', false, $post );
314 457 if ( ! $skip_password_check && post_password_required( $post ) ) {
315 - $cache[ $post_id ] = false;
316 458 return false;
317 459 }
318 460
319 - /**
320 - * Filters the statuses that are permitted to be tracked.
321 - *
322 - * By default, the only status tracked is 'publish'. Use this filter if you have other published content that has a different (custom) status.
323 - *
324 - * @since 2.5.0
325 - *
326 - * @param string[] $trackable_statuses The list of post statuses that are allowed to be tracked.
327 - * @param int|WP_Post $post Which post object or ID is being checked.
328 - */
329 - $statuses = apply_filters( 'wp_parsely_trackable_statuses', array( 'publish' ), $post );
330 - $cache[ $post_id ] = in_array( get_post_status( $post ), $statuses, true );
331 - return $cache[ $post_id ];
461 + $statuses = self::get_trackable_statuses( $post );
462 + return in_array( get_post_status( $post ), $statuses, true );
332 463 }
333 464
334 465 /**
466 + * Deprecated. Please use the `Metadata` class instead.
467 + *
335 468 * Creates parsely metadata object from post metadata.
336 469 *
470 + * @deprecated 3.3.0
471 + * @see \Parsely\Metadata::construct_metadata
472 + *
337 473 * @param array<string, mixed> $parsely_options parsely_options array.
338 474 * @param WP_Post $post object.
339 - * @return array<string, mixed>
475 + * @return Metadata_Attributes
340 476 */
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',
477 + public function construct_parsely_metadata( array $parsely_options, WP_Post $post ) {
478 + _deprecated_function( __FUNCTION__, '3.3', 'Metadata::construct_metadata()' );
479 + $metadata = new Metadata( $this );
480 + return $metadata->construct_metadata( $post );
481 + }
482 +
483 + /**
484 + * Calls Parse.ly's update metadata endpoint, sending the post's updated
485 + * metadata.
486 + *
487 + * @param int $post_id The ID of the post to update.
488 + * @return bool True if the metadata endpoint was called, false otherwise.
489 + */
490 + public function call_update_metadata_endpoint( int $post_id ): bool {
491 + $options = $this->get_options();
492 +
493 + if ( $this->site_id_is_missing() || '' === $options['metadata_secret'] ) {
494 + return false;
495 + }
496 +
497 + $current_post_type = get_post_type( $post_id );
498 + if ( false === $current_post_type ) {
499 + return false;
500 + }
501 +
502 + $tracked_post_types = array_merge(
503 + $options['track_post_types'],
504 + $options['track_page_types']
345 505 );
346 - $current_url = $this->get_current_url();
347 - $queried_object_id = get_queried_object_id();
348 506
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 );
507 + // Check that the post's type is trackable.
508 + if ( ! in_array( $current_post_type, $tracked_post_types, true ) ) {
509 + return false;
510 + }
398 511
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 - }
512 + // Check that the post's status is trackable.
513 + if ( ! self::post_has_trackable_status( $post_id ) ) {
514 + return false;
515 + }
406 516
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 - }
517 + $post = get_post( $post_id );
518 + if ( null === $post ) {
519 + return false;
520 + }
423 521
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 ) );
522 + // Don't call the endpoint when integration tests are running, but
523 + // signal that the above checks have passed.
524 + if ( defined( 'INTEGRATION_TESTS_RUNNING' ) ) {
525 + return true;
526 + }
435 527
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 );
528 + $metadata = ( new Metadata( $this ) )->construct_metadata( $post );
447 529
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 - }
530 + $endpoint_metadata = array(
531 + 'canonical_url' => $metadata['url'] ?? '',
532 + 'page_type' => $this->convert_jsonld_to_parsely_type( $metadata['@type'] ?? '' ),
533 + 'title' => $metadata['headline'] ?? '',
534 + 'image_url' => $metadata['image']['url'] ?? '',
535 + 'pub_date_tmsp' => $metadata['datePublished'] ?? '',
536 + 'section' => $metadata['articleSection'] ?? '',
537 + 'authors' => $metadata['creator'] ?? '',
538 + 'tags' => $metadata['keywords'] ?? '',
539 + );
460 540
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 - );
541 + $parsely_api_base_url = Content_API_Service::get_base_url();
542 + $parsely_api_endpoint = $parsely_api_base_url . '/metadata/posts';
543 + $parsely_metadata_secret = $options['metadata_secret'];
473 544
474 - $this->set_metadata_post_times( $parsely_page, $post );
545 + $headers = array( 'Content-Type' => 'application/json' );
546 + $body = wp_json_encode(
547 + array(
548 + 'secret' => $parsely_metadata_secret,
549 + 'apikey' => $this->get_site_id(),
550 + 'metadata' => $endpoint_metadata,
551 + )
552 + );
475 553
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 554 /**
502 - * Filters the structured metadata.
555 + * POST request options.
503 556 *
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.
557 + * @var WP_HTTP_Request_Args $request_options
509 558 */
510 - $filtered = apply_filters( 'wp_parsely_metadata', $parsely_page, $post, $parsely_options );
511 - if ( is_array( $filtered ) ) {
512 - return $filtered;
559 + $request_options = array(
560 + 'method' => 'POST',
561 + 'headers' => $headers,
562 + 'blocking' => false,
563 + 'body' => $body,
564 + 'data_format' => 'body',
565 + );
566 +
567 + $response = wp_remote_post( $parsely_api_endpoint, $request_options );
568 +
569 + if ( is_wp_error( $response ) ) {
570 + return false;
513 571 }
514 - return array();
572 +
573 + update_post_meta( $post_id, 'parsely_metadata_last_updated', time() );
574 +
575 + return true;
515 576 }
516 577
517 578 /**
518 - * Sets all metadata values related to post time.
579 + * Safely returns options for the plugin by assigning defaults contained in
580 + * optionDefaults.
519 581 *
520 - * @since 3.0.2
582 + * As soon as actual options are saved, they override the defaults. This
583 + * prevents us from having to do a lot of isset() checking on variables.
521 584 *
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
585 + * @return Parsely_Options
525 586 */
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 );
587 + public function get_options() {
588 + /**
589 + * Variable.
590 + *
591 + * @var Parsely_Options|null
592 + */
593 + $options = get_option( self::OPTIONS_KEY, null );
529 594
530 - if ( false === $post_created_gmt ) {
531 - return;
595 + // Existing plugin installation without full metadata option.
596 + /* @phpstan-ignore isset.offset, booleanAnd.alwaysFalse */
597 + if ( is_array( $options ) && ! isset( $options['full_metadata_in_non_posts'] ) ) {
598 + $this->set_default_full_metadata_in_non_posts();
532 599 }
533 600
534 - $metadata['dateCreated'] = $post_created_gmt;
535 - $metadata['datePublished'] = $post_created_gmt;
536 - $metadata['dateModified'] = $post_created_gmt;
601 + // Existing plugin installation without Content Intelligence options.
602 + /* @phpstan-ignore isset.offset, booleanAnd.alwaysFalse */
603 + if ( is_array( $options ) && ! isset( $options['content_helper'] ) ) {
604 + $this->set_default_content_helper_settings_values();
605 + }
537 606
538 - $post_modified_gmt = get_post_modified_time( $date_format, true, $post );
607 + // Existing plugin installation that's missing a Content Intelligence
608 + // feature option.
609 + /* @phpstan-ignore isset.offset */
610 + if ( is_array( $options ) && isset( $options['content_helper'] ) ) {
611 + /** @var array<string,Parsely_Options_Content_Helper_Feature> $pch_options */
612 + $pch_options = $options['content_helper'];
539 613
540 - if ( false !== $post_modified_gmt && $post_modified_gmt > $post_created_gmt ) {
541 - $metadata['dateModified'] = $post_modified_gmt;
614 + /** @var array<string,Parsely_Options_Content_Helper_Feature> $pch_options_defaults */
615 + $pch_options_defaults = $this->option_defaults['content_helper'];
616 +
617 + if ( count( $pch_options ) !== count( $pch_options_defaults ) ) {
618 + $new_keys = array_diff(
619 + array_keys( $pch_options_defaults ),
620 + array_keys( $pch_options )
621 + );
622 +
623 + foreach ( $new_keys as $key ) {
624 + $options['content_helper'][ $key ] = $pch_options_defaults[ $key ];
625 + }
626 + }
542 627 }
628 +
629 + // New plugin installation that hasn't saved its options yet.
630 + if ( ! is_array( $options ) ) {
631 + $this->set_default_track_as_values();
632 + $this->set_default_full_metadata_in_non_posts();
633 + $options = $this->option_defaults;
634 + }
635 +
636 + /**
637 + * Final options including managed credentials and options.
638 + *
639 + * @var Parsely_Options
640 + */
641 + return array_merge(
642 + $this->option_defaults,
643 + $options,
644 + $this->get_managed_credentials(),
645 + $this->managed_options
646 + );
543 647 }
544 648
545 649 /**
546 - * Updates the Parsely metadata endpoint with the new metadata of the post.
650 + * Returns the value of a nested option.
547 651 *
548 - * @param int $post_id id of the post to update.
549 - * @return void
652 + * @since 3.16.0
653 + *
654 + * @param string $option The option to get.
655 + * @param Parsely_Options $options The options to get the value from.
656 + * @return mixed The value of the nested option.
550 657 */
551 - public function update_metadata_endpoint( int $post_id ): void {
552 - $parsely_options = $this->get_options();
658 + public static function get_nested_option_value( $option, $options ) {
659 + $keys = explode( '[', str_replace( ']', '', $option ) );
660 + $value = $options;
553 661
554 - if ( $this->api_key_is_missing() || empty( $parsely_options['metadata_secret'] ) ) {
555 - return;
662 + foreach ( $keys as $key ) {
663 + if ( isset( $value[ $key ] ) ) {
664 + $value = $value[ $key ];
665 + }
556 666 }
557 667
558 - $post = get_post( $post_id );
559 - $metadata = $this->construct_parsely_metadata( $parsely_options, $post );
668 + return $value;
669 + }
560 670
561 - $endpoint_metadata = array(
562 - 'canonical_url' => $metadata['url'],
563 - 'page_type' => $this->convert_jsonld_to_parsely_type( $metadata['@type'] ),
564 - 'title' => $metadata['headline'],
565 - 'image_url' => $metadata['thumbnailUrl'],
566 - 'pub_date_tmsp' => $metadata['datePublished'],
567 - 'section' => $metadata['articleSection'],
568 - 'authors' => $metadata['creator'],
569 - 'tags' => $metadata['keywords'],
570 - );
671 + /**
672 + * Sets the default values for the track_post_types and track_page_types
673 + * options.
674 + *
675 + * @since 3.9.0
676 + */
677 + public function set_default_track_as_values(): void {
678 + $this->option_defaults['track_page_types'] = array();
679 + $this->option_defaults['track_post_types'] = array();
571 680
572 - $parsely_api_endpoint = 'https://api.parsely.com/v2/metadata/posts';
573 - $parsely_metadata_secret = $parsely_options['metadata_secret'];
574 - $headers = array(
575 - 'Content-Type' => 'application/json',
576 - );
577 - $body = wp_json_encode(
578 - array(
579 - 'secret' => $parsely_metadata_secret,
580 - 'apikey' => $parsely_options['apikey'],
581 - 'metadata' => $endpoint_metadata,
582 - )
583 - );
584 - $response = wp_remote_post(
585 - $parsely_api_endpoint,
586 - array(
587 - 'method' => 'POST',
588 - 'headers' => $headers,
589 - 'blocking' => false,
590 - 'body' => $body,
591 - 'data_format' => 'body',
592 - )
593 - );
681 + $post_types = get_post_types( array( 'public' => true ) );
594 682
595 - if ( ! is_wp_error( $response ) ) {
596 - $current_timestamp = time();
597 - update_post_meta( $post_id, 'parsely_metadata_last_updated', $current_timestamp );
683 + foreach ( $post_types as $post_type ) {
684 + if ( ! post_type_supports( $post_type, 'editor' ) ) {
685 + continue;
686 + }
687 +
688 + if ( is_post_type_hierarchical( $post_type ) ) {
689 + $this->option_defaults['track_page_types'][] = $post_type;
690 + } else {
691 + $this->option_defaults['track_post_types'][] = $post_type;
692 + }
598 693 }
599 694 }
600 695
601 696 /**
602 - * Updates posts with Parsely metadata api in bulk.
697 + * Sets the default value for the full_metadata_in_non_posts option.
603 698 *
604 - * @return void
699 + * @since 3.14.0
605 700 */
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 - )
701 + public function set_default_full_metadata_in_non_posts(): void {
702 + $this->option_defaults['full_metadata_in_non_posts'] = true;
703 +
704 + // Usage of any of these filters will result in the setting being set
705 + // to false.
706 + $filter_tags = array(
707 + 'wp_parsely_metadata',
708 + 'wp_parsely_post_tags',
709 + 'wp_parsely_permalink',
710 + 'wp_parsely_post_category',
711 + 'wp_parsely_pre_authors',
712 + 'wp_parsely_post_authors',
713 + 'wp_parsely_custom_taxonomies',
714 + 'wp_parsely_post_type',
618 715 );
619 - $ids = wp_cache_get( 'parsely_post_ids_need_meta_updating' );
620 - if ( false === $ids ) {
621 - $ids = array();
622 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
623 - $results = $wpdb->get_results(
624 - $wpdb->prepare( "SELECT DISTINCT(id) FROM {$wpdb->posts} WHERE post_type IN (\" . %s . \") AND id NOT IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'parsely_metadata_last_updated');", $allowed_types_string ),
625 - ARRAY_N
626 - );
627 - foreach ( $results as $result ) {
628 - array_push( $ids, $result[0] );
629 - }
630 - wp_cache_set( 'parsely_post_ids_need_meta_updating', $ids, '', 86400 );
631 - }
632 716
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' );
717 + foreach ( $filter_tags as $filter_tag ) {
718 + if ( has_filter( $filter_tag ) ) {
719 + $this->option_defaults['full_metadata_in_non_posts'] = false;
637 720 break;
638 721 }
639 - $this->update_metadata_endpoint( $post_id );
640 722 }
641 723 }
642 724
643 725 /**
644 - * Get the cache buster value for script and styles.
726 + * Sets the default values for Content Intelligence options.
645 727 *
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.
728 + * Gives PCH access to all users having the edit_posts capability, to keep
729 + * consistent behavior with plugin versions prior to 3.16.0.
648 730 *
649 - * @since 2.5.0
650 - * @deprecated 3.2.0
731 + * @since 3.16.0
732 + */
733 + public function set_default_content_helper_settings_values(): void {
734 + $this->option_defaults['content_helper'] =
735 + Permissions::build_pch_permissions_settings_array(
736 + true,
737 + array_keys( Permissions::get_user_roles_with_edit_posts_cap() )
738 + );
739 + }
740 +
741 + /**
742 + * Gets the URL of the plugin's settings page.
651 743 *
652 - * @return string Random number string or plugin version string.
744 + * @param int|null $_blog_id The Blog ID for the multisite subsite to use
745 + * for context (Default null for current).
746 + * @return string
653 747 */
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 - }
748 + public static function get_settings_url( ?int $_blog_id = null ): string {
749 + return get_admin_url( $_blog_id, 'admin.php?page=' . self::MENU_SLUG );
750 + }
660 751
661 - $cache_buster = defined( 'WP_DEBUG' ) && WP_DEBUG && empty( 'WP_TESTS_DOMAIN' ) ? wp_rand() : PARSELY_VERSION;
752 + /**
753 + * Returns the URL of the Parse.ly dashboard for a specific page. If a page
754 + * is not specified, the home dashboard URL for the specified Site ID is
755 + * returned.
756 + *
757 + * @since 3.7.0
758 + *
759 + * @param string $site_id The Site ID for which to get the URL.
760 + * @param string $page_url Optional. The page for which to get the URL.
761 + * @return string The complete dashboard URL.
762 + */
763 + public static function get_dash_url( string $site_id, string $page_url = '' ): string {
764 + $result = trailingslashit( self::DASHBOARD_BASE_URL . '/' . $site_id ) . 'find';
662 765
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' );
766 + if ( '' !== $page_url ) {
767 + $page_url = self::get_url_with_itm_source( $page_url, null );
768 + $result .= '?url=' . rawurlencode( $page_url );
769 + }
671 770
672 - return $cache_buster;
771 + return $result;
673 772 }
674 773
675 774 /**
676 - * Returns the tags associated with this page or post
775 + * Adds or replaces the itm_source parameter in the URL. Removes the
776 + * parameter if the passed value is null or an empty string.
677 777 *
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.
778 + * @since 3.9.0
779 + *
780 + * @param string $url The URL to modify.
781 + * @param string|null $itm_source The value of the itm_source parameter.
782 + * @return string The resulting URL.
680 783 */
681 - private function get_tags( int $post_id ): array {
682 - $tags = array();
683 - $post_tags = wp_get_post_tags( $post_id );
684 - if ( ! is_wp_error( $post_tags ) ) {
685 - foreach ( $post_tags as $wp_tag ) {
686 - $tags[] = $wp_tag->name;
687 - }
784 + public static function get_url_with_itm_source( string $url, $itm_source ): string {
785 + if ( null === $itm_source || '' === $itm_source ) {
786 + return remove_query_arg( 'itm_source', $url );
688 787 }
689 - return $tags;
788 +
789 + $itm_source = rawurlencode( $itm_source );
790 +
791 + return add_query_arg( 'itm_source', $itm_source, $url );
690 792 }
691 793
692 794 /**
693 - * Returns an array of all the child categories for the current post
795 + * Checks to see if the current user is a member of the current blog.
694 796 *
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.
797 + * @return bool
698 798 */
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 - }
799 + public function is_blog_member_logged_in(): bool {
800 + // Can't use $blog_id here because it futzes with the global $blog_id.
801 + $current_blog_id = get_current_blog_id();
802 + $current_user_id = get_current_user_id();
713 803
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 ) );
804 + return is_user_member_of_blog( $current_user_id, $current_blog_id );
717 805 }
718 806
719 807 /**
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.
808 + * Converts JSON-LD type to respective Parse.ly page type.
723 809 *
724 - * @return array
810 + * If the JSON-LD type is one of the types Parse.ly supports as a "post",
811 + * then "post" will be returned. Otherwise, for "non-posts" and unknown
812 + * types, "index" is returned.
813 + *
814 + * @since 2.5.0
815 + *
816 + * @see https://docs.parse.ly/metatags/#h-field-description
817 + *
818 + * @param string $type JSON-LD type.
819 + * @return string "post" or "index".
725 820 */
726 - public function get_options(): array {
727 - $options = get_option( self::OPTIONS_KEY, $this->option_defaults );
821 + public function convert_jsonld_to_parsely_type( string $type ): string {
822 + return in_array( $type, self::SUPPORTED_JSONLD_POST_TYPES, true ) ? 'post' : 'index';
823 + }
728 824
729 - if ( ! is_array( $options ) ) {
730 - return $this->option_defaults;
731 - }
825 + /**
826 + * Determines if a Site ID is saved in the options.
827 + *
828 + * @since 2.6.0
829 + * @since 3.7.0 renamed from api_key_is_set.
830 + *
831 + * @return bool True is Site ID is set, false if it is missing.
832 + */
833 + public function site_id_is_set(): bool {
834 + $options = $this->get_options();
732 835
733 - return array_merge( $this->option_defaults, $options );
836 + return '' !== $options['apikey'];
734 837 }
735 838
736 839 /**
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.
840 + * Determines if a Site ID is not saved in the options.
739 841 *
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.
842 + * @since 2.6.0
843 + * @since 3.7.0 renamed from api_key_is_missing.
844 + *
845 + * @return bool True if Site ID is missing, false if it is set.
743 846 */
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 - }
847 + public function site_id_is_missing(): bool {
848 + return ! $this->site_id_is_set();
849 + }
757 850
758 - if ( is_string( $term_name ) && 0 < strlen( $term_name ) ) {
759 - $category_name = $term_name;
760 - }
761 - }
851 + /**
852 + * Gets the Site ID if set.
853 + *
854 + * @since 2.6.0
855 + * @since 3.7.0 renamed from get_site_id.
856 + *
857 + * @return string Site ID if set, or empty string if not.
858 + */
859 + public function get_site_id(): string {
860 + $options = $this->get_options();
762 861
763 - /**
764 - * Filters the constructed category name that are used as metadata keywords.
765 - *
766 - * @since 1.8.0
767 - *
768 - * @param string $category Category name.
769 - * @param WP_Post $post_obj Post object.
770 - * @param array $parsely_options The Parsely options.
771 - */
772 - $category_name = apply_filters( 'wp_parsely_post_category', $category_name, $post_obj, $parsely_options );
773 -
774 - return $this->get_clean_parsely_page_value( $category_name );
862 + return $this->site_id_is_set() ? $options['apikey'] : '';
775 863 }
776 864
777 865 /**
778 - * Return the top-most category/taxonomy value in a hierarcy given a taxonomy value's ID
779 - * ( WordPress calls taxonomy values 'terms' ).
866 + * Returns whether the API Secret is set in the plugin's options.
780 867 *
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.
868 + * @since 3.4.0
869 + *
870 + * @return bool True if the API Secret is set, false if not set.
784 871 */
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;
872 + public function api_secret_is_set(): bool {
873 + $options = $this->get_options();
874 +
875 + return '' !== $options['api_secret'];
791 876 }
792 877
793 878 /**
794 - * Return the bottom-most category/taxonomy value in a hierarcy given a post ID
795 - * ( WordPress calls taxonomy values 'terms' ).
879 + * Returns the API Secret stored in the plugin's options.
796 880 *
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.
881 + * @since 3.4.0
882 + *
883 + * @return string The API Secret, empty string if the API secret is not set.
800 884 */
801 - private function get_bottom_level_term( int $post_id, string $taxonomy_name ): string {
802 - $terms = get_the_terms( $post_id, $taxonomy_name );
885 + public function get_api_secret(): string {
886 + $options = $this->get_options();
803 887
804 - if ( ! is_array( $terms ) ) {
805 - return '';
806 - }
888 + return $this->api_secret_is_set() ? $options['api_secret'] : '';
889 + }
807 890
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 '';
891 + /**
892 + * Returns all supported post and non-post types.
893 + *
894 + * @since 3.7.0
895 + *
896 + * @return string[] all supported types
897 + */
898 + public function get_all_supported_types(): array {
899 + return self::$all_supported_types;
827 900 }
828 901
829 902 /**
830 - * Get all term values from custom taxonomies.
903 + * Gets all tracked post types.
831 904 *
832 - * @param WP_Post $post_obj The post object.
905 + * @since 3.7.0
906 + *
833 907 * @return array<string>
834 908 */
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();
909 + public function get_all_track_types(): array {
910 + $options = $this->get_options();
839 911
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 - }
912 + return array_unique( array_merge( $options['track_post_types'], $options['track_page_types'] ) );
913 + }
848 914
849 - return $all_values;
915 + /**
916 + * Gets default options.
917 + *
918 + * @since 3.8.0
919 + *
920 + * @return Parsely_Options
921 + */
922 + public function get_default_options() {
923 + return $this->option_defaults;
850 924 }
851 925
852 926 /**
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
927 + * Returns the credentials that are being managed at the platform level.
856 928 *
857 - * @param int $post_id The id of the post.
858 - * @return array<WP_User>
929 + * @since 3.9.0
930 + * @access private
931 + *
932 + * @return Parsely_Options|array<empty> The managed credentials.
859 933 */
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;
934 + private function get_managed_credentials() {
935 + if ( true !== $this->are_credentials_managed ) {
936 + return array();
937 + }
864 938
865 - if ( ! $post_id && $post_ID ) {
866 - $post_id = $post_ID;
867 - }
939 + $credentials = apply_filters( 'wp_parsely_credentials', array() );
868 940
869 - if ( ! $post_id && $post ) {
870 - $post_id = $post->ID;
871 - }
941 + if ( ! is_array( $credentials ) || 0 === count( $credentials ) ) {
942 + return array();
943 + }
872 944
873 - if ( $post_id ) {
874 - $coauthor_terms = get_the_terms( $post_id, $coauthors_plus->coauthor_taxonomy );
945 + $result = array();
875 946
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 - }
947 + if ( isset( $credentials['site_id'] ) ) {
948 + $result['apikey'] = $credentials['site_id'];
894 949 }
895 - return $coauthors;
896 - }
897 950
898 - /**
899 - * Determine author name from display name, falling back to firstname
900 - * lastname, then nickname and finally the nicename.
901 - *
902 - * @param ?WP_User $author The author of the post.
903 - * @return string
904 - */
905 - private function get_author_name( ?WP_User $author ): string {
906 - // Gracefully handle situation where no author is available.
907 - if ( null === $author ) {
908 - return '';
951 + if ( isset( $credentials['api_secret'] ) ) {
952 + $result['api_secret'] = $credentials['api_secret'];
909 953 }
910 954
911 - if ( ! empty( $author->display_name ) ) {
912 - return $author->display_name;
955 + if ( isset( $credentials['metadata_secret'] ) ) {
956 + $result['metadata_secret'] = $credentials['metadata_secret'];
913 957 }
914 958
915 - $author_name = $author->user_firstname . ' ' . $author->user_lastname;
916 - if ( ' ' !== $author_name ) {
917 - return $author_name;
918 - }
959 + return $result;
960 + }
919 961
920 - if ( ! empty( $author->nickname ) ) {
921 - return $author->nickname;
922 - }
962 + /**
963 + * Returns whether credentials are being managed at the platform level.
964 + *
965 + * @since 3.9.0
966 + * @access private
967 + *
968 + * @return bool Whether credentials are being managed at the platform level.
969 + */
970 + private function are_credentials_managed(): bool {
971 + $credentials = apply_filters( 'wp_parsely_credentials', array() );
923 972
924 - if ( ! empty( $author->user_nicename ) ) {
925 - return $author->user_nicename;
973 + if ( ! is_array( $credentials ) || 0 === count( $credentials ) ) {
974 + return false;
926 975 }
927 976
928 - return '';
977 + return $credentials['is_managed'] ?? false;
929 978 }
930 979
931 980 /**
932 - * Retrieve all the authors for a post as an array. Can include multiple
933 - * authors if coauthors plugin is in use.
981 + * Sets the values of managed options.
934 982 *
935 - * @param WP_Post $post The post object.
936 - * @return array<string>
983 + * This function won't accept managing credentials or certain plugin options
984 + * that are being managed through other means. For managing credentials,
985 + * please use the `wp_parsely_credentials` filter.
986 + *
987 + * @since 3.9.0
988 + * @access private
937 989 */
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 - }
990 + private function set_managed_options(): void {
991 + $managed_options = apply_filters( 'wp_parsely_managed_options', false );
992 +
993 + if ( ! is_array( $managed_options ) ) {
994 + return;
945 995 }
946 996
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 );
997 + // Don't allow certain options to be set as managed.
998 + unset(
999 + $managed_options['apikey'],
1000 + $managed_options['api_secret'],
1001 + $managed_options['metadata_secret'],
1002 + $managed_options['track_post_types'],
1003 + $managed_options['track_page_types'],
1004 + $managed_options['plugin_version']
1005 + );
956 1006
957 - // Getting the author name for each author.
958 - $authors = array_map( array( $this, 'get_author_name' ), $authors );
1007 + if ( 0 === count( $managed_options ) ) {
1008 + return;
1009 + }
959 1010
960 1011 /**
961 - * Filters the list of author names for a post.
1012 + * Current options.
962 1013 *
963 - * @since 1.14.0
964 - *
965 - * @param string[] $authors One or more author names.
966 - * @param WP_Post $post Post object.
1014 + * @var Parsely_Options $current_options
967 1015 */
968 - $authors = apply_filters( 'wp_parsely_post_authors', $authors, $post );
1016 + $current_options = get_option( self::OPTIONS_KEY, array() );
969 1017
970 - return array_map( array( $this, 'get_clean_parsely_page_value' ), $authors );
1018 + // Set managed options values.
1019 + foreach ( $managed_options as $key => $value ) {
1020 + $is_option_valid = isset( $this->option_defaults[ $key ] );
1021 +
1022 + if ( $is_option_valid ) {
1023 + if ( null === $value ) {
1024 + // When null, the option gets its value from the database.
1025 + $this->managed_options[ $key ] =
1026 + $current_options[ $key ] ?? $this->option_defaults[ $key ];
1027 + } else {
1028 + $this->managed_options[ $key ] =
1029 + $this->sanitize_managed_option( $key, $value );
1030 + }
1031 + }
1032 + }
971 1033 }
972 1034
973 1035 /**
974 - * Sanitize content
1036 + * Gets the Parse.ly canonical URL for a given post.
975 1037 *
976 - * @since 2.6.0
1038 + * @since 3.19.0
977 1039 *
978 - * @param string|null $val The content you'd like sanitized.
979 - * @return string
1040 + * @param WP_Post|int $post The post ID or post object.
1041 + * @return string The Parse.ly canonical URL.
980 1042 */
981 - public function get_clean_parsely_page_value( ?string $val ): string {
982 - if ( null === $val ) {
983 - return '';
1043 + public static function get_canonical_url_from_post( $post ): string {
1044 + $post_id = is_int( $post ) ? $post : $post->ID;
1045 + $canonical_url = get_post_meta( $post_id, self::PARSELY_CANONICAL_URL_META_KEY, true );
1046 +
1047 + if ( null !== $canonical_url && is_string( $canonical_url ) && '' !== $canonical_url ) {
1048 + return self::get_canonical_url( $canonical_url );
984 1049 }
985 1050
986 - $val = str_replace( "\n", '', $val );
987 - $val = str_replace( "\r", '', $val );
988 - $val = wp_strip_all_tags( $val );
989 - return trim( $val );
1051 + $permalink = get_permalink( $post );
1052 +
1053 + if ( false === $permalink ) {
1054 + return __( 'no permalink', 'wp-parsely' );
1055 + }
1056 +
1057 + return self::get_canonical_url( $permalink );
990 1058 }
991 1059
992 1060 /**
993 - * Get the URL of the plugin settings page.
1061 + * Returns the canonical version of the passed URL.
994 1062 *
995 - * @param int $_blog_id The Blog ID for the multisite subsite to use for context (Default null for current).
1063 + * In this context, the canonical URL is the URL containing the Site ID as
1064 + * its domain. If the Site ID differs from the real domain, the
1065 + * `wp_parsely_canonical_url_domain` filter can be used to set it.
996 1066 *
997 - * @return string
998 - */
999 - public static function get_settings_url( int $_blog_id = null ): string {
1000 - return get_admin_url( $_blog_id, 'options-general.php?page=' . self::MENU_SLUG );
1001 - }
1002 -
1003 - /**
1004 - * Get the URL of the current PHP script.
1005 - * A fall-back implementation to determine permalink
1067 + * @since 3.19.0
1068 + * @since 3.20.4 Made the domain overridable.
1006 1069 *
1007 - * @since 3.0.0 $parsely_type Default parameter changed to `non-post`.
1008 - *
1009 - * @param string $parsely_type Optional. Parse.ly post type you're interested in, either 'post' or 'non-post'. Default is 'non-post'.
1010 - * @param int $post_id Optional. ID of the post you want to get the URL for. Default is 0, which means the global `$post` is used.
1011 - * @return string
1070 + * @param string $url The URL to get the canonical URL for.
1071 + * @return string The canonical URL.
1012 1072 */
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 );
1073 + public static function get_canonical_url( string $url ): string {
1074 + $canonical_url_domain = apply_filters(
1075 + 'wp_parsely_canonical_url_domain',
1076 + null
1077 + );
1016 1078
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 - : '';
1079 + // Handle domain override.
1080 + if ( is_string( $canonical_url_domain ) ) {
1081 + // Get the canonical URL domain without protocol, trailing slashes
1082 + // or accidental whitespace.
1083 + $canonical_url_domain = rtrim( trim( $canonical_url_domain ), '/' );
1084 + $canonical_url_domain = preg_replace( '#^https?://#', '', $canonical_url_domain );
1033 1085
1034 - $url = home_url( $request_uri );
1086 + if ( is_string( $canonical_url_domain ) && '' !== $canonical_url_domain ) {
1087 + $url_domain = (string) wp_parse_url( $url, PHP_URL_HOST );
1088 + return str_replace( $url_domain, $canonical_url_domain, $url );
1089 + }
1035 1090 }
1036 1091
1037 - $options = $this->get_options();
1038 - return $options['force_https_canonicals']
1039 - ? str_replace( 'http://', 'https://', $url )
1040 - : str_replace( 'https://', 'http://', $url );
1041 - }
1092 + $site_id = \Parsely\get_parsely()->get_site_id();
1093 + $home_url_host = (string) wp_parse_url( home_url(), PHP_URL_HOST );
1042 1094
1043 - /**
1044 - * Get the first image from a post
1045 - * https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
1046 - *
1047 - * @param WP_Post $post The post object you're interested in.
1048 - * @return string
1049 - */
1050 - public function get_first_image( WP_Post $post ): string {
1051 - ob_start();
1052 - ob_end_clean();
1053 - if ( preg_match_all( '/<img.+src=[\'"]( [^\'"]+ )[\'"].*>/i', $post->post_content, $matches ) ) {
1054 - return $matches[1][0];
1095 + if ( $home_url_host === $site_id ) {
1096 + // URL does not need to be modified.
1097 + return $url;
1055 1098 }
1056 - return '';
1057 - }
1058 1099
1059 - /**
1060 - * Check to see if parsely user is logged in.
1061 - *
1062 - * @return bool
1063 - */
1064 - public function parsely_is_user_logged_in(): bool {
1065 - // can't use $blog_id here because it futzes with the global $blog_id.
1066 - $current_blog_id = get_current_blog_id();
1067 - $current_user_id = get_current_user_id();
1068 - return is_user_member_of_blog( $current_user_id, $current_blog_id );
1100 + // Return the URL with the Site ID as the domain.
1101 + return str_replace( $home_url_host, $site_id, $url );
1069 1102 }
1070 1103
1071 1104 /**
1072 - * Convert JSON-LD type to respective Parse.ly page type.
1105 + * Sets the Parse.ly canonical URL for a post.
1073 1106 *
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.
1107 + * @since 3.19.0
1076 1108 *
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".
1109 + * @param WP_Post|int $post The post object or post ID.
1110 + * @param string $url The canonical URL.
1111 + * @return bool True if the canonical URL was set, false otherwise.
1084 1112 */
1085 - private function convert_jsonld_to_parsely_type( string $type ): string {
1086 - return in_array( $type, $this->supported_jsonld_post_types, true ) ? 'post' : 'index';
1113 + public static function set_canonical_url( $post, string $url ): bool {
1114 + $post_id = is_int( $post ) ? $post : $post->ID;
1115 + $canonical_url = self::get_canonical_url( $url );
1116 +
1117 + return false !== update_post_meta(
1118 + $post_id,
1119 + self::PARSELY_CANONICAL_URL_META_KEY,
1120 + sanitize_url( $canonical_url, array( 'http', 'https' ) )
1121 + );
1087 1122 }
1088 1123
1089 1124 /**
1090 - * Determine if an API key is saved in the options.
1125 + * Sanitizes the value of the passed managed option.
1091 1126 *
1092 - * @since 2.6.0
1127 + * @since 3.9.0
1128 + * @access private
1093 1129 *
1094 - * @return bool True is API key is set, false if it is missing.
1130 + * @param string $option_id The option's ID.
1131 + * @param bool|string $value The option's value.
1132 + * @return bool|string The sanitized option value.
1095 1133 */
1096 - public function api_key_is_set(): bool {
1097 - $options = $this->get_options();
1134 + private function sanitize_managed_option( string $option_id, $value ) {
1135 + $option_value_type = gettype( $this->option_defaults[ $option_id ] );
1098 1136
1099 - return (
1100 - isset( $options['apikey'] ) &&
1101 - is_string( $options['apikey'] ) &&
1102 - '' !== $options['apikey']
1103 - );
1137 + if ( 'boolean' === $option_value_type && ! is_bool( $value ) ) {
1138 + _doing_it_wrong(
1139 + __FUNCTION__,
1140 + esc_html(
1141 + sprintf( /* translators: 1: Option ID */
1142 + __( 'The value of the managed option `%1$s` must be of type `boolean`.', 'wp-parsely' ),
1143 + $option_id
1144 + )
1145 + ),
1146 + ''
1147 + );
1148 +
1149 + return false;
1150 + }
1151 +
1152 + if ( 'string' === $option_value_type ) {
1153 + if ( ! is_string( $value ) ) {
1154 + _doing_it_wrong(
1155 + __FUNCTION__,
1156 + esc_html(
1157 + sprintf( /* translators: 1: Option ID */
1158 + __( 'The value of the managed option `%1$s` must be of type `string`.', 'wp-parsely' ),
1159 + $option_id
1160 + )
1161 + ),
1162 + ''
1163 + );
1164 +
1165 + $value = strval( $value );
1166 + }
1167 +
1168 + // String options that are restricted to specific values.
1169 + $restricted_value_options = array(
1170 + 'custom_taxonomy_section' => Settings_Page::get_section_taxonomies(),
1171 + 'meta_type' => array( 'json_ld', 'repeated_metas' ),
1172 + );
1173 +
1174 + // Verify that the above values are respected.
1175 + foreach ( $restricted_value_options as $option_key => $valid_values ) {
1176 + if ( $option_id === $option_key ) {
1177 + if ( ! in_array( $value, $valid_values, true ) ) {
1178 + _doing_it_wrong(
1179 + __FUNCTION__,
1180 + esc_html(
1181 + sprintf( /* translators: 1: Option value 2: Option ID */
1182 + __( 'The value `%1$s` is not allowed for the managed option `%2$s`.', 'wp-parsely' ),
1183 + $value,
1184 + $option_id
1185 + )
1186 + ),
1187 + ''
1188 + );
1189 +
1190 + $value = $this->option_defaults[ $option_id ];
1191 + }
1192 + }
1193 + }
1194 + }
1195 +
1196 + return $value;
1104 1197 }
1105 1198
1106 1199 /**
1107 - * Determine if an API key is not saved in the options.
1200 + * Allows remote requests to Parse.ly.
1108 1201 *
1109 - * @since 2.6.0
1202 + * This is needed for environments, such as wp-now, that block remote requests.
1110 1203 *
1111 - * @return bool True if API key is missing, false if it is set.
1204 + * @since 3.13.0
1205 + * @since 3.24.2 Matches the Parse.ly hosts exactly, over HTTPS.
1206 + * @access private
1112 1207 */
1113 - public function api_key_is_missing(): bool {
1114 - return ! $this->api_key_is_set();
1115 - }
1208 + private function allow_parsely_remote_requests(): void {
1209 + $allowed_urls = array(
1210 + self::DASHBOARD_BASE_URL,
1211 + Content_API_Service::get_base_url(),
1212 + Suggestions_API_Service::get_base_url(),
1213 + );
1116 1214
1117 - /**
1118 - * Get the API key if set.
1119 - *
1120 - * @since 2.6.0
1121 - *
1122 - * @return string API key if set, or empty string if not.
1123 - */
1124 - public function get_api_key(): string {
1125 - $options = $this->get_options();
1215 + add_filter(
1216 + 'http_request_host_is_external',
1217 + function ( bool $external, string $host, string $url ) use ( $allowed_urls ) {
1218 + $scheme = strtolower( (string) wp_parse_url( $url, PHP_URL_SCHEME ) );
1219 + $allowed_hosts = array_map(
1220 + static function ( string $allowed_url ): string {
1221 + return (string) wp_parse_url( $allowed_url, PHP_URL_HOST );
1222 + },
1223 + $allowed_urls
1224 + );
1126 1225
1127 - return $this->api_key_is_set() ? $options['apikey'] : '';
1226 + if ( 'https' === $scheme && in_array( strtolower( $host ), $allowed_hosts, true ) ) {
1227 + return true;
1228 + }
1229 +
1230 + return $external;
1231 + },
1232 + 10,
1233 + 3
1234 + );
1128 1235 }
1129 1236 }