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

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