PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 18.1
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v18.1
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / inc / class-wpseo-utils.php

class-wpseo-utils.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 18.1, at inc/class-wpseo-utils.php

1,421 lines 38.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WPSEO plugin file.
4 *
5 * @package WPSEO\Internals
6 * @since 1.8.0
7 */
8
9 use Yoast\WP\SEO\Integrations\Feature_Flag_Integration;
10
11 /**
12 * Group of utility methods for use by WPSEO.
13 * All methods are static, this is just a sort of namespacing class wrapper.
14 */
15 class WPSEO_Utils {
16
17 /**
18 * Whether the PHP filter extension is enabled.
19 *
20 * @since 1.8.0
21 *
22 * @var bool
23 */
24 public static $has_filters;
25
26 /**
27 * Check whether file editing is allowed for the .htaccess and robots.txt files.
28 *
29 * {@internal current_user_can() checks internally whether a user is on wp-ms and adjusts accordingly.}}
30 *
31 * @since 1.8.0
32 *
33 * @return bool
34 */
35 public static function allow_system_file_edit() {
36 $allowed = true;
37
38 if ( current_user_can( 'edit_files' ) === false ) {
39 $allowed = false;
40 }
41
42 /**
43 * Filter: 'wpseo_allow_system_file_edit' - Allow developers to change whether the editing of
44 * .htaccess and robots.txt is allowed.
45 *
46 * @api bool $allowed Whether file editing is allowed.
47 */
48 return apply_filters( 'wpseo_allow_system_file_edit', $allowed );
49 }
50
51 /**
52 * Check if the web server is running on Apache or compatible (LiteSpeed).
53 *
54 * @since 1.8.0
55 *
56 * @return bool
57 */
58 public static function is_apache() {
59 if ( ! isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
60 return false;
61 }
62
63 $software = sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) );
64
65 return stripos( $software, 'apache' ) !== false || stripos( $software, 'litespeed' ) !== false;
66 }
67
68 /**
69 * Check if the web server is running on Nginx.
70 *
71 * @since 1.8.0
72 *
73 * @return bool
74 */
75 public static function is_nginx() {
76 if ( ! isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
77 return false;
78 }
79
80 $software = sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) );
81
82 return stripos( $software, 'nginx' ) !== false;
83 }
84
85 /**
86 * Check whether a url is relative.
87 *
88 * @since 1.8.0
89 *
90 * @param string $url URL string to check.
91 *
92 * @return bool
93 */
94 public static function is_url_relative( $url ) {
95 return YoastSEO()->helpers->url->is_relative( $url );
96 }
97
98 /**
99 * Recursively trim whitespace round a string value or of string values within an array.
100 * Only trims strings to avoid typecasting a variable (to string).
101 *
102 * @since 1.8.0
103 *
104 * @param mixed $value Value to trim or array of values to trim.
105 *
106 * @return mixed Trimmed value or array of trimmed values.
107 */
108 public static function trim_recursive( $value ) {
109 if ( is_string( $value ) ) {
110 $value = trim( $value );
111 }
112 elseif ( is_array( $value ) ) {
113 $value = array_map( [ __CLASS__, 'trim_recursive' ], $value );
114 }
115
116 return $value;
117 }
118
119 /**
120 * Translates a decimal analysis score into a textual one.
121 *
122 * @since 1.8.0
123 *
124 * @param int $val The decimal score to translate.
125 * @param bool $css_value Whether to return the i18n translated score or the CSS class value.
126 *
127 * @return string
128 */
129 public static function translate_score( $val, $css_value = true ) {
130 $seo_rank = WPSEO_Rank::from_numeric_score( $val );
131
132 if ( $css_value ) {
133 return $seo_rank->get_css_class();
134 }
135
136 return $seo_rank->get_label();
137 }
138
139 /**
140 * Emulate the WP native sanitize_text_field function in a %%variable%% safe way.
141 *
142 * Sanitize a string from user input or from the db.
143 *
144 * - Check for invalid UTF-8;
145 * - Convert single < characters to entity;
146 * - Strip all tags;
147 * - Remove line breaks, tabs and extra white space;
148 * - Strip octets - BUT DO NOT REMOVE (part of) VARIABLES WHICH WILL BE REPLACED.
149 *
150 * @link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/formatting.php for the original.
151 *
152 * @since 1.8.0
153 *
154 * @param string $value String value to sanitize.
155 *
156 * @return string
157 */
158 public static function sanitize_text_field( $value ) {
159 $filtered = wp_check_invalid_utf8( $value );
160
161 if ( strpos( $filtered, '<' ) !== false ) {
162 $filtered = wp_pre_kses_less_than( $filtered );
163 // This will strip extra whitespace for us.
164 $filtered = wp_strip_all_tags( $filtered, true );
165 }
166 else {
167 $filtered = trim( preg_replace( '`[\r\n\t ]+`', ' ', $filtered ) );
168 }
169
170 $found = false;
171 while ( preg_match( '`[^%](%[a-f0-9]{2})`i', $filtered, $match ) ) {
172 $filtered = str_replace( $match[1], '', $filtered );
173 $found = true;
174 }
175 unset( $match );
176
177 if ( $found ) {
178 // Strip out the whitespace that may now exist after removing the octets.
179 $filtered = trim( preg_replace( '` +`', ' ', $filtered ) );
180 }
181
182 /**
183 * Filter a sanitized text field string.
184 *
185 * @since WP 2.9.0
186 *
187 * @param string $filtered The sanitized string.
188 * @param string $str The string prior to being sanitized.
189 */
190 return apply_filters( 'sanitize_text_field', $filtered, $value ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals -- Using WP native filter.
191 }
192
193 /**
194 * Sanitize a url for saving to the database.
195 * Not to be confused with the old native WP function.
196 *
197 * @since 1.8.0
198 *
199 * @param string $value String URL value to sanitize.
200 * @param array $allowed_protocols Optional set of allowed protocols.
201 *
202 * @return string
203 */
204 public static function sanitize_url( $value, $allowed_protocols = [ 'http', 'https' ] ) {
205
206 $url = '';
207 $parts = wp_parse_url( $value );
208
209 if ( isset( $parts['scheme'], $parts['host'] ) ) {
210 $url = $parts['scheme'] . '://';
211
212 if ( isset( $parts['user'] ) ) {
213 $url .= rawurlencode( $parts['user'] );
214 $url .= isset( $parts['pass'] ) ? ':' . rawurlencode( $parts['pass'] ) : '';
215 $url .= '@';
216 }
217
218 $parts['host'] = preg_replace(
219 '`[^a-z0-9-.:\[\]\\x80-\\xff]`',
220 '',
221 strtolower( $parts['host'] )
222 );
223
224 $url .= $parts['host'] . ( isset( $parts['port'] ) ? ':' . intval( $parts['port'] ) : '' );
225 }
226
227 if ( isset( $parts['path'] ) && strpos( $parts['path'], '/' ) === 0 ) {
228 $path = explode( '/', wp_strip_all_tags( $parts['path'] ) );
229 $path = self::sanitize_encoded_text_field( $path );
230 $url .= implode( '/', $path );
231 }
232
233 if ( ! $url ) {
234 return '';
235 }
236
237 if ( isset( $parts['query'] ) ) {
238 wp_parse_str( $parts['query'], $parsed_query );
239
240 $parsed_query = array_combine(
241 self::sanitize_encoded_text_field( array_keys( $parsed_query ) ),
242 self::sanitize_encoded_text_field( array_values( $parsed_query ) )
243 );
244
245 $url = add_query_arg( $parsed_query, $url );
246 }
247
248 if ( isset( $parts['fragment'] ) ) {
249 $url .= '#' . self::sanitize_encoded_text_field( $parts['fragment'] );
250 }
251
252 if ( strpos( $url, '%' ) !== false ) {
253 $url = preg_replace_callback(
254 '`%[a-fA-F0-9]{2}`',
255 static function( $octects ) {
256 return strtolower( $octects[0] );
257 },
258 $url
259 );
260 }
261
262 return esc_url_raw( $url, $allowed_protocols );
263 }
264
265 /**
266 * Decode, sanitize and encode the array of strings or the string.
267 *
268 * @since 13.3
269 *
270 * @param array|string $value The value to sanitize and encode.
271 *
272 * @return array|string The sanitized value.
273 */
274 public static function sanitize_encoded_text_field( $value ) {
275 if ( is_array( $value ) ) {
276 return array_map( [ __CLASS__, 'sanitize_encoded_text_field' ], $value );
277 }
278
279 return rawurlencode( sanitize_text_field( rawurldecode( $value ) ) );
280 }
281
282 /**
283 * Validate a value as boolean.
284 *
285 * @since 1.8.0
286 *
287 * @param mixed $value Value to validate.
288 *
289 * @return bool
290 */
291 public static function validate_bool( $value ) {
292 if ( ! isset( self::$has_filters ) ) {
293 self::$has_filters = extension_loaded( 'filter' );
294 }
295
296 if ( self::$has_filters ) {
297 return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
298 }
299 else {
300 return self::emulate_filter_bool( $value );
301 }
302 }
303
304 /**
305 * Cast a value to bool.
306 *
307 * @since 1.8.0
308 *
309 * @param mixed $value Value to cast.
310 *
311 * @return bool
312 */
313 public static function emulate_filter_bool( $value ) {
314 $true = [
315 '1',
316 'true',
317 'True',
318 'TRUE',
319 'y',
320 'Y',
321 'yes',
322 'Yes',
323 'YES',
324 'on',
325 'On',
326 'ON',
327 ];
328 $false = [
329 '0',
330 'false',
331 'False',
332 'FALSE',
333 'n',
334 'N',
335 'no',
336 'No',
337 'NO',
338 'off',
339 'Off',
340 'OFF',
341 ];
342
343 if ( is_bool( $value ) ) {
344 return $value;
345 }
346 elseif ( is_int( $value ) && ( $value === 0 || $value === 1 ) ) {
347 return (bool) $value;
348 }
349 elseif ( ( is_float( $value ) && ! is_nan( $value ) ) && ( $value === (float) 0 || $value === (float) 1 ) ) {
350 return (bool) $value;
351 }
352 elseif ( is_string( $value ) ) {
353 $value = trim( $value );
354 if ( in_array( $value, $true, true ) ) {
355 return true;
356 }
357 elseif ( in_array( $value, $false, true ) ) {
358 return false;
359 }
360 else {
361 return false;
362 }
363 }
364
365 return false;
366 }
367
368 /**
369 * Validate a value as integer.
370 *
371 * @since 1.8.0
372 *
373 * @param mixed $value Value to validate.
374 *
375 * @return int|bool Int or false in case of failure to convert to int.
376 */
377 public static function validate_int( $value ) {
378 if ( ! isset( self::$has_filters ) ) {
379 self::$has_filters = extension_loaded( 'filter' );
380 }
381
382 if ( self::$has_filters ) {
383 return filter_var( $value, FILTER_VALIDATE_INT );
384 }
385 else {
386 return self::emulate_filter_int( $value );
387 }
388 }
389
390 /**
391 * Cast a value to integer.
392 *
393 * @since 1.8.0
394 *
395 * @param mixed $value Value to cast.
396 *
397 * @return int|bool
398 */
399 public static function emulate_filter_int( $value ) {
400 if ( is_int( $value ) ) {
401 return $value;
402 }
403 elseif ( is_float( $value ) ) {
404 // phpcs:ignore WordPress.PHP.StrictComparisons -- Purposeful loose comparison.
405 if ( (int) $value == $value && ! is_nan( $value ) ) {
406 return (int) $value;
407 }
408 else {
409 return false;
410 }
411 }
412 elseif ( is_string( $value ) ) {
413 $value = trim( $value );
414 if ( $value === '' ) {
415 return false;
416 }
417 elseif ( ctype_digit( $value ) ) {
418 return (int) $value;
419 }
420 elseif ( strpos( $value, '-' ) === 0 && ctype_digit( substr( $value, 1 ) ) ) {
421 return (int) $value;
422 }
423 else {
424 return false;
425 }
426 }
427
428 return false;
429 }
430
431 /**
432 * Clears the WP or W3TC cache depending on which is used.
433 *
434 * @since 1.8.0
435 */
436 public static function clear_cache() {
437 if ( function_exists( 'w3tc_pgcache_flush' ) ) {
438 w3tc_pgcache_flush();
439 }
440 elseif ( function_exists( 'wp_cache_clear_cache' ) ) {
441 wp_cache_clear_cache();
442 }
443 }
444
445 /**
446 * Clear rewrite rules.
447 *
448 * @since 1.8.0
449 */
450 public static function clear_rewrites() {
451 delete_option( 'rewrite_rules' );
452 }
453
454 /**
455 * Do simple reliable math calculations without the risk of wrong results.
456 *
457 * In the rare case that the bcmath extension would not be loaded, it will return the normal calculation results.
458 *
459 * @link http://floating-point-gui.de/
460 * @link http://php.net/language.types.float.php See the big red warning.
461 *
462 * @since 1.5.0
463 * @since 1.8.0 Moved from stand-alone function to this class.
464 *
465 * @param mixed $number1 Scalar (string/int/float/bool).
466 * @param string $action Calculation action to execute. Valid input:
467 * '+' or 'add' or 'addition',
468 * '-' or 'sub' or 'subtract',
469 * '*' or 'mul' or 'multiply',
470 * '/' or 'div' or 'divide',
471 * '%' or 'mod' or 'modulus'
472 * '=' or 'comp' or 'compare'.
473 * @param mixed $number2 Scalar (string/int/float/bool).
474 * @param bool $round Whether or not to round the result. Defaults to false.
475 * Will be disregarded for a compare operation.
476 * @param int $decimals Decimals for rounding operation. Defaults to 0.
477 * @param int $precision Calculation precision. Defaults to 10.
478 *
479 * @return mixed Calculation Result or false if either or the numbers isn't scalar or
480 * an invalid operation was passed.
481 * - For compare the result will always be an integer.
482 * - For all other operations, the result will either be an integer (preferred)
483 * or a float.
484 */
485 public static function calc( $number1, $action, $number2, $round = false, $decimals = 0, $precision = 10 ) {
486 static $bc;
487
488 if ( ! is_scalar( $number1 ) || ! is_scalar( $number2 ) ) {
489 return false;
490 }
491
492 if ( ! isset( $bc ) ) {
493 $bc = extension_loaded( 'bcmath' );
494 }
495
496 if ( $bc ) {
497 $number1 = number_format( $number1, 10, '.', '' );
498 $number2 = number_format( $number2, 10, '.', '' );
499 }
500
501 $result = null;
502 $compare = false;
503
504 switch ( $action ) {
505 case '+':
506 case 'add':
507 case 'addition':
508 $result = ( $bc ) ? bcadd( $number1, $number2, $precision ) /* string */ : ( $number1 + $number2 );
509 break;
510
511 case '-':
512 case 'sub':
513 case 'subtract':
514 $result = ( $bc ) ? bcsub( $number1, $number2, $precision ) /* string */ : ( $number1 - $number2 );
515 break;
516
517 case '*':
518 case 'mul':
519 case 'multiply':
520 $result = ( $bc ) ? bcmul( $number1, $number2, $precision ) /* string */ : ( $number1 * $number2 );
521 break;
522
523 case '/':
524 case 'div':
525 case 'divide':
526 if ( $bc ) {
527 $result = bcdiv( $number1, $number2, $precision ); // String, or NULL if right_operand is 0.
528 }
529 elseif ( $number2 != 0 ) { // phpcs:ignore WordPress.PHP.StrictComparisons -- Purposeful loose comparison.
530 $result = ( $number1 / $number2 );
531 }
532
533 if ( ! isset( $result ) ) {
534 $result = 0;
535 }
536 break;
537
538 case '%':
539 case 'mod':
540 case 'modulus':
541 if ( $bc ) {
542 $result = bcmod( $number1, $number2 ); // String, or NULL if modulus is 0.
543 }
544 elseif ( $number2 != 0 ) { // phpcs:ignore WordPress.PHP.StrictComparisons -- Purposeful loose comparison.
545 $result = ( $number1 % $number2 );
546 }
547
548 if ( ! isset( $result ) ) {
549 $result = 0;
550 }
551 break;
552
553 case '=':
554 case 'comp':
555 case 'compare':
556 $compare = true;
557 if ( $bc ) {
558 $result = bccomp( $number1, $number2, $precision ); // Returns int 0, 1 or -1.
559 }
560 else {
561 // phpcs:ignore WordPress.PHP.StrictComparisons -- Purposeful loose comparison.
562 $result = ( $number1 == $number2 ) ? 0 : ( ( $number1 > $number2 ) ? 1 : -1 );
563 }
564 break;
565 }
566
567 if ( isset( $result ) ) {
568 if ( $compare === false ) {
569 if ( $round === true ) {
570 $result = round( floatval( $result ), $decimals );
571 if ( $decimals === 0 ) {
572 $result = (int) $result;
573 }
574 }
575 else {
576 // phpcs:ignore WordPress.PHP.StrictComparisons -- Purposeful loose comparison.
577 $result = ( intval( $result ) == $result ) ? intval( $result ) : floatval( $result );
578 }
579 }
580
581 return $result;
582 }
583
584 return false;
585 }
586
587 /**
588 * Trim whitespace and NBSP (Non-breaking space) from string.
589 *
590 * @since 2.0.0
591 *
592 * @param string $text String input to trim.
593 *
594 * @return string
595 */
596 public static function trim_nbsp_from_string( $text ) {
597 $find = [ '&nbsp;', chr( 0xC2 ) . chr( 0xA0 ) ];
598 $text = str_replace( $find, ' ', $text );
599 $text = trim( $text );
600
601 return $text;
602 }
603
604 /**
605 * Check if a string is a valid datetime.
606 *
607 * @since 2.0.0
608 *
609 * @param string $datetime String input to check as valid input for DateTime class.
610 *
611 * @return bool
612 */
613 public static function is_valid_datetime( $datetime ) {
614 return YoastSEO()->helpers->date->is_valid_datetime( $datetime );
615 }
616
617 /**
618 * Format the URL to be sure it is okay for using as a redirect url.
619 *
620 * This method will parse the URL and combine them in one string.
621 *
622 * @since 2.3.0
623 *
624 * @param string $url URL string.
625 *
626 * @return mixed
627 */
628 public static function format_url( $url ) {
629 $parsed_url = wp_parse_url( $url );
630
631 $formatted_url = '';
632 if ( ! empty( $parsed_url['path'] ) ) {
633 $formatted_url = $parsed_url['path'];
634 }
635
636 // Prepend a slash if first char != slash.
637 if ( stripos( $formatted_url, '/' ) !== 0 ) {
638 $formatted_url = '/' . $formatted_url;
639 }
640
641 // Append 'query' string if it exists.
642 if ( ! empty( $parsed_url['query'] ) ) {
643 $formatted_url .= '?' . $parsed_url['query'];
644 }
645
646 return apply_filters( 'wpseo_format_admin_url', $formatted_url );
647 }
648
649 /**
650 * Retrieves the sitename.
651 *
652 * @since 3.0.0
653 *
654 * @return string
655 */
656 public static function get_site_name() {
657 return YoastSEO()->helpers->site->get_site_name();
658 }
659
660 /**
661 * Check if the current opened page is a Yoast SEO page.
662 *
663 * @since 3.0.0
664 *
665 * @return bool
666 */
667 public static function is_yoast_seo_page() {
668 return YoastSEO()->helpers->current_page->is_yoast_seo_page();
669 }
670
671 /**
672 * Check if the current opened page belongs to Yoast SEO Free.
673 *
674 * @since 3.3.0
675 *
676 * @param string $current_page The current page the user is on.
677 *
678 * @return bool
679 */
680 public static function is_yoast_seo_free_page( $current_page ) {
681 $yoast_seo_free_pages = [
682 'wpseo_dashboard',
683 'wpseo_titles',
684 'wpseo_social',
685 'wpseo_advanced',
686 'wpseo_tools',
687 'wpseo_search_console',
688 'wpseo_licenses',
689 ];
690
691 return in_array( $current_page, $yoast_seo_free_pages, true );
692 }
693
694 /**
695 * Checks if we are in the premium or free plugin.
696 *
697 * @deprecated 16.0
698 * @codeCoverageIgnore
699 *
700 * @return bool True when we are in the premium plugin.
701 */
702 public static function is_yoast_seo_premium() {
703 _deprecated_function( __FUNCTION__, '16.0', 'YoastSEO()->helpers->product->is_premium' );
704 return YoastSEO()->helpers->product->is_premium();
705 }
706
707 /**
708 * Determine if Yoast SEO is in development mode?
709 *
710 * Inspired by JetPack (https://github.com/Automattic/jetpack/blob/master/class.jetpack.php#L1383-L1406).
711 *
712 * @since 3.0.0
713 *
714 * @return bool
715 */
716 public static function is_development_mode() {
717 $development_mode = false;
718
719 if ( defined( 'YOAST_ENVIRONMENT' ) && YOAST_ENVIRONMENT === 'development' ) {
720 $development_mode = true;
721 }
722 elseif ( defined( 'WPSEO_DEBUG' ) ) {
723 $development_mode = WPSEO_DEBUG;
724 }
725 elseif ( site_url() && strpos( site_url(), '.' ) === false ) {
726 $development_mode = true;
727 }
728
729 /**
730 * Filter the Yoast SEO development mode.
731 *
732 * @since 3.0
733 *
734 * @param bool $development_mode Is Yoast SEOs development mode active.
735 */
736 return apply_filters( 'yoast_seo_development_mode', $development_mode );
737 }
738
739 /**
740 * Retrieve home URL with proper trailing slash.
741 *
742 * @since 3.3.0
743 *
744 * @param string $path Path relative to home URL.
745 * @param string|null $scheme Scheme to apply.
746 *
747 * @return string Home URL with optional path, appropriately slashed if not.
748 */
749 public static function home_url( $path = '', $scheme = null ) {
750 return YoastSEO()->helpers->url->home( $path, $scheme );
751 }
752
753 /**
754 * Checks if the WP-REST-API is available.
755 *
756 * @since 3.6
757 * @since 3.7 Introduced the $minimum_version parameter.
758 *
759 * @param string $minimum_version The minimum version the API should be.
760 *
761 * @return bool Returns true if the API is available.
762 */
763 public static function is_api_available( $minimum_version = '2.0' ) {
764 return ( defined( 'REST_API_VERSION' )
765 && version_compare( REST_API_VERSION, $minimum_version, '>=' ) );
766 }
767
768 /**
769 * Determine whether or not the metabox should be displayed for a post type.
770 *
771 * @param string|null $post_type Optional. The post type to check the visibility of the metabox for.
772 *
773 * @return bool Whether or not the metabox should be displayed.
774 */
775 protected static function display_post_type_metabox( $post_type = null ) {
776 if ( ! isset( $post_type ) ) {
777 $post_type = get_post_type();
778 }
779
780 if ( ! isset( $post_type ) || ! WPSEO_Post_Type::is_post_type_accessible( $post_type ) ) {
781 return false;
782 }
783
784 if ( $post_type === 'attachment' && WPSEO_Options::get( 'disable-attachment' ) ) {
785 return false;
786 }
787
788 return apply_filters( 'wpseo_enable_editor_features_' . $post_type, WPSEO_Options::get( 'display-metabox-pt-' . $post_type ) );
789 }
790
791 /**
792 * Determine whether or not the metabox should be displayed for a taxonomy.
793 *
794 * @param string|null $taxonomy Optional. The post type to check the visibility of the metabox for.
795 *
796 * @return bool Whether or not the metabox should be displayed.
797 */
798 protected static function display_taxonomy_metabox( $taxonomy = null ) {
799 if ( ! isset( $taxonomy ) || ! in_array( $taxonomy, get_taxonomies( [ 'public' => true ], 'names' ), true ) ) {
800 return false;
801 }
802
803 return WPSEO_Options::get( 'display-metabox-tax-' . $taxonomy );
804 }
805
806 /**
807 * Determines whether the metabox is active for the given identifier and type.
808 *
809 * @param string $identifier The identifier to check for.
810 * @param string $type The type to check for.
811 *
812 * @return bool Whether or not the metabox is active.
813 */
814 public static function is_metabox_active( $identifier, $type ) {
815 if ( $type === 'post_type' ) {
816 return self::display_post_type_metabox( $identifier );
817 }
818
819 if ( $type === 'taxonomy' ) {
820 return self::display_taxonomy_metabox( $identifier );
821 }
822
823 return false;
824 }
825
826 /**
827 * Determines whether the plugin is active for the entire network.
828 *
829 * @return bool Whether or not the plugin is network-active.
830 */
831 public static function is_plugin_network_active() {
832 return YoastSEO()->helpers->url->is_plugin_network_active();
833 }
834
835 /**
836 * Gets the type of the current post.
837 *
838 * @return string The post type, or an empty string.
839 */
840 public static function get_post_type() {
841 global $post;
842
843 if ( isset( $post->post_type ) ) {
844 return $post->post_type;
845 }
846 elseif ( isset( $_GET['post_type'] ) ) {
847 return sanitize_text_field( wp_unslash( $_GET['post_type'] ) );
848 }
849
850 return '';
851 }
852
853 /**
854 * Gets the type of the current page.
855 *
856 * @return string Returns 'post' if the current page is a post edit page. Taxonomy in other cases.
857 */
858 public static function get_page_type() {
859 global $pagenow;
860 if ( WPSEO_Metabox::is_post_edit( $pagenow ) ) {
861 return 'post';
862 }
863
864 return 'taxonomy';
865 }
866
867 /**
868 * Getter for the Adminl10n array. Applies the wpseo_admin_l10n filter.
869 *
870 * @return array The Adminl10n array.
871 */
872 public static function get_admin_l10n() {
873 $post_type = self::get_post_type();
874 $page_type = self::get_page_type();
875
876 $label_object = false;
877 $no_index = false;
878
879 if ( $page_type === 'post' ) {
880 $label_object = get_post_type_object( $post_type );
881 $no_index = WPSEO_Options::get( 'noindex-' . $post_type, false );
882 }
883 else {
884 $label_object = WPSEO_Taxonomy::get_labels();
885
886 $taxonomy_slug = filter_input( INPUT_GET, 'taxonomy', FILTER_DEFAULT, [ 'options' => [ 'default' => '' ] ] );
887 $no_index = WPSEO_Options::get( 'noindex-tax-' . $taxonomy_slug, false );
888 }
889
890 $wpseo_admin_l10n = [
891 'displayAdvancedTab' => WPSEO_Capability_Utils::current_user_can( 'wpseo_edit_advanced_metadata' ) || ! WPSEO_Options::get( 'disableadvanced_meta' ),
892 'noIndex' => (bool) $no_index,
893 'isPostType' => (bool) get_post_type(),
894 'postType' => get_post_type(),
895 'postTypeNamePlural' => ( $page_type === 'post' ) ? $label_object->label : $label_object->name,
896 'postTypeNameSingular' => ( $page_type === 'post' ) ? $label_object->labels->singular_name : $label_object->singular_name,
897 'isBreadcrumbsDisabled' => WPSEO_Options::get( 'breadcrumbs-enable', false ) !== true && ! current_theme_supports( 'yoast-seo-breadcrumbs' ),
898 // phpcs:ignore Generic.ControlStructures.DisallowYodaConditions -- Bug: squizlabs/PHP_CodeSniffer#2962.
899 'isPrivateBlog' => ( (string) get_option( 'blog_public' ) ) === '0',
900 ];
901
902 $additional_entries = apply_filters( 'wpseo_admin_l10n', [] );
903 if ( is_array( $additional_entries ) ) {
904 $wpseo_admin_l10n = array_merge( $wpseo_admin_l10n, $additional_entries );
905 }
906
907 return $wpseo_admin_l10n;
908 }
909
910 /**
911 * Retrieves the analysis worker log level. Defaults to errors only.
912 *
913 * Uses bool YOAST_SEO_DEBUG as flag to enable logging. Off equals ERROR.
914 * Uses string YOAST_SEO_DEBUG_ANALYSIS_WORKER as log level for the Analysis
915 * Worker. Defaults to INFO.
916 * Can be: TRACE, DEBUG, INFO, WARN or ERROR.
917 *
918 * @return string The log level to use.
919 */
920 public static function get_analysis_worker_log_level() {
921 if ( defined( 'YOAST_SEO_DEBUG' ) && YOAST_SEO_DEBUG ) {
922 return defined( 'YOAST_SEO_DEBUG_ANALYSIS_WORKER' ) ? YOAST_SEO_DEBUG_ANALYSIS_WORKER : 'INFO';
923 }
924
925 return 'ERROR';
926 }
927
928 /**
929 * Returns the unfiltered home URL.
930 *
931 * In case WPML is installed, returns the original home_url and not the WPML version.
932 * In case of a multisite setup we return the network_home_url.
933 *
934 * @codeCoverageIgnore
935 *
936 * @return string The home url.
937 */
938 public static function get_home_url() {
939 return YoastSEO()->helpers->url->network_safe_home_url();
940 }
941
942 /**
943 * Prepares data for outputting as JSON.
944 *
945 * @param array $data The data to format.
946 *
947 * @return false|string The prepared JSON string.
948 */
949 public static function format_json_encode( $data ) {
950 $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
951
952 if ( self::is_development_mode() ) {
953 $flags = ( $flags | JSON_PRETTY_PRINT );
954
955 /**
956 * Filter the Yoast SEO development mode.
957 *
958 * @api array $data Allows filtering of the JSON data for debug purposes.
959 */
960 $data = apply_filters( 'wpseo_debug_json_data', $data );
961 }
962
963 // phpcs:ignore Yoast.Yoast.AlternativeFunctions.json_encode_wp_json_encodeWithAdditionalParams -- This is the definition of format_json_encode.
964 return wp_json_encode( $data, $flags );
965 }
966
967 /**
968 * Extends the allowed post tags with accessibility-related attributes.
969 *
970 * @codeCoverageIgnore
971 *
972 * @param array $allowed_post_tags The allowed post tags.
973 *
974 * @return array The allowed tags including post tags, input tags and select tags.
975 */
976 public static function extend_kses_post_with_a11y( $allowed_post_tags ) {
977 static $a11y_tags;
978
979 if ( isset( $a11y_tags ) === false ) {
980 $a11y_tags = [
981 'button' => [
982 'aria-expanded' => true,
983 'aria-controls' => true,
984 ],
985 'div' => [
986 'tabindex' => true,
987 ],
988 // Below are attributes that are needed for backwards compatibility (WP < 5.1).
989 'span' => [
990 'aria-hidden' => true,
991 ],
992 'input' => [
993 'aria-describedby' => true,
994 ],
995 'select' => [
996 'aria-describedby' => true,
997 ],
998 'textarea' => [
999 'aria-describedby' => true,
1000 ],
1001 ];
1002
1003 // Add the global allowed attributes to each html element.
1004 $a11y_tags = array_map( '_wp_add_global_attributes', $a11y_tags );
1005 }
1006
1007 return array_merge_recursive( $allowed_post_tags, $a11y_tags );
1008 }
1009
1010 /**
1011 * Extends the allowed post tags with input, select and option tags.
1012 *
1013 * @codeCoverageIgnore
1014 *
1015 * @param array $allowed_post_tags The allowed post tags.
1016 *
1017 * @return array The allowed tags including post tags, input tags, select tags and option tags.
1018 */
1019 public static function extend_kses_post_with_forms( $allowed_post_tags ) {
1020 static $input_tags;
1021
1022 if ( isset( $input_tags ) === false ) {
1023 $input_tags = [
1024 'input' => [
1025 'accept' => true,
1026 'accesskey' => true,
1027 'align' => true,
1028 'alt' => true,
1029 'autocomplete' => true,
1030 'autofocus' => true,
1031 'checked' => true,
1032 'contenteditable' => true,
1033 'dirname' => true,
1034 'disabled' => true,
1035 'draggable' => true,
1036 'dropzone' => true,
1037 'form' => true,
1038 'formaction' => true,
1039 'formenctype' => true,
1040 'formmethod' => true,
1041 'formnovalidate' => true,
1042 'formtarget' => true,
1043 'height' => true,
1044 'hidden' => true,
1045 'lang' => true,
1046 'list' => true,
1047 'max' => true,
1048 'maxlength' => true,
1049 'min' => true,
1050 'multiple' => true,
1051 'name' => true,
1052 'pattern' => true,
1053 'placeholder' => true,
1054 'readonly' => true,
1055 'required' => true,
1056 'size' => true,
1057 'spellcheck' => true,
1058 'src' => true,
1059 'step' => true,
1060 'tabindex' => true,
1061 'translate' => true,
1062 'type' => true,
1063 'value' => true,
1064 'width' => true,
1065
1066 /*
1067 * Below are attributes that are needed for backwards compatibility (WP < 5.1).
1068 * They are used for the social media image in the metabox.
1069 * These can be removed once we move to the React versions of the social previews.
1070 */
1071 'data-target' => true,
1072 'data-target-id' => true,
1073 ],
1074 'select' => [
1075 'accesskey' => true,
1076 'autofocus' => true,
1077 'contenteditable' => true,
1078 'disabled' => true,
1079 'draggable' => true,
1080 'dropzone' => true,
1081 'form' => true,
1082 'hidden' => true,
1083 'lang' => true,
1084 'multiple' => true,
1085 'name' => true,
1086 'onblur' => true,
1087 'onchange' => true,
1088 'oncontextmenu' => true,
1089 'onfocus' => true,
1090 'oninput' => true,
1091 'oninvalid' => true,
1092 'onreset' => true,
1093 'onsearch' => true,
1094 'onselect' => true,
1095 'onsubmit' => true,
1096 'required' => true,
1097 'size' => true,
1098 'spellcheck' => true,
1099 'tabindex' => true,
1100 'translate' => true,
1101 ],
1102 'option' => [
1103 'class' => true,
1104 'disabled' => true,
1105 'id' => true,
1106 'label' => true,
1107 'selected' => true,
1108 'value' => true,
1109 ],
1110 ];
1111
1112 // Add the global allowed attributes to each html element.
1113 $input_tags = array_map( '_wp_add_global_attributes', $input_tags );
1114 }
1115
1116 return array_merge_recursive( $allowed_post_tags, $input_tags );
1117 }
1118
1119 /**
1120 * Gets an array of enabled features.
1121 *
1122 * @return string[] The array of enabled features.
1123 */
1124 public static function retrieve_enabled_features() {
1125 /**
1126 * The feature flag integration.
1127 *
1128 * @var Feature_Flag_Integration $feature_flag_integration;
1129 */
1130 $feature_flag_integration = YoastSEO()->classes->get( Feature_Flag_Integration::class );
1131 return $feature_flag_integration->get_enabled_features();
1132 }
1133
1134 /* ********************* DEPRECATED METHODS ********************* */
1135
1136 /**
1137 * List all the available user roles.
1138 *
1139 * @since 1.8.0
1140 * @deprecated 15.0
1141 * @codeCoverageIgnore
1142 *
1143 * @return array
1144 */
1145 public static function get_roles() {
1146 _deprecated_function( __METHOD__, '15.0', 'wp_roles()->get_names()' );
1147 $yoast_seo_wp_roles = wp_roles();
1148
1149 $roles = $yoast_seo_wp_roles->get_names();
1150
1151 return $roles;
1152 }
1153
1154 /**
1155 * Checks if the current installation supports MyYoast access tokens.
1156 *
1157 * @deprecated 15.0
1158 * @codeCoverageIgnore
1159 *
1160 * @return bool True if access_tokens are supported.
1161 */
1162 public static function has_access_token_support() {
1163 _deprecated_function( __METHOD__, 'WPSEO 15.0' );
1164 return false;
1165 }
1166
1167 /**
1168 * Standardize whitespace in a string.
1169 *
1170 * Replace line breaks, carriage returns, tabs with a space, then remove double spaces.
1171 *
1172 * @since 1.8.0
1173 * @deprecated 15.2
1174 * @codeCoverageIgnore
1175 *
1176 * @param string $text String input to standardize.
1177 *
1178 * @return string
1179 */
1180 public static function standardize_whitespace( $text ) {
1181 _deprecated_function( __METHOD__, 'WPSEO 15.2' );
1182
1183 return YoastSEO()->helpers->string->standardize_whitespace( $text );
1184 }
1185
1186 /**
1187 * First strip out registered and enclosing shortcodes using native WordPress strip_shortcodes function.
1188 * Then strip out the shortcodes with a filthy regex, because people don't properly register their shortcodes.
1189 *
1190 * @since 1.8.0
1191 * @deprecated 15.2
1192 * @codeCoverageIgnore
1193 *
1194 * @param string $text Input string that might contain shortcodes.
1195 *
1196 * @return string String without shortcodes.
1197 */
1198 public static function strip_shortcode( $text ) {
1199 _deprecated_function( __METHOD__, 'WPSEO 15.2' );
1200
1201 return YoastSEO()->helpers->string->strip_shortcode( $text );
1202 }
1203
1204 /**
1205 * Retrieves the title separator.
1206 *
1207 * @since 3.0.0
1208 * @deprecated 15.2
1209 * @codeCoverageIgnore
1210 *
1211 * @return string
1212 */
1213 public static function get_title_separator() {
1214 _deprecated_function( __METHOD__, 'WPSEO 15.2', 'Yoast\WP\SEO\Helpers\Options_Helper::get_title_separator' );
1215
1216 return YoastSEO()->helpers->options->get_title_separator();
1217 }
1218
1219 /**
1220 * Flush W3TC cache after successful update/add of taxonomy meta option.
1221 *
1222 * @since 1.8.0
1223 * @deprecated 15.3
1224 * @codeCoverageIgnore
1225 */
1226 public static function flush_w3tc_cache() {
1227 _deprecated_function( __METHOD__, 'WPSEO 15.3' );
1228 }
1229
1230 /**
1231 * Determines whether or not WooCommerce is active.
1232 *
1233 * @deprecated 15.3
1234 * @codeCoverageIgnore
1235 *
1236 * @return bool Whether or not WooCommerce is active.
1237 */
1238 public static function is_woocommerce_active() {
1239 _deprecated_function( __METHOD__, 'WPSEO 15.3' );
1240
1241 return YoastSEO()->helpers->woocommerce->is_active();
1242 }
1243
1244 /**
1245 * Outputs a Schema blob.
1246 *
1247 * @deprecated 15.5
1248 * @codeCoverageIgnore
1249 *
1250 * @param array $graph The Schema graph array to output.
1251 * @param string $class_to_add The (optional) class to add to the script tag.
1252 *
1253 * @return bool
1254 */
1255 public static function schema_output( $graph, $class_to_add = 'yoast-schema-graph' ) {
1256 _deprecated_function( __METHOD__, 'WPSEO 15.5' );
1257
1258 if ( ! is_array( $graph ) || empty( $graph ) ) {
1259 return false;
1260 }
1261
1262 // phpcs:ignore WordPress.Security.EscapeOutput -- Escaping happens in WPSEO_Utils::schema_tag, which should be whitelisted.
1263 echo self::schema_tag( $graph, $class_to_add );
1264 return true;
1265 }
1266
1267 /**
1268 * Returns a script tag with Schema blob.
1269 *
1270 * @deprecated 15.5
1271 * @codeCoverageIgnore
1272 *
1273 * @param array $graph The Schema graph array to output.
1274 * @param string $class_to_add The (optional) class to add to the script tag.
1275 *
1276 * @return false|string A schema blob with script tags.
1277 */
1278 public static function schema_tag( $graph, $class_to_add = 'yoast-schema-graph' ) {
1279 _deprecated_function( __METHOD__, 'WPSEO 15.5' );
1280
1281 if ( ! is_array( $graph ) || empty( $graph ) ) {
1282 return false;
1283 }
1284
1285 $output = [
1286 '@context' => 'https://schema.org',
1287 '@graph' => $graph,
1288 ];
1289 return "<script type='application/ld+json' class='" . esc_attr( $class_to_add ) . "'>" . self::format_json_encode( $output ) . '</script>' . "\n";
1290 }
1291
1292 /**
1293 * Returns the SVG for the traffic light in the metabox.
1294 *
1295 * @deprecated 15.5
1296 * @codeCoverageIgnore
1297 *
1298 * @return string
1299 */
1300 public static function traffic_light_svg() {
1301 _deprecated_function( __METHOD__, 'WPSEO 15.5' );
1302
1303 return <<<'SVG'
1304 <svg class="yst-traffic-light init" version="1.1" xmlns="http://www.w3.org/2000/svg"
1305 role="img" aria-hidden="true" focusable="false"
1306 x="0px" y="0px" viewBox="0 0 30 47" enable-background="new 0 0 30 47" xml:space="preserve">
1307 <g id="BG_1_">
1308 </g>
1309 <g id="traffic_light">
1310 <g>
1311 <g>
1312 <g>
1313 <path fill="#5B2942" d="M22,0H8C3.6,0,0,3.6,0,7.9v31.1C0,43.4,3.6,47,8,47h14c4.4,0,8-3.6,8-7.9V7.9C30,3.6,26.4,0,22,0z
1314 M27.5,38.8c0,3.1-2.6,5.7-5.8,5.7H8.3c-3.2,0-5.8-2.5-5.8-5.7V8.3c0-1.5,0.6-2.9,1.7-4c1.1-1,2.5-1.6,4.1-1.6h13.4
1315 c1.5,0,3,0.6,4.1,1.6c1.1,1.1,1.7,2.5,1.7,4V38.8z"/>
1316 </g>
1317 <g class="traffic-light-color traffic-light-red">
1318 <ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
1319 <ellipse fill="#DC3232" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
1320 <ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
1321 </g>
1322 <g class="traffic-light-color traffic-light-orange">
1323 <ellipse fill="#F49A00" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
1324 <ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
1325 <ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
1326 </g>
1327 <g class="traffic-light-color traffic-light-green">
1328 <ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
1329 <ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
1330 <ellipse fill="#63B22B" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
1331 </g>
1332 <g class="traffic-light-color traffic-light-empty">
1333 <ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
1334 <ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
1335 <ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
1336 </g>
1337 <g class="traffic-light-color traffic-light-init">
1338 <ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
1339 <ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
1340 <ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
1341 </g>
1342 </g>
1343 </g>
1344 </g>
1345 </svg>
1346 SVG;
1347 }
1348
1349 /**
1350 * Gets the plugin name from file.
1351 *
1352 * @since 2.3.3
1353 * @deprecated 15.5
1354 * @codeCoverageIgnore
1355 *
1356 * @param string $plugin Plugin path relative to plugins directory.
1357 *
1358 * @return string|bool
1359 */
1360 public static function get_plugin_name( $plugin ) {
1361 _deprecated_function( __METHOD__, 'WPSEO 15.5' );
1362
1363 $plugin_details = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
1364
1365 if ( $plugin_details['Name'] !== '' ) {
1366 return $plugin_details['Name'];
1367 }
1368
1369 return false;
1370 }
1371
1372 /**
1373 * Returns a base64 URL for the svg for use in the menu.
1374 *
1375 * @since 3.3.0
1376 * @deprecated 15.5
1377 * @codeCoverageIgnore
1378 *
1379 * @param bool $base64 Whether or not to return base64'd output.
1380 *
1381 * @return string
1382 */
1383 public static function get_icon_svg( $base64 = true ) {
1384 _deprecated_function( __METHOD__, 'WPSEO 15.5' );
1385
1386 $svg = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="100%" height="100%" style="fill:#82878c" viewBox="0 0 512 512" role="img" aria-hidden="true" focusable="false"><g><g><g><g><path d="M203.6,395c6.8-17.4,6.8-36.6,0-54l-79.4-204h70.9l47.7,149.4l74.8-207.6H116.4c-41.8,0-76,34.2-76,76V357c0,41.8,34.2,76,76,76H173C189,424.1,197.6,410.3,203.6,395z"/></g><g><path d="M471.6,154.8c0-41.8-34.2-76-76-76h-3L285.7,365c-9.6,26.7-19.4,49.3-30.3,68h216.2V154.8z"/></g></g><path stroke-width="2.974" stroke-miterlimit="10" d="M338,1.3l-93.3,259.1l-42.1-131.9h-89.1l83.8,215.2c6,15.5,6,32.5,0,48c-7.4,19-19,37.3-53,41.9l-7.2,1v76h8.3c81.7,0,118.9-57.2,149.6-142.9L431.6,1.3H338z M279.4,362c-32.9,92-67.6,128.7-125.7,131.8v-45c37.5-7.5,51.3-31,59.1-51.1c7.5-19.3,7.5-40.7,0-60l-75-192.7h52.8l53.3,166.8l105.9-294h58.1L279.4,362z"/></g></g></svg>';
1387
1388 if ( $base64 ) {
1389 //phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- This encoding is intended.
1390 return 'data:image/svg+xml;base64,' . base64_encode( $svg );
1391 }
1392
1393 return $svg;
1394 }
1395
1396 /**
1397 * Checks whether the current user is allowed to access the configuration.
1398 *
1399 * @since 1.8.0
1400 * @deprecated 15.5
1401 * @codeCoverageIgnore
1402 *
1403 * @return bool
1404 */
1405 public static function grant_access() {
1406 _deprecated_function( __METHOD__, 'WPSEO 15.5' );
1407
1408 if ( ! is_multisite() ) {
1409 return true;
1410 }
1411
1412 $options = get_site_option( 'wpseo_ms' );
1413
1414 if ( empty( $options['access'] ) || $options['access'] === 'admin' ) {
1415 return current_user_can( 'wpseo_manage_options' );
1416 }
1417
1418 return is_super_admin();
1419 }
1420 }
1421