PluginProbe
Elementor Website Builder – more than just a page builder / 3.6.3
Elementor Website Builder – more than just a page builder v3.6.3
4.3.0-beta2 4.3.0-beta1 4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.5 4.2.0-beta2 4.2.0-dev2 4.2.0-beta1 4.1.4 4.1.3 4.1.2 4.1.1 4.1.0 4.1.0-beta3 4.1.0-dev3 4.0.9 4.1.0-beta2 4.1.0-dev2 4.0.8 4.1.0-beta1 4.1.0-dev1 4.0.7 All 451 releases
elementor / includes / utils.php

utils.php in Elementor Website Builder – more than just a page builder 3.6.3, at includes/utils.php

783 lines 19.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Elementor;
3
4 use Elementor\Core\Utils\Collection;
5
6 if ( ! defined( 'ABSPATH' ) ) {
7 exit; // Exit if accessed directly.
8 }
9
10 /**
11 * Elementor utils.
12 *
13 * Elementor utils handler class is responsible for different utility methods
14 * used by Elementor.
15 *
16 * @since 1.0.0
17 */
18 class Utils {
19
20 const DEPRECATION_RANGE = 0.4;
21
22 const EDITOR_BREAK_LINES_OPTION_KEY = 'elementor_editor_break_lines';
23
24 /**
25 * A list of safe tage for `validate_html_tag` method.
26 */
27 const ALLOWED_HTML_WRAPPER_TAGS = [
28 'a',
29 'article',
30 'aside',
31 'button',
32 'div',
33 'footer',
34 'h1',
35 'h2',
36 'h3',
37 'h4',
38 'h5',
39 'h6',
40 'header',
41 'main',
42 'nav',
43 'p',
44 'section',
45 'span',
46 ];
47
48 const EXTENDED_ALLOWED_HTML_TAGS = [
49 'iframe' => [
50 'iframe' => [
51 'allow' => true,
52 'allowfullscreen' => true,
53 'frameborder' => true,
54 'height' => true,
55 'loading' => true,
56 'name' => true,
57 'referrerpolicy' => true,
58 'sandbox' => true,
59 'src' => true,
60 'width' => true,
61 ],
62 ],
63 'svg' => [
64 'svg' => [
65 'aria-hidden' => true,
66 'aria-labelledby' => true,
67 'class' => true,
68 'height' => true,
69 'role' => true,
70 'viewbox' => true,
71 'width' => true,
72 'xmlns' => true,
73 ],
74 'g' => [
75 'fill' => true,
76 ],
77 'title' => [
78 'title' => true,
79 ],
80 'path' => [
81 'd' => true,
82 'fill' => true,
83 ],
84 ],
85 'image' => [
86 'img' => [
87 'srcset' => true,
88 'sizes' => true,
89 ],
90 ],
91 ];
92
93 /**
94 * Is WP CLI.
95 *
96 * @return bool
97 */
98 public static function is_wp_cli() {
99 return defined( 'WP_CLI' ) && WP_CLI;
100 }
101
102 /**
103 * Is script debug.
104 *
105 * Whether script debug is enabled or not.
106 *
107 * @since 1.0.0
108 * @access public
109 * @static
110 *
111 * @return bool True if it's a script debug is active, false otherwise.
112 */
113 public static function is_script_debug() {
114 return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
115 }
116
117 /**
118 * Get pro link.
119 *
120 * Retrieve the link to Elementor Pro.
121 *
122 * @since 1.7.0
123 * @access public
124 * @static
125 *
126 * @param string $link URL to Elementor pro.
127 *
128 * @return string Elementor pro link.
129 */
130 public static function get_pro_link( $link ) {
131 static $theme_name = false;
132
133 if ( ! $theme_name ) {
134 $theme_obj = wp_get_theme();
135 if ( $theme_obj->parent() ) {
136 $theme_name = $theme_obj->parent()->get( 'Name' );
137 } else {
138 $theme_name = $theme_obj->get( 'Name' );
139 }
140
141 $theme_name = sanitize_key( $theme_name );
142 }
143
144 $link = add_query_arg( 'utm_term', $theme_name, $link );
145
146 return $link;
147 }
148
149 /**
150 * Replace URLs.
151 *
152 * Replace old URLs to new URLs. This method also updates all the Elementor data.
153 *
154 * @since 2.1.0
155 * @static
156 * @access public
157 *
158 * @param $from
159 * @param $to
160 *
161 * @return string
162 * @throws \Exception
163 */
164 public static function replace_urls( $from, $to ) {
165 $from = trim( $from );
166 $to = trim( $to );
167
168 if ( $from === $to ) {
169 throw new \Exception( esc_html__( 'The `from` and `to` URL\'s must be different', 'elementor' ) );
170 }
171
172 $is_valid_urls = ( filter_var( $from, FILTER_VALIDATE_URL ) && filter_var( $to, FILTER_VALIDATE_URL ) );
173 if ( ! $is_valid_urls ) {
174 throw new \Exception( esc_html__( 'The `from` and `to` URL\'s must be valid URL\'s', 'elementor' ) );
175 }
176
177 global $wpdb;
178
179 // @codingStandardsIgnoreStart cannot use `$wpdb->prepare` because it remove's the backslashes
180 $rows_affected = $wpdb->query(
181 "UPDATE {$wpdb->postmeta} " .
182 "SET `meta_value` = REPLACE(`meta_value`, '" . str_replace( '/', '\\\/', $from ) . "', '" . str_replace( '/', '\\\/', $to ) . "') " .
183 "WHERE `meta_key` = '_elementor_data' AND `meta_value` LIKE '[%' ;" ); // meta_value LIKE '[%' are json formatted
184 // @codingStandardsIgnoreEnd
185
186 if ( false === $rows_affected ) {
187 throw new \Exception( esc_html__( 'An error occurred', 'elementor' ) );
188 }
189
190 // Allow externals to replace-urls, when they have to.
191 $rows_affected += (int) apply_filters( 'elementor/tools/replace-urls', 0, $from, $to );
192
193 Plugin::$instance->files_manager->clear_cache();
194
195 return sprintf(
196 /* translators: %d: Number of rows. */
197 _n( '%d row affected.', '%d rows affected.', $rows_affected, 'elementor' ),
198 $rows_affected
199 );
200 }
201
202 /**
203 * Is post supports Elementor.
204 *
205 * Whether the post supports editing with Elementor.
206 *
207 * @since 1.0.0
208 * @access public
209 * @static
210 *
211 * @param int $post_id Optional. Post ID. Default is `0`.
212 *
213 * @return string True if post supports editing with Elementor, false otherwise.
214 */
215 public static function is_post_support( $post_id = 0 ) {
216 $post_type = get_post_type( $post_id );
217
218 $is_supported = self::is_post_type_support( $post_type );
219
220 /**
221 * Is post type support.
222 *
223 * Filters whether the post type supports editing with Elementor.
224 *
225 * @since 1.0.0
226 * @deprecated 2.2.0 Use `elementor/utils/is_post_support` Instead
227 *
228 * @param bool $is_supported Whether the post type supports editing with Elementor.
229 * @param int $post_id Post ID.
230 * @param string $post_type Post type.
231 */
232 $is_supported = apply_filters( 'elementor/utils/is_post_type_support', $is_supported, $post_id, $post_type );
233
234 /**
235 * Is post support.
236 *
237 * Filters whether the post supports editing with Elementor.
238 *
239 * @since 2.2.0
240 *
241 * @param bool $is_supported Whether the post type supports editing with Elementor.
242 * @param int $post_id Post ID.
243 * @param string $post_type Post type.
244 */
245 $is_supported = apply_filters( 'elementor/utils/is_post_support', $is_supported, $post_id, $post_type );
246
247 return $is_supported;
248 }
249
250
251 /**
252 * Is post type supports Elementor.
253 *
254 * Whether the post type supports editing with Elementor.
255 *
256 * @since 2.2.0
257 * @access public
258 * @static
259 *
260 * @param string $post_type Post Type.
261 *
262 * @return string True if post type supports editing with Elementor, false otherwise.
263 */
264 public static function is_post_type_support( $post_type ) {
265 if ( ! post_type_exists( $post_type ) ) {
266 return false;
267 }
268
269 if ( ! post_type_supports( $post_type, 'elementor' ) ) {
270 return false;
271 }
272
273 return true;
274 }
275
276 /**
277 * Get placeholder image source.
278 *
279 * Retrieve the source of the placeholder image.
280 *
281 * @since 1.0.0
282 * @access public
283 * @static
284 *
285 * @return string The source of the default placeholder image used by Elementor.
286 */
287 public static function get_placeholder_image_src() {
288 $placeholder_image = ELEMENTOR_ASSETS_URL . 'images/placeholder.png';
289
290 /**
291 * Get placeholder image source.
292 *
293 * Filters the source of the default placeholder image used by Elementor.
294 *
295 * @since 1.0.0
296 *
297 * @param string $placeholder_image The source of the default placeholder image.
298 */
299 $placeholder_image = apply_filters( 'elementor/utils/get_placeholder_image_src', $placeholder_image );
300
301 return $placeholder_image;
302 }
303
304 /**
305 * Generate random string.
306 *
307 * Returns a string containing a hexadecimal representation of random number.
308 *
309 * @since 1.0.0
310 * @access public
311 * @static
312 *
313 * @return string Random string.
314 */
315 public static function generate_random_string() {
316 return dechex( rand() );
317 }
318
319 /**
320 * Do not cache.
321 *
322 * Tell WordPress cache plugins not to cache this request.
323 *
324 * @since 1.0.0
325 * @access public
326 * @static
327 */
328 public static function do_not_cache() {
329 if ( ! defined( 'DONOTCACHEPAGE' ) ) {
330 define( 'DONOTCACHEPAGE', true );
331 }
332
333 if ( ! defined( 'DONOTCACHEDB' ) ) {
334 define( 'DONOTCACHEDB', true );
335 }
336
337 if ( ! defined( 'DONOTMINIFY' ) ) {
338 define( 'DONOTMINIFY', true );
339 }
340
341 if ( ! defined( 'DONOTCDN' ) ) {
342 define( 'DONOTCDN', true );
343 }
344
345 if ( ! defined( 'DONOTCACHCEOBJECT' ) ) {
346 define( 'DONOTCACHCEOBJECT', true );
347 }
348
349 // Set the headers to prevent caching for the different browsers.
350 nocache_headers();
351 }
352
353 /**
354 * Get timezone string.
355 *
356 * Retrieve timezone string from the WordPress database.
357 *
358 * @since 1.0.0
359 * @access public
360 * @static
361 *
362 * @return string Timezone string.
363 */
364 public static function get_timezone_string() {
365 $current_offset = (float) get_option( 'gmt_offset' );
366 $timezone_string = get_option( 'timezone_string' );
367
368 // Create a UTC+- zone if no timezone string exists.
369 if ( empty( $timezone_string ) ) {
370 if ( $current_offset < 0 ) {
371 $timezone_string = 'UTC' . $current_offset;
372 } else {
373 $timezone_string = 'UTC+' . $current_offset;
374 }
375 }
376
377 return $timezone_string;
378 }
379
380 /**
381 * Get create new post URL.
382 *
383 * Retrieve a custom URL for creating a new post/page using Elementor.
384 *
385 * @since 1.9.0
386 * @access public
387 * @deprecated 3.3.0
388 * @static
389 *
390 * @param string $post_type Optional. Post type slug. Default is 'page'.
391 * @param string|null $template_type Optional. Query arg 'template_type'. Default is null.
392 *
393 * @return string A URL for creating new post using Elementor.
394 */
395 public static function get_create_new_post_url( $post_type = 'page', $template_type = null ) {
396 Plugin::$instance->modules_manager->get_modules( 'dev-tools' )->deprecation->deprecated_function( __FUNCTION__, '3.3.0', 'Plugin::$instance->documents->get_create_new_post_url()' );
397
398 return Plugin::$instance->documents->get_create_new_post_url( $post_type, $template_type );
399 }
400
401 /**
402 * Get post autosave.
403 *
404 * Retrieve an autosave for any given post.
405 *
406 * @since 1.9.2
407 * @access public
408 * @static
409 *
410 * @param int $post_id Post ID.
411 * @param int $user_id Optional. User ID. Default is `0`.
412 *
413 * @return \WP_Post|false Post autosave or false.
414 */
415 public static function get_post_autosave( $post_id, $user_id = 0 ) {
416 global $wpdb;
417
418 $post = get_post( $post_id );
419
420 $where = $wpdb->prepare( 'post_parent = %d AND post_name LIKE %s AND post_modified_gmt > %s', [ $post_id, "{$post_id}-autosave%", $post->post_modified_gmt ] );
421
422 if ( $user_id ) {
423 $where .= $wpdb->prepare( ' AND post_author = %d', $user_id );
424 }
425
426 $revision = $wpdb->get_row( "SELECT * FROM $wpdb->posts WHERE $where AND post_type = 'revision'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
427
428 if ( $revision ) {
429 $revision = new \WP_Post( $revision );
430 } else {
431 $revision = false;
432 }
433
434 return $revision;
435 }
436
437 /**
438 * Is CPT supports custom templates.
439 *
440 * Whether the Custom Post Type supports templates.
441 *
442 * @since 2.0.0
443 * @access public
444 * @static
445 *
446 * @return bool True is templates are supported, False otherwise.
447 */
448 public static function is_cpt_custom_templates_supported() {
449 require_once ABSPATH . '/wp-admin/includes/theme.php';
450
451 return method_exists( wp_get_theme(), 'get_post_templates' );
452 }
453
454 /**
455 * @since 2.1.2
456 * @access public
457 * @static
458 */
459 public static function array_inject( $array, $key, $insert ) {
460 $length = array_search( $key, array_keys( $array ), true ) + 1;
461
462 return array_slice( $array, 0, $length, true ) +
463 $insert +
464 array_slice( $array, $length, null, true );
465 }
466
467 /**
468 * Render html attributes
469 *
470 * @access public
471 * @static
472 * @param array $attributes
473 *
474 * @return string
475 */
476 public static function render_html_attributes( array $attributes ) {
477 $rendered_attributes = [];
478
479 foreach ( $attributes as $attribute_key => $attribute_values ) {
480 if ( is_array( $attribute_values ) ) {
481 $attribute_values = implode( ' ', $attribute_values );
482 }
483
484 $rendered_attributes[] = sprintf( '%1$s="%2$s"', $attribute_key, esc_attr( $attribute_values ) );
485 }
486
487 return implode( ' ', $rendered_attributes );
488 }
489
490 /**
491 * Safe print html attributes
492 *
493 * @access public
494 * @static
495 * @param array $attributes
496 */
497 public static function print_html_attributes( array $attributes ) {
498 // PHPCS - the method render_html_attributes is safe.
499 echo self::render_html_attributes( $attributes ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
500 }
501
502 public static function get_meta_viewport( $context = '' ) {
503 $meta_tag = '<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />';
504
505 /**
506 * Viewport meta tag.
507 *
508 * Filters the meta tag containing the viewport information.
509 *
510 * This hook can be used to change the intial viewport meta tag set by Elementor
511 * and replace it with a different viewport tag.
512 *
513 * @since 2.5.0
514 *
515 * @param string $meta_tag Viewport meta tag.
516 * @param string $context Page context.
517 */
518 $meta_tag = apply_filters( 'elementor/template/viewport_tag', $meta_tag, $context );
519
520 return $meta_tag;
521 }
522
523 /**
524 * Add Elementor Config js vars to the relevant script handle,
525 * WP will wrap it with <script> tag.
526 * To make sure this script runs thru the `script_loader_tag` hook, use a known handle value.
527 * @param string $handle
528 * @param string $js_var
529 * @param mixed $config
530 */
531 public static function print_js_config( $handle, $js_var, $config ) {
532 $config = wp_json_encode( $config );
533
534 if ( get_option( self::EDITOR_BREAK_LINES_OPTION_KEY ) ) {
535 // Add new lines to avoid memory limits in some hosting servers that handles the buffer output according to new line characters
536 $config = str_replace( '}},"', '}},' . PHP_EOL . '"', $config );
537 }
538
539 $script_data = 'var ' . $js_var . ' = ' . $config . ';';
540
541 wp_add_inline_script( $handle, $script_data, 'before' );
542 }
543
544 public static function handle_deprecation( $item, $version, $replacement = null ) {
545 preg_match( '/^[0-9]+\.[0-9]+/', ELEMENTOR_VERSION, $current_version );
546
547 $current_version_as_float = (float) $current_version[0];
548
549 preg_match( '/^[0-9]+\.[0-9]+/', $version, $alias_version );
550
551 $alias_version_as_float = (float) $alias_version[0];
552
553 if ( round( $current_version_as_float - $alias_version_as_float, 1 ) >= self::DEPRECATION_RANGE ) {
554 _deprecated_file( $item, $version, $replacement ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
555 }
556 }
557
558 /**
559 * Checks a control value for being empty, including a string of '0' not covered by PHP's empty().
560 *
561 * @param mixed $source
562 * @param bool|string $key
563 *
564 * @return bool
565 */
566 public static function is_empty( $source, $key = false ) {
567 if ( is_array( $source ) ) {
568 if ( ! isset( $source[ $key ] ) ) {
569 return true;
570 }
571
572 $source = $source[ $key ];
573 }
574
575 return '0' !== $source && empty( $source );
576 }
577
578 public static function has_pro() {
579 return defined( 'ELEMENTOR_PRO_VERSION' );
580 }
581
582 /**
583 * Convert HTMLEntities to UTF-8 characters
584 *
585 * @param $string
586 * @return string
587 */
588 public static function urlencode_html_entities( $string ) {
589 $entities_dictionary = [
590 '&#145;' => "'", // Opening single quote
591 '&#146;' => "'", // Closing single quote
592 '&#147;' => '"', // Closing double quote
593 '&#148;' => '"', // Opening double quote
594 '&#8216;' => "'", // Closing single quote
595 '&#8217;' => "'", // Opening single quote
596 '&#8218;' => "'", // Single low quote
597 '&#8220;' => '"', // Closing double quote
598 '&#8221;' => '"', // Opening double quote
599 '&#8222;' => '"', // Double low quote
600 ];
601
602 // Decode decimal entities
603 $string = str_replace( array_keys( $entities_dictionary ), array_values( $entities_dictionary ), $string );
604
605 return rawurlencode( html_entity_decode( $string, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
606 }
607
608 /**
609 * Parse attributes that come as a string of comma-delimited key|value pairs.
610 * Removes Javascript events and unescaped `href` attributes.
611 *
612 * @param string $attributes_string
613 *
614 * @param string $delimiter Default comma `,`.
615 *
616 * @return array
617 */
618 public static function parse_custom_attributes( $attributes_string, $delimiter = ',' ) {
619 $attributes = explode( $delimiter, $attributes_string );
620 $result = [];
621
622 foreach ( $attributes as $attribute ) {
623 $attr_key_value = explode( '|', $attribute );
624
625 $attr_key = mb_strtolower( $attr_key_value[0] );
626
627 // Remove any not allowed characters.
628 preg_match( '/[-_a-z0-9]+/', $attr_key, $attr_key_matches );
629
630 if ( empty( $attr_key_matches[0] ) ) {
631 continue;
632 }
633
634 $attr_key = $attr_key_matches[0];
635
636 // Avoid Javascript events and unescaped href.
637 if ( 'href' === $attr_key || 'on' === substr( $attr_key, 0, 2 ) ) {
638 continue;
639 }
640
641 if ( isset( $attr_key_value[1] ) ) {
642 $attr_value = trim( $attr_key_value[1] );
643 } else {
644 $attr_value = '';
645 }
646
647 $result[ $attr_key ] = $attr_value;
648 }
649
650 return $result;
651 }
652
653 public static function find_element_recursive( $elements, $id ) {
654 foreach ( $elements as $element ) {
655 if ( $id === $element['id'] ) {
656 return $element;
657 }
658
659 if ( ! empty( $element['elements'] ) ) {
660 $element = self::find_element_recursive( $element['elements'], $id );
661
662 if ( $element ) {
663 return $element;
664 }
665 }
666 }
667
668 return false;
669 }
670
671 /**
672 * Change Submenu First Item Label
673 *
674 * Overwrite the label of the first submenu item of an admin menu item.
675 *
676 * Fired by `admin_menu` action.
677 *
678 * @since 3.1.0
679 *
680 * @param $menu_slug
681 * @param $new_label
682 * @access public
683 */
684 public static function change_submenu_first_item_label( $menu_slug, $new_label ) {
685 global $submenu;
686
687 if ( isset( $submenu[ $menu_slug ] ) ) {
688 // @codingStandardsIgnoreStart
689 $submenu[ $menu_slug ][0][0] = $new_label;
690 // @codingStandardsIgnoreEnd
691 }
692 }
693
694 /**
695 * Validate an HTML tag against a safe allowed list.
696 *
697 * @param string $tag
698 *
699 * @return string
700 */
701 public static function validate_html_tag( $tag ) {
702 return in_array( strtolower( $tag ), self::ALLOWED_HTML_WRAPPER_TAGS ) ? $tag : 'div';
703 }
704
705 /**
706 * Safe print a validated HTML tag.
707 *
708 * @param string $tag
709 */
710 public static function print_validated_html_tag( $tag ) {
711 // PHPCS - the method validate_html_tag is safe.
712 echo self::validate_html_tag( $tag ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
713 }
714
715 /**
716 * Print internal content (not user input) without escaping.
717 */
718 public static function print_unescaped_internal_string( $string ) {
719 echo $string; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
720 }
721
722 /**
723 * Get recently edited posts query.
724 *
725 * Returns `WP_Query` of the recent edited posts.
726 * By default max posts ( $args['posts_per_page'] ) is 3.
727 *
728 * @param array $args
729 *
730 * @return \WP_Query
731 */
732 public static function get_recently_edited_posts_query( $args = [] ) {
733 $args = wp_parse_args( $args, [
734 'no_found_rows' => true,
735 'post_type' => 'any',
736 'post_status' => [ 'publish', 'draft' ],
737 'posts_per_page' => '3',
738 'meta_key' => '_elementor_edit_mode',
739 'meta_value' => 'builder',
740 'orderby' => 'modified',
741 ] );
742
743 return new \WP_Query( $args );
744 }
745
746 public static function print_wp_kses_extended( $string, array $tags ) {
747 $allowed_html = wp_kses_allowed_html( 'post' );
748 // Since PHP 5.6 cannot use isset() on the result of an expression.
749 $extended_allowed_html_tags = self::EXTENDED_ALLOWED_HTML_TAGS;
750
751 foreach ( $tags as $tag ) {
752 if ( isset( $extended_allowed_html_tags[ $tag ] ) ) {
753 $extended_tags = apply_filters( "elementor/extended_allowed_html_tags/{$tag}", self::EXTENDED_ALLOWED_HTML_TAGS[ $tag ] );
754 $allowed_html = array_replace_recursive( $allowed_html, $extended_tags );
755 }
756 }
757
758 echo wp_kses( $string, $allowed_html );
759 }
760
761 public static function is_elementor_path( $path ) {
762 $path = wp_normalize_path( $path );
763
764 /**
765 * Elementor related paths.
766 *
767 * Filters Elementor related paths.
768 *
769 * @param string[] $available_paths
770 */
771 $available_paths = apply_filters( 'elementor/utils/elementor_related_paths', [ ELEMENTOR_PATH ] );
772
773 return (bool) ( new Collection( $available_paths ) )
774 ->map( function ( $p ) {
775 // `untrailingslashit` in order to include other plugins prefixed with elementor.
776 return untrailingslashit( wp_normalize_path( $p ) );
777 } )
778 ->find(function ( $p ) use ( $path ) {
779 return false !== strpos( $path, $p );
780 } );
781 }
782 }
783