PluginProbe
Elementor Website Builder – more than just a page builder / 3.4.7
Elementor Website Builder – more than just a page builder v3.4.7
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.4.7, at includes/utils.php

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