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

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