PluginProbe
Elementor Website Builder – more than just a page builder / 3.34.3
Elementor Website Builder – more than just a page builder v3.34.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 / template-library / sources / local.php

local.php in Elementor Website Builder – more than just a page builder 3.34.3, at includes/template-library/sources/local.php

1,964 lines 55.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Elementor\TemplateLibrary;
3
4 use Elementor\Core\Admin\Menu\Admin_Menu_Manager;
5 use Elementor\Core\Base\Document;
6 use Elementor\Core\Editor\Editor;
7 use Elementor\Core\Utils\Collection;
8 use Elementor\DB;
9 use Elementor\Core\Settings\Manager as SettingsManager;
10 use Elementor\Includes\TemplateLibrary\Sources\AdminMenuItems\Add_New_Template_Menu_Item;
11 use Elementor\Includes\TemplateLibrary\Sources\AdminMenuItems\Saved_Templates_Menu_Item;
12 use Elementor\Includes\TemplateLibrary\Sources\AdminMenuItems\Templates_Categories_Menu_Item;
13 use Elementor\Modules\Library\Documents\Library_Document;
14 use Elementor\Plugin;
15 use Elementor\Utils;
16 use Elementor\User;
17 use Elementor\Core\Isolation\Wordpress_Adapter;
18 use Elementor\Core\Isolation\Wordpress_Adapter_Interface;
19 use Elementor\Core\Isolation\Elementor_Adapter;
20 use Elementor\Core\Isolation\Elementor_Adapter_Interface;
21 use Elementor\Modules\EditorOne\Classes\Menu_Data_Provider;
22 use Elementor\Includes\TemplateLibrary\Sources\AdminMenuItems\Editor_One_Saved_Templates_Menu;
23 use Elementor\Includes\TemplateLibrary\Sources\AdminMenuItems\Editor_One_Templates_Menu;
24
25 if ( ! defined( 'ABSPATH' ) ) {
26 exit; // Exit if accessed directly.
27 }
28
29 /**
30 * Elementor template library local source.
31 *
32 * Elementor template library local source handler class is responsible for
33 * handling local Elementor templates saved by the user locally on his site.
34 *
35 * @since 1.0.0
36 */
37 class Source_Local extends Source_Base {
38
39 /**
40 * Elementor template-library post-type slug.
41 */
42 const CPT = 'elementor_library';
43
44 /**
45 * Elementor template-library taxonomy slug.
46 */
47 const TAXONOMY_TYPE_SLUG = 'elementor_library_type';
48
49 /**
50 * Elementor template-library category slug.
51 */
52 const TAXONOMY_CATEGORY_SLUG = 'elementor_library_category';
53
54 /**
55 * Elementor template-library meta key.
56 *
57 * @deprecated 2.3.0 Use `Elementor\Core\Base\Document::TYPE_META_KEY` const instead.
58 */
59 const TYPE_META_KEY = '_elementor_template_type';
60
61 /**
62 * Elementor template-library temporary files folder.
63 */
64 const TEMP_FILES_DIR = 'elementor/tmp';
65
66 /**
67 * Elementor template-library bulk export action name.
68 */
69 const BULK_EXPORT_ACTION = 'elementor_export_multiple_templates';
70
71 const ADMIN_MENU_SLUG = 'edit.php?post_type=elementor_library';
72
73 const ADMIN_MENU_PRIORITY = 10;
74
75 const ADMIN_SCREEN_ID = 'edit-elementor_library';
76
77 /**
78 * Template types.
79 *
80 * Holds the list of supported template types that can be displayed.
81 *
82 * @access private
83 * @static
84 *
85 * @var array
86 */
87 private static $template_types = [];
88
89 /**
90 * Post type object.
91 *
92 * Holds the post type object of the current post.
93 *
94 * @access private
95 *
96 * @var \WP_Post_Type
97 */
98 private $post_type_object;
99
100 /**
101 * @var Wordpress_Adapter_Interface
102 */
103 protected $wordpress_adapter = null;
104
105 /**
106 * @var Elementor_Adapter_Interface
107 */
108 protected $elementor_adapter = null;
109
110 /**
111 * @since 2.3.0
112 * @access public
113 * @static
114 * @return array
115 */
116 public static function get_template_types() {
117 return self::$template_types;
118 }
119
120 /**
121 * Get local template type.
122 *
123 * Retrieve the template type from the post meta.
124 *
125 * @since 1.0.0
126 * @access public
127 * @static
128 *
129 * @param int $template_id The template ID.
130 *
131 * @return mixed The value of meta data field.
132 */
133 public static function get_template_type( $template_id ) {
134 return get_post_meta( $template_id, Document::TYPE_META_KEY, true );
135 }
136
137 /**
138 * Is base templates screen.
139 *
140 * Whether the current screen base is edit and the post type is template.
141 *
142 * @since 1.0.0
143 * @access public
144 * @static
145 *
146 * @return bool True on base templates screen, False otherwise.
147 */
148 public static function is_base_templates_screen() {
149 global $current_screen;
150
151 if ( ! $current_screen ) {
152 return false;
153 }
154
155 return 'edit' === $current_screen->base && self::CPT === $current_screen->post_type;
156 }
157
158 /**
159 * Add template type.
160 *
161 * Register new template type to the list of supported local template types.
162 *
163 * @since 1.0.3
164 * @access public
165 * @static
166 *
167 * @param string $type Template type.
168 */
169 public static function add_template_type( $type ) {
170 self::$template_types[ $type ] = $type;
171 }
172
173 /**
174 * Remove template type.
175 *
176 * Remove existing template type from the list of supported local template
177 * types.
178 *
179 * @since 1.8.0
180 * @access public
181 * @static
182 *
183 * @param string $type Template type.
184 */
185 public static function remove_template_type( $type ) {
186 if ( isset( self::$template_types[ $type ] ) ) {
187 unset( self::$template_types[ $type ] );
188 }
189 }
190
191 public static function get_admin_url( $relative = false ) {
192 $base_url = self::ADMIN_MENU_SLUG;
193 if ( ! $relative ) {
194 $base_url = admin_url( $base_url );
195 }
196
197 return add_query_arg( 'tabs_group', 'library', $base_url );
198 }
199
200 /**
201 * Get local template ID.
202 *
203 * Retrieve the local template ID.
204 *
205 * @since 1.0.0
206 * @access public
207 *
208 * @return string The local template ID.
209 */
210 public function get_id() {
211 return 'local';
212 }
213
214 /**
215 * Get local template title.
216 *
217 * Retrieve the local template title.
218 *
219 * @since 1.0.0
220 * @access public
221 *
222 * @return string The local template title.
223 */
224 public function get_title() {
225 return esc_html__( 'Local', 'elementor' );
226 }
227
228 /**
229 * Register local template data.
230 *
231 * Used to register custom template data like a post type, a taxonomy or any
232 * other data.
233 *
234 * The local template class registers a new `elementor_library` post type
235 * and an `elementor_library_type` taxonomy. They are used to store data for
236 * local templates saved by the user on his site.
237 *
238 * @since 1.0.0
239 * @access public
240 */
241 public function register_data() {
242 $labels = [
243 'name' => esc_html_x( 'My Templates', 'Template Library', 'elementor' ),
244 'singular_name' => esc_html_x( 'Template', 'Template Library', 'elementor' ),
245 'add_new' => esc_html__( 'Add New Template', 'elementor' ),
246 'add_new_item' => esc_html__( 'Add New Template', 'elementor' ),
247 'edit_item' => esc_html__( 'Edit Template', 'elementor' ),
248 'new_item' => esc_html__( 'New Template', 'elementor' ),
249 'all_items' => esc_html__( 'All Templates', 'elementor' ),
250 'view_item' => esc_html__( 'View Template', 'elementor' ),
251 'search_items' => esc_html__( 'Search Template', 'elementor' ),
252 'not_found' => esc_html__( 'No Templates found', 'elementor' ),
253 'not_found_in_trash' => esc_html__( 'No Templates found in Trash', 'elementor' ),
254 'parent_item_colon' => esc_html__( 'Parent Template:', 'elementor' ),
255 'menu_name' => esc_html_x( 'Templates', 'Template Library', 'elementor' ),
256 ];
257
258 $args = [
259 'labels' => $labels,
260 'public' => true,
261 'rewrite' => false,
262 'menu_icon' => 'dashicons-admin-page',
263 'show_ui' => true,
264 'show_in_menu' => true,
265 'show_in_nav_menus' => false,
266 'exclude_from_search' => true,
267 'capability_type' => 'post',
268 'hierarchical' => false,
269 'supports' => [ 'title', 'thumbnail', 'author', 'elementor', 'custom-fields' ],
270 'show_in_rest' => true,
271 ];
272
273 $this->avoid_rest_access_for_non_admins();
274
275 /**
276 * Register template library post type args.
277 *
278 * Filters the post type arguments when registering elementor template library post type.
279 *
280 * @since 1.0.0
281 *
282 * @param array $args Arguments for registering a post type.
283 */
284 $args = apply_filters( 'elementor/template_library/sources/local/register_post_type_args', $args );
285
286 $this->post_type_object = register_post_type( self::CPT, $args );
287
288 $args = [
289 'hierarchical' => false,
290 'show_ui' => false,
291 'show_in_nav_menus' => false,
292 'show_admin_column' => true,
293 'query_var' => is_admin(),
294 'rewrite' => false,
295 'public' => false,
296 'label' => esc_html_x( 'Type', 'Template Library', 'elementor' ),
297 ];
298
299 /**
300 * Register template library taxonomy args.
301 *
302 * Filters the taxonomy arguments when registering elementor template library taxonomy.
303 *
304 * @since 1.0.0
305 *
306 * @param array $args Arguments for registering a taxonomy.
307 */
308 $args = apply_filters( 'elementor/template_library/sources/local/register_taxonomy_args', $args );
309
310 $cpts_to_associate = [ self::CPT ];
311
312 /**
313 * Custom post types to associate.
314 *
315 * Filters the list of custom post types when registering elementor template library taxonomy.
316 *
317 * @since 1.0.0
318 *
319 * @param array $cpts_to_associate Custom post types. Default is `elementor_library` post type.
320 */
321 $cpts_to_associate = apply_filters( 'elementor/template_library/sources/local/register_taxonomy_cpts', $cpts_to_associate );
322
323 register_taxonomy( self::TAXONOMY_TYPE_SLUG, $cpts_to_associate, $args );
324
325 /**
326 * Categories
327 */
328 $args = [
329 'hierarchical' => true,
330 'show_ui' => true,
331 'show_in_nav_menus' => false,
332 'show_admin_column' => true,
333 'query_var' => is_admin(),
334 'rewrite' => false,
335 'public' => false,
336 'labels' => [
337 'name' => esc_html_x( 'Categories', 'Template Library', 'elementor' ),
338 'singular_name' => esc_html_x( 'Category', 'Template Library', 'elementor' ),
339 'all_items' => esc_html_x( 'All Categories', 'Template Library', 'elementor' ),
340 ],
341 ];
342
343 /**
344 * Register template library category args.
345 *
346 * Filters the category arguments when registering elementor template library category.
347 *
348 * @since 2.4.0
349 *
350 * @param array $args Arguments for registering a category.
351 */
352 $args = apply_filters( 'elementor/template_library/sources/local/register_category_args', $args );
353
354 register_taxonomy( self::TAXONOMY_CATEGORY_SLUG, self::CPT, $args );
355 }
356
357 /**
358 * Remove Add New item from admin menu.
359 *
360 * Fired by `admin_menu` action.
361 *
362 * @since 2.4.0
363 * @access public
364 */
365 private function admin_menu_reorder( Admin_Menu_Manager $admin_menu ) {
366 global $submenu;
367
368 if ( ! isset( $submenu[ static::ADMIN_MENU_SLUG ] ) ) {
369 return;
370 }
371
372 remove_submenu_page( static::ADMIN_MENU_SLUG, static::ADMIN_MENU_SLUG );
373
374 $add_new_slug = 'post-new.php?post_type=' . static::CPT;
375 $category_slug = 'edit-tags.php?taxonomy=' . static::TAXONOMY_CATEGORY_SLUG . '&amp;post_type=' . static::CPT;
376
377 $library_submenu = new Collection( $submenu[ static::ADMIN_MENU_SLUG ] );
378
379 $add_new_item = $library_submenu->find( function ( $item ) use ( $add_new_slug ) {
380 return $add_new_slug === $item[2];
381 } );
382
383 $categories_item = $library_submenu->find( function ( $item ) use ( $category_slug ) {
384 return $category_slug === $item[2];
385 } );
386
387 if ( $add_new_item ) {
388 remove_submenu_page( static::ADMIN_MENU_SLUG, $add_new_slug );
389
390 $admin_menu->register( admin_url( static::ADMIN_MENU_SLUG . '#add_new' ), new Add_New_Template_Menu_Item() );
391 }
392
393 if ( $categories_item ) {
394 remove_submenu_page( static::ADMIN_MENU_SLUG, $category_slug );
395
396 $admin_menu->register( $category_slug, new Templates_Categories_Menu_Item() );
397 }
398 }
399
400 /**
401 * Add a `current` CSS class to the `Saved Templates` submenu page when it's active.
402 * It should work by default, but since we interfere with WordPress' builtin CPT menus it doesn't work properly.
403 *
404 * @return void
405 */
406 private function admin_menu_set_current() {
407 global $submenu;
408
409 if ( $this->is_current_screen() ) {
410 $library_submenu = &$submenu[ static::ADMIN_MENU_SLUG ];
411 $library_title = $this->get_library_title();
412
413 foreach ( $library_submenu as &$item ) {
414 if ( $library_title === $item[0] ) {
415 if ( ! isset( $item[4] ) ) {
416 $item[4] = '';
417 }
418 $item[4] .= ' current';
419 }
420 }
421 }
422 }
423
424 private function register_admin_menu( Admin_Menu_Manager $admin_menu ) {
425 if ( ! $this->is_editor_one_active() ) {
426 $admin_menu->register( static::get_admin_url( true ), new Saved_Templates_Menu_Item() );
427 }
428 }
429
430 private function register_editor_one_menu( Menu_Data_Provider $menu_data_provider ) {
431 $menu_data_provider->register_menu( new Editor_One_Templates_Menu() );
432 $menu_data_provider->register_menu( new Editor_One_Saved_Templates_Menu() );
433 }
434
435 private function is_editor_one_active(): bool {
436 return (bool) Plugin::instance()->modules_manager->get_modules( 'editor-one' );
437 }
438
439 public function admin_title( $admin_title, $title ) {
440 $library_title = $this->get_library_title();
441
442 if ( $library_title ) {
443 $admin_title = str_replace( $title, $library_title, $admin_title );
444 }
445
446 return $admin_title;
447 }
448
449 public function replace_admin_heading() {
450 $library_title = $this->get_library_title();
451
452 if ( $library_title ) {
453 global $post_type_object;
454
455 $post_type_object->labels->name = $library_title;
456 }
457 }
458
459 /**
460 * Get local templates.
461 *
462 * Retrieve local templates saved by the user on his site.
463 *
464 * @since 1.0.0
465 * @access public
466 *
467 * @param array $args Optional. Filter templates based on a set of
468 * arguments. Default is an empty array.
469 *
470 * @return array Local templates.
471 */
472 public function get_items( $args = [] ) {
473 $template_types = array_values( self::$template_types );
474
475 if ( ! empty( $args['type'] ) ) {
476 $template_types = $args['type'];
477 unset( $args['type'] );
478 }
479
480 $defaults = [
481 'post_type' => self::CPT,
482 'post_status' => 'publish',
483 'posts_per_page' => -1,
484 'orderby' => 'title',
485 'order' => 'ASC',
486 'meta_query' => [
487 [
488 'key' => Document::TYPE_META_KEY,
489 'value' => $template_types,
490 ],
491 ],
492 ];
493
494 $query_args = wp_parse_args( $args, $defaults );
495
496 $templates_query = new \WP_Query( $query_args );
497
498 $templates = [];
499
500 if ( $templates_query->have_posts() ) {
501 foreach ( $templates_query->get_posts() as $post ) {
502 $templates[] = $this->get_item( $post->ID );
503 }
504 }
505
506 return $templates;
507 }
508
509 /**
510 * Save local template.
511 *
512 * Save new or update existing template on the database.
513 *
514 * @since 1.0.0
515 * @access public
516 *
517 * @param array $template_data Local template data.
518 *
519 * @return \WP_Error|int The ID of the saved/updated template, `WP_Error` otherwise.
520 */
521 public function save_item( $template_data ) {
522 if ( ! current_user_can( $this->post_type_object->cap->edit_posts ) ) {
523 return new \WP_Error( 'save_error', esc_html__( 'Access denied.', 'elementor' ) );
524 }
525
526 $defaults = [
527 'title' => esc_html__( '(no title)', 'elementor' ),
528 'page_settings' => [],
529 ];
530
531 $template_data = wp_parse_args( $template_data, $defaults );
532 $template_data['status'] = current_user_can( 'publish_posts' ) ? 'publish' : 'pending';
533
534 // BC: Allow importing any template type when using CLI
535 // to support users that rely on this mechanism.
536 $should_check_template_type = ! $this->is_wp_cli();
537
538 if (
539 $should_check_template_type &&
540 ! $this->is_valid_template_type( $template_data['type'] )
541 ) {
542 return new \WP_Error( 'invalid_template_type', esc_html__( 'Invalid template type.', 'elementor' ) );
543 }
544
545 $document = Plugin::$instance->documents->create(
546 $template_data['type'],
547 [
548 'post_title' => $template_data['title'],
549 'post_status' => $template_data['status'],
550 ]
551 );
552
553 if ( is_wp_error( $document ) ) {
554 /**
555 * @var \WP_Error $document
556 */
557 return $document;
558 }
559
560 if ( ! empty( $template_data['content'] ) ) {
561 $template_data['content'] = $this->replace_elements_ids( $template_data['content'] );
562 }
563
564 $document->save( [
565 'elements' => $template_data['content'],
566 'settings' => $template_data['page_settings'],
567 ] );
568
569 $template_id = $document->get_main_id();
570
571 /**
572 * After template library save.
573 *
574 * Fires after Elementor template library was saved.
575 *
576 * @since 1.0.1
577 *
578 * @param int $template_id The ID of the template.
579 * @param array $template_data The template data.
580 */
581 do_action( 'elementor/template-library/after_save_template', $template_id, $template_data );
582
583 /**
584 * After template library update.
585 *
586 * Fires after Elementor template library was updated.
587 *
588 * @since 1.0.1
589 *
590 * @param int $template_id The ID of the template.
591 * @param array $template_data The template data.
592 */
593 do_action( 'elementor/template-library/after_update_template', $template_id, $template_data );
594
595 return $template_id;
596 }
597
598 protected function is_valid_template_type( $type ) {
599 $document_class = Plugin::$instance->documents->get_document_type( $type, false );
600
601 if ( ! $document_class ) {
602 return false;
603 }
604
605 $cpt = $document_class::get_property( 'cpt' );
606
607 if ( ! $cpt || ! is_array( $cpt ) || 1 !== count( $cpt ) ) {
608 return false;
609 }
610
611 $is_valid_template_type = in_array( static::CPT, $cpt, true );
612
613 return apply_filters(
614 'elementor/template_library/sources/local/is_valid_template_type',
615 $is_valid_template_type,
616 $cpt,
617 );
618 }
619
620 /** For testing purposes only, in order to be able to mock the `WP_CLI` constant. */
621 protected function is_wp_cli() {
622 return Utils::is_wp_cli();
623 }
624
625 /**
626 * Update local template.
627 *
628 * Update template on the database.
629 *
630 * @since 1.0.0
631 * @access public
632 *
633 * @param array $new_data New template data.
634 *
635 * @return \WP_Error|true True if template updated, `WP_Error` otherwise.
636 */
637 public function update_item( $new_data ) {
638 if ( ! current_user_can( $this->post_type_object->cap->edit_post, $new_data['id'] ) ) {
639 return new \WP_Error( 'save_error', esc_html__( 'Access denied.', 'elementor' ) );
640 }
641
642 $document = Plugin::$instance->documents->get( $new_data['id'] );
643
644 if ( ! $document ) {
645 return new \WP_Error( 'save_error', esc_html__( 'Template not exist.', 'elementor' ) );
646 }
647
648 $save_data = [];
649
650 if ( isset( $new_data['title'] ) ) {
651 $save_data['post_title'] = $new_data['title'];
652 }
653
654 if ( isset( $new_data['content'] ) ) {
655 $save_data['elements'] = $new_data['content'];
656 }
657
658 $document->save( $save_data );
659
660 /**
661 * After template library update.
662 *
663 * Fires after Elementor template library was updated.
664 *
665 * @since 1.0.0
666 *
667 * @param int $new_data_id The ID of the new template.
668 * @param array $new_data The new template data.
669 */
670 do_action( 'elementor/template-library/after_update_template', $new_data['id'], $new_data );
671
672 return true;
673 }
674
675 /**
676 * Get local template.
677 *
678 * Retrieve a single local template saved by the user on his site.
679 *
680 * @since 1.0.0
681 * @access public
682 *
683 * @param int $template_id The template ID.
684 *
685 * @return array Local template.
686 */
687 public function get_item( $template_id ) {
688 $post = get_post( $template_id );
689
690 $user = get_user_by( 'id', $post->post_author );
691
692 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $template_id );
693
694 $page_settings = $page->get_data( 'settings' );
695
696 $date = strtotime( $post->post_date );
697
698 $data = [
699 'template_id' => $post->ID,
700 'source' => $this->get_id(),
701 'type' => self::get_template_type( $post->ID ),
702 'title' => $post->post_title,
703 'thumbnail' => get_the_post_thumbnail_url( $post ),
704 'date' => $date,
705 'human_date' => date_i18n( get_option( 'date_format' ), $date ),
706 'human_modified_date' => date_i18n( get_option( 'date_format' ), strtotime( $post->post_modified ) ),
707 'author' => $user->display_name,
708 'status' => $post->post_status,
709 'hasPageSettings' => ! empty( $page_settings ),
710 'tags' => [],
711 'export_link' => $this->get_export_link( $template_id ),
712 'url' => get_permalink( $post->ID ),
713 ];
714
715 /**
716 * Get template library template.
717 *
718 * Filters the template data when retrieving a single template from the
719 * template library.
720 *
721 * @since 1.0.0
722 *
723 * @param array $data Template data.
724 */
725 $data = apply_filters( 'elementor/template-library/get_template', $data );
726
727 return $data;
728 }
729
730 /**
731 * Get template data.
732 *
733 * Retrieve the data of a single local template saved by the user on his site.
734 *
735 * @since 1.5.0
736 * @access public
737 *
738 * @param array $args Custom template arguments.
739 *
740 * @return array Local template data.
741 */
742 public function get_data( array $args ) {
743 $template_id = $args['template_id'];
744
745 $document = Plugin::$instance->documents->get( $template_id );
746 $content = [];
747
748 if ( $document ) {
749 // TODO: Validate the data (in JS too!).
750 if ( ! empty( $args['display'] ) ) {
751 $content = $document->get_elements_raw_data( null, true );
752 } else {
753 $content = $document->get_elements_data();
754 }
755
756 if ( ! empty( $content ) ) {
757 $content = $this->replace_elements_ids( $content );
758
759 /**
760 * Filters the template content data.
761 *
762 * This filter allows third-party plugins to modify template content
763 * when loaded via get_template_data(), making the behavior consistent
764 * with Frontend::get_builder_content().
765 *
766 * @since 3.34.0
767 *
768 * @param array $content The template content data.
769 * @param int $template_id The template ID.
770 */
771 $content = apply_filters( 'elementor/frontend/builder_content_data', $content, $template_id );
772 }
773 }
774
775 $data = [
776 'content' => $content,
777 ];
778
779 if ( ! empty( $args['with_page_settings'] ) ) {
780 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $args['template_id'] );
781
782 $data['page_settings'] = $page->get_data( 'settings' );
783 }
784
785 return $data;
786 }
787
788 /**
789 * Delete local template.
790 *
791 * Delete template from the database.
792 *
793 * @since 1.0.0
794 * @access public
795 *
796 * @param int $template_id The template ID.
797 *
798 * @return \WP_Post|\WP_Error|false|null Post data on success, false or null
799 * or 'WP_Error' on failure.
800 */
801 public function delete_template( $template_id ) {
802 if ( ! current_user_can( $this->post_type_object->cap->delete_post, $template_id ) ) {
803 return new \WP_Error( 'template_error', esc_html__( 'Access denied.', 'elementor' ) );
804 }
805
806 return wp_delete_post( $template_id, true );
807 }
808
809 public function bulk_delete_items( array $template_ids ) {
810 foreach ( $template_ids as $template_id ) {
811 if ( ! current_user_can( $this->post_type_object->cap->delete_post, $template_id ) ) {
812 return new \WP_Error( 'template_error', esc_html__( 'Access denied.', 'elementor' ) );
813 }
814 }
815
816 foreach ( $template_ids as $template_id ) {
817 wp_delete_post( $template_id, true );
818 }
819
820 return true;
821 }
822
823 /**
824 * Export local template.
825 *
826 * Export template to a file.
827 *
828 * @since 1.0.0
829 * @access public
830 *
831 * @param int $template_id The template ID.
832 *
833 * @return \WP_Error WordPress error if template export failed.
834 */
835 public function export_template( $template_id ) {
836 $permissions_error = $this->validate_template_export_permissions( $template_id );
837
838 if ( is_wp_error( $permissions_error ) ) {
839 return $permissions_error;
840 }
841
842 $file_data = $this->prepare_template_export( $template_id );
843
844 if ( is_wp_error( $file_data ) ) {
845 return $file_data;
846 }
847
848 $this->send_file_headers( $file_data['name'], strlen( $file_data['content'] ) );
849
850 $this->serve_file( $file_data['content'] );
851
852 die;
853 }
854
855 private function validate_template_export_permissions( $template_id ) {
856 $post_id = intval( $template_id );
857 if ( get_post_type( $post_id ) !== self::CPT ) {
858 return new \WP_Error( 'template_error', esc_html__( 'Invalid template type or template does not exist.', 'elementor' ) );
859 }
860
861 $post_status = get_post_status( $post_id );
862 if ( 'private' === $post_status && ! current_user_can( 'read_private_posts', $post_id ) ) {
863 return new \WP_Error( 'template_error', esc_html__( 'You do not have permission to access this template.', 'elementor' ) );
864 }
865
866 if ( 'publish' !== $post_status && ! current_user_can( 'edit_post', $post_id ) ) {
867 return new \WP_Error( 'template_error', esc_html__( 'You do not have permission to export this template.', 'elementor' ) );
868 }
869
870 return null;
871 }
872
873 /**
874 * Export multiple local templates.
875 *
876 * Export multiple template to a ZIP file.
877 *
878 * @since 1.6.0
879 * @access public
880 *
881 * @param array $template_ids An array of template IDs.
882 *
883 * @return \WP_Error WordPress error if export failed.
884 */
885 public function export_multiple_templates( array $template_ids ) {
886 $files = [];
887
888 $wp_upload_dir = wp_upload_dir();
889
890 $temp_path = $wp_upload_dir['basedir'] . '/' . self::TEMP_FILES_DIR;
891
892 // Create temp path if it doesn't exist
893 wp_mkdir_p( $temp_path );
894
895 // Create all json files
896 foreach ( $template_ids as $template_id ) {
897 $file_data = $this->prepare_template_export( $template_id );
898
899 if ( is_wp_error( $file_data ) ) {
900 continue;
901 }
902
903 $complete_path = $temp_path . '/' . $file_data['name'];
904
905 $put_contents = file_put_contents( $complete_path, $file_data['content'] );
906
907 if ( ! $put_contents ) {
908 return new \WP_Error( '404', sprintf( 'Cannot create file "%s".', $file_data['name'] ) );
909 }
910
911 $files[] = [
912 'path' => $complete_path,
913 'name' => $file_data['name'],
914 ];
915 }
916
917 if ( ! $files ) {
918 return new \WP_Error( 'empty_files', 'There is no files to export (probably all the requested templates are empty).' );
919 }
920
921 // Create temporary .zip file
922 $zip_archive_filename = 'elementor-templates-' . gmdate( 'Y-m-d' ) . '.zip';
923
924 $zip_archive = new \ZipArchive();
925
926 $zip_complete_path = $temp_path . '/' . $zip_archive_filename;
927
928 $zip_archive->open( $zip_complete_path, \ZipArchive::CREATE );
929
930 foreach ( $files as $file ) {
931 $zip_archive->addFile( $file['path'], $file['name'] );
932 }
933
934 $zip_archive->close();
935
936 foreach ( $files as $file ) {
937 unlink( $file['path'] );
938 }
939
940 $this->send_file_headers( $zip_archive_filename, $this->filesize( $zip_complete_path ) );
941
942 $this->serve_zip( $zip_complete_path );
943
944 unlink( $zip_complete_path );
945
946 die;
947 }
948
949 /**
950 * Import local template.
951 *
952 * Import template from a file.
953 *
954 * @since 1.0.0
955 * @access public
956 *
957 * @param string $name - The file name.
958 * @param string $path - The file path.
959 * @return \WP_Error|array An array of items on success, 'WP_Error' on failure.
960 */
961 public function import_template( $name, $path ) {
962 if ( empty( $path ) ) {
963 return new \WP_Error( 'file_error', 'Please upload a file to import' );
964 }
965
966 // Set the Request's state as an Elementor upload request, in order to support unfiltered file uploads.
967 Plugin::$instance->uploads_manager->set_elementor_upload_state( true );
968
969 $items = [];
970
971 // If the import file is a Zip file with potentially multiple JSON files
972 if ( 'zip' === pathinfo( $name, PATHINFO_EXTENSION ) ) {
973 $extracted_files = Plugin::$instance->uploads_manager->extract_and_validate_zip( $path, [ 'json' ] );
974
975 if ( is_wp_error( $extracted_files ) ) {
976 // Delete the temporary extraction directory, since it's now not necessary.
977 Plugin::$instance->uploads_manager->remove_file_or_dir( $extracted_files['extraction_directory'] );
978
979 return $extracted_files;
980 }
981
982 foreach ( $extracted_files['files'] as $file_path ) {
983 // Skip macOS metadata files and folders
984 if ( false !== strpos( $file_path, '__MACOSX' ) || '.' === basename( $file_path )[0] ) {
985 continue;
986 }
987
988 $import_result = $this->import_single_template( $file_path );
989
990 if ( is_wp_error( $import_result ) ) {
991 // Skip failed files
992 continue;
993 }
994
995 $items[] = $import_result;
996 }
997
998 // Delete the temporary extraction directory, since it's now not necessary.
999 Plugin::$instance->uploads_manager->remove_file_or_dir( $extracted_files['extraction_directory'] );
1000 } else {
1001 // If the import file is a single JSON file
1002 $import_result = $this->import_single_template( $path );
1003
1004 if ( is_wp_error( $import_result ) ) {
1005 return $import_result;
1006 }
1007
1008 $items[] = $import_result;
1009 }
1010
1011 return $items;
1012 }
1013
1014 /**
1015 * Post row actions.
1016 *
1017 * Add an export link to the template library action links table list.
1018 *
1019 * Fired by `post_row_actions` filter.
1020 *
1021 * @since 1.0.0
1022 * @access public
1023 *
1024 * @param array $actions An array of row action links.
1025 * @param \WP_Post $post The post object.
1026 *
1027 * @return array An updated array of row action links.
1028 */
1029 public function post_row_actions( $actions, \WP_Post $post ) {
1030 if ( self::is_base_templates_screen() ) {
1031 if ( $this->is_template_supports_export( $post->ID ) ) {
1032 $actions['export-template'] = sprintf( '<a href="%1$s">%2$s</a>', $this->get_export_link( $post->ID ), esc_html__( 'Export Template', 'elementor' ) );
1033 }
1034 }
1035
1036 return $actions;
1037 }
1038
1039 /**
1040 * Admin import template form.
1041 *
1042 * The import form displayed in "My Library" screen in WordPress dashboard.
1043 *
1044 * The form allows the user to import template in json/zip format to the site.
1045 *
1046 * Fired by `admin_footer` action.
1047 *
1048 * @since 1.0.0
1049 * @access public
1050 */
1051 public function admin_import_template_form() {
1052 if ( ! self::is_base_templates_screen() || ! User::is_current_user_can_upload_json() ) {
1053 return;
1054 }
1055
1056 /** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
1057 $ajax = Plugin::$instance->common->get_component( 'ajax' );
1058 ?>
1059 <div id="elementor-hidden-area">
1060 <a id="elementor-import-template-trigger" class="page-title-action button button-secondary"><?php echo esc_html__( 'Import Templates', 'elementor' ); ?></a>
1061 <div id="elementor-import-template-area">
1062 <div id="elementor-import-template-title"><?php echo esc_html__( 'Choose an Elementor template JSON file or a .zip archive of Elementor templates, and add them to the list of templates available in your library.', 'elementor' ); ?></div>
1063 <form id="elementor-import-template-form" method="post" action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" enctype="multipart/form-data">
1064 <input type="hidden" name="action" value="elementor_library_direct_actions">
1065 <input type="hidden" name="library_action" value="direct_import_template">
1066 <input type="hidden" name="_nonce" value="<?php Utils::print_unescaped_internal_string( $ajax->create_nonce() ); ?>">
1067 <fieldset id="elementor-import-template-form-inputs">
1068 <input type="file" name="file" accept=".json,application/json,.zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" required>
1069 <input id="e-import-template-action" type="submit" class="button" value="<?php echo esc_attr__( 'Import Now', 'elementor' ); ?>">
1070 </fieldset>
1071 </form>
1072 </div>
1073 </div>
1074 <?php
1075 }
1076
1077 /**
1078 * Block template frontend
1079 *
1080 * Don't display the single view of the template library post type in the
1081 * frontend, for users that don't have the proper permissions.
1082 *
1083 * Fired by `template_redirect` action.
1084 *
1085 * @since 1.0.0
1086 * @access public
1087 */
1088 public function block_template_frontend() {
1089 if ( is_singular( self::CPT ) && ! current_user_can( Editor::EDITING_CAPABILITY ) ) {
1090 wp_safe_redirect( site_url(), 301 );
1091 die;
1092 }
1093 }
1094
1095 /**
1096 * Is template library supports export.
1097 *
1098 * Whether the template library supports export.
1099 *
1100 * Template saved by the user locally on his site, support export by default
1101 * but this can be changed using a filter.
1102 *
1103 * @since 1.0.0
1104 * @access public
1105 *
1106 * @param int $template_id The template ID.
1107 *
1108 * @return bool Whether the template library supports export.
1109 */
1110 public function is_template_supports_export( $template_id ) {
1111 $export_support = true;
1112
1113 /**
1114 * Is template library supports export.
1115 *
1116 * Filters whether the template library supports export.
1117 *
1118 * @since 1.0.0
1119 *
1120 * @param bool $export_support Whether the template library supports export.
1121 * Default is true.
1122 * @param int $template_id Post ID.
1123 */
1124 $export_support = apply_filters( 'elementor/template_library/is_template_supports_export', $export_support, $template_id );
1125
1126 return $export_support;
1127 }
1128
1129 /**
1130 * Remove Elementor post state.
1131 *
1132 * Remove the 'elementor' post state from the display states of the post.
1133 *
1134 * Used to remove the 'elementor' post state from the template library items.
1135 *
1136 * Fired by `display_post_states` filter.
1137 *
1138 * @since 1.8.0
1139 * @access public
1140 *
1141 * @param array $post_states An array of post display states.
1142 * @param \WP_Post $post The current post object.
1143 *
1144 * @return array Updated array of post display states.
1145 */
1146 public function remove_elementor_post_state_from_library( $post_states, $post ) {
1147 if ( self::CPT === $post->post_type && isset( $post_states['elementor'] ) ) {
1148 unset( $post_states['elementor'] );
1149 }
1150 return $post_states;
1151 }
1152
1153 /**
1154 * Get template export link.
1155 *
1156 * Retrieve the link used to export a single template based on the template
1157 * ID.
1158 *
1159 * @since 2.0.0
1160 * @access private
1161 *
1162 * @param int $template_id The template ID.
1163 *
1164 * @return string Template export URL.
1165 */
1166 private function get_export_link( $template_id ) {
1167 // TODO: BC since 2.3.0 - Use `$ajax->create_nonce()`
1168 /** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
1169 // $ajax = Plugin::$instance->common->get_component( 'ajax' );
1170
1171 return add_query_arg(
1172 [
1173 'action' => 'elementor_library_direct_actions',
1174 'library_action' => 'export_template',
1175 'source' => $this->get_id(),
1176 '_nonce' => wp_create_nonce( 'elementor_ajax' ),
1177 'template_id' => $template_id,
1178 ],
1179 admin_url( 'admin-ajax.php' )
1180 );
1181 }
1182
1183 /**
1184 * On template save.
1185 *
1186 * Run this method when template is being saved.
1187 *
1188 * Fired by `save_post` action.
1189 *
1190 * @since 1.0.1
1191 * @access public
1192 *
1193 * @param int $post_id Post ID.
1194 * @param \WP_Post $post The current post object.
1195 */
1196 public function on_save_post( $post_id, \WP_Post $post ) {
1197 if ( self::CPT !== $post->post_type ) {
1198 return;
1199 }
1200
1201 if ( self::get_template_type( $post_id ) ) { // It's already with a type
1202 return;
1203 }
1204
1205 // Don't save type on import, the importer will do it.
1206 if ( did_action( 'import_start' ) ) {
1207 return;
1208 }
1209
1210 $this->save_item_type( $post_id, 'page' );
1211 }
1212
1213 /**
1214 * Save item type.
1215 *
1216 * When saving/updating templates, this method is used to update the post
1217 * meta data and the taxonomy.
1218 *
1219 * @since 1.0.1
1220 * @access private
1221 *
1222 * @param int $post_id Post ID.
1223 * @param string $type Item type.
1224 */
1225 private function save_item_type( $post_id, $type ) {
1226 update_post_meta( $post_id, Document::TYPE_META_KEY, $type );
1227
1228 wp_set_object_terms( $post_id, $type, self::TAXONOMY_TYPE_SLUG );
1229 }
1230
1231 /**
1232 * Bulk export action.
1233 *
1234 * Adds an 'Export' action to the Bulk Actions drop-down in the template
1235 * library.
1236 *
1237 * Fired by `bulk_actions-edit-elementor_library` filter.
1238 *
1239 * @since 1.6.0
1240 * @access public
1241 *
1242 * @param array $actions An array of the available bulk actions.
1243 *
1244 * @return array An array of the available bulk actions.
1245 */
1246 public function admin_add_bulk_export_action( $actions ) {
1247 $actions[ self::BULK_EXPORT_ACTION ] = esc_html__( 'Export', 'elementor' );
1248
1249 return $actions;
1250 }
1251
1252 /**
1253 * Add bulk export action.
1254 *
1255 * Handles the template library bulk export action.
1256 *
1257 * Fired by `handle_bulk_actions-edit-elementor_library` filter.
1258 *
1259 * @since 1.6.0
1260 * @access public
1261 *
1262 * @param string $redirect_to The redirect URL.
1263 * @param string $action The action being taken.
1264 * @param array $post_ids The items to take the action on.
1265 */
1266 public function admin_export_multiple_templates( $redirect_to, $action, $post_ids ) {
1267 if ( self::BULK_EXPORT_ACTION === $action ) {
1268 $result = $this->export_multiple_templates( $post_ids );
1269
1270 // If you reach this line, the export failed
1271 // PHPCS - Not user input.
1272 wp_die( $result->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1273 }
1274 }
1275
1276 /**
1277 * Print admin tabs.
1278 *
1279 * Used to output the template library tabs with their labels.
1280 *
1281 * Fired by `views_edit-elementor_library` filter.
1282 *
1283 * @since 2.0.0
1284 * @access public
1285 *
1286 * @param array $views An array of available list table views.
1287 *
1288 * @return array An updated array of available list table views.
1289 */
1290 public function admin_print_tabs( $views ) {
1291 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1292 $current_type = Utils::get_super_global_value( $_REQUEST, self::TAXONOMY_TYPE_SLUG ) ?? '';
1293 $active_class = $current_type ? '' : ' nav-tab-active';
1294 $current_tabs_group = $this->get_current_tab_group();
1295
1296 $url_args = [
1297 'post_type' => self::CPT,
1298 'tabs_group' => $current_tabs_group,
1299 ];
1300
1301 $baseurl = add_query_arg( $url_args, admin_url( 'edit.php' ) );
1302
1303 $filter = [
1304 'admin_tab_group' => $current_tabs_group,
1305 ];
1306 $operator = 'and';
1307
1308 if ( empty( $current_tabs_group ) ) {
1309 // Don't include 'not-supported' or other templates that don't set their `admin_tab_group`.
1310 $operator = 'NOT';
1311 }
1312
1313 $doc_types = Plugin::$instance->documents->get_document_types( $filter, $operator );
1314
1315 if ( 1 >= count( $doc_types ) ) {
1316 return $views;
1317 }
1318
1319 ?>
1320 <div id="elementor-template-library-tabs-wrapper" class="nav-tab-wrapper">
1321 <a class="nav-tab<?php echo esc_attr( $active_class ); ?>" href="<?php echo esc_url( $baseurl ); ?>">
1322 <?php
1323 $all_title = $this->get_library_title();
1324 if ( ! $all_title ) {
1325 $all_title = esc_html__( 'All', 'elementor' );
1326 }
1327 Utils::print_unescaped_internal_string( $all_title ); ?>
1328 </a>
1329 <?php
1330 foreach ( $doc_types as $type => $class_name ) :
1331 $active_class = '';
1332
1333 if ( $current_type === $type ) {
1334 $active_class = ' nav-tab-active';
1335 }
1336
1337 $type_url = esc_url( add_query_arg( self::TAXONOMY_TYPE_SLUG, $type, $baseurl ) );
1338 $type_label = $this->get_template_label_by_type( $type );
1339 Utils::print_unescaped_internal_string( "<a class='nav-tab{$active_class}' href='{$type_url}'>{$type_label}</a>" );
1340 endforeach;
1341 ?>
1342 </div>
1343 <?php
1344 return $views;
1345 }
1346
1347 /**
1348 * Maybe render blank state.
1349 *
1350 * When the template library has no saved templates, display a blank admin page offering
1351 * to create the very first template.
1352 *
1353 * Fired by `manage_posts_extra_tablenav` action.
1354 *
1355 * @since 2.0.0
1356 * @access public
1357 *
1358 * @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
1359 * @param array $args
1360 */
1361 public function maybe_render_blank_state( $which, array $args = [] ) {
1362 global $post_type;
1363
1364 $args = wp_parse_args( $args, [
1365 'cpt' => self::CPT,
1366 'post_type' => get_query_var( 'elementor_library_type' ),
1367 ] );
1368
1369 if ( $args['cpt'] !== $post_type || 'bottom' !== $which ) {
1370 return;
1371 }
1372
1373 global $wp_list_table;
1374
1375 $total_items = $wp_list_table->get_pagination_arg( 'total_items' );
1376
1377 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1378 if ( ! empty( $total_items ) || ! empty( $_REQUEST['s'] ) ) {
1379 return;
1380 }
1381
1382 $current_type = $args['post_type'];
1383
1384 $document_types = Plugin::instance()->documents->get_document_types();
1385
1386 if ( empty( $document_types[ $current_type ] ) ) {
1387 return;
1388 }
1389
1390 // TODO: Better way to exclude widget type.
1391 if ( 'widget' === $current_type ) {
1392 return;
1393 }
1394
1395 // TODO: This code maybe unreachable see if above `if ( empty( $document_types[ $current_type ] ) )`.
1396 if ( empty( $current_type ) ) {
1397 $counts = (array) wp_count_posts( self::CPT );
1398 unset( $counts['auto-draft'] );
1399 $count = array_sum( $counts );
1400
1401 if ( 0 < $count ) {
1402 return;
1403 }
1404
1405 $current_type = 'template';
1406
1407 $args['additional_inline_style'] = '#elementor-template-library-tabs-wrapper {display: none;}';
1408 }
1409
1410 $this->render_blank_state( $current_type, $args );
1411 }
1412
1413 private function render_blank_state( $current_type, array $args = [] ) {
1414 $current_type_label = $this->get_template_label_by_type( $current_type );
1415 $inline_style = '#posts-filter .wp-list-table, #posts-filter .tablenav.top, .tablenav.bottom .actions, .wrap .subsubsub { display:none;}';
1416
1417 $args = wp_parse_args( $args, [
1418 'additional_inline_style' => '',
1419 'href' => '',
1420 'description' => esc_html__( 'Add templates and reuse them across your website. Easily export and import them to any other project, for an optimized workflow.', 'elementor' ),
1421 ] );
1422 $inline_style .= $args['additional_inline_style'];
1423 ?>
1424 <style type="text/css"><?php Utils::print_unescaped_internal_string( $inline_style ); ?></style>
1425 <div class="elementor-template_library-blank_state">
1426 <?php $this->print_blank_state_template( $current_type_label, $args['href'], $args['description'] ); ?>
1427 </div>
1428 <?php
1429 }
1430
1431 /**
1432 * Print Blank State Template
1433 *
1434 * When the an entity (CPT, Taxonomy...etc) has no saved items, print a blank admin page offering
1435 * to create the very first item.
1436 *
1437 * This method is public because it needs to be accessed from outside the Source_Local
1438 *
1439 * @since 3.1.0
1440 * @access public
1441 *
1442 * @param string $current_type_label The Entity title.
1443 * @param string $href The URL for the 'Add New' button.
1444 * @param string $description The sub title describing the Entity (Post Type, Taxonomy, etc.).
1445 */
1446 public function print_blank_state_template( $current_type_label, $href, $description ) {
1447 ?>
1448 <div class="elementor-blank_state">
1449 <i class="eicon-folder"></i>
1450 <h3>
1451 <?php
1452 /* translators: %s: Template type label. */
1453 printf( esc_html__( 'Create Your First %s', 'elementor' ), esc_html( $current_type_label ) );
1454 ?>
1455 </h3>
1456 <p><?php echo wp_kses_post( $description ); ?></p>
1457 <a id="elementor-template-library-add-new" class="elementor-button e-primary" href="<?php echo esc_url( $href ); ?>">
1458 <?php
1459 /* translators: %s: Template type label. */
1460 printf( esc_html__( 'Add New %s', 'elementor' ), esc_html( $current_type_label ) );
1461 ?>
1462 </a>
1463 </div>
1464 <?php
1465 }
1466
1467 /**
1468 * Add filter by category.
1469 *
1470 * In the templates library, add a filter by Elementor library category.
1471 *
1472 * @access public
1473 *
1474 * @param string $post_type The post type slug.
1475 */
1476 public function add_filter_by_category( $post_type ) {
1477 if ( self::CPT !== $post_type ) {
1478 return;
1479 }
1480
1481 $all_items = get_taxonomy( self::TAXONOMY_CATEGORY_SLUG )->labels->all_items;
1482 $dropdown_options = [
1483 'show_option_all' => $all_items,
1484 'show_option_none' => $all_items,
1485 'hide_empty' => 0,
1486 'hierarchical' => 1,
1487 'show_count' => 0,
1488 'orderby' => 'name',
1489 'value_field' => 'slug',
1490 'taxonomy' => self::TAXONOMY_CATEGORY_SLUG,
1491 'name' => self::TAXONOMY_CATEGORY_SLUG,
1492 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1493 'selected' => Utils::get_super_global_value( $_GET, self::TAXONOMY_CATEGORY_SLUG ) ?? '',
1494 ];
1495
1496 printf(
1497 '<label class="screen-reader-text" for="%1$s">%2$s</label>',
1498 esc_attr( self::TAXONOMY_CATEGORY_SLUG ),
1499 esc_html_x( 'Filter by category', 'Template Library', 'elementor' )
1500 );
1501 wp_dropdown_categories( $dropdown_options );
1502 }
1503
1504 /**
1505 * Import single template.
1506 *
1507 * Import template from a file to the database.
1508 *
1509 * @since 1.6.0
1510 * @access private
1511 *
1512 * @param string $file_path File name.
1513 *
1514 * @return \WP_Error|int|array Local template array, or template ID, or
1515 * `WP_Error`.
1516 */
1517 private function import_single_template( $file_path ) {
1518 $data = $this->prepare_import_template_data( $file_path );
1519
1520 if ( is_wp_error( $data ) ) {
1521 return $data;
1522 }
1523
1524 if ( empty( $data ) ) {
1525 return new \WP_Error( 'file_error', 'Invalid File' );
1526 }
1527
1528 $template_id = $this->save_item( [
1529 'content' => $data['content'],
1530 'title' => $data['title'],
1531 'type' => $data['type'],
1532 'page_settings' => $data['page_settings'],
1533 ] );
1534
1535 if ( is_wp_error( $template_id ) ) {
1536 return $template_id;
1537 }
1538
1539 return $this->get_item( $template_id );
1540 }
1541
1542 /**
1543 * Prepare template to export.
1544 *
1545 * Retrieve the relevant template data and return them as an array.
1546 *
1547 * @since 1.6.0
1548 * @access private
1549 *
1550 * @param int $template_id The template ID.
1551 *
1552 * @return \WP_Error|array Exported template data.
1553 */
1554 private function prepare_template_export( $template_id ) {
1555 $document = Plugin::$instance->documents->get( $template_id );
1556
1557 $template_data = $document->get_export_data();
1558
1559 if ( empty( $template_data['content'] ) ) {
1560 return new \WP_Error( 'empty_template', 'The template is empty' );
1561 }
1562
1563 $content = apply_filters(
1564 'elementor/template_library/sources/local/export/elements',
1565 $template_data['content']
1566 );
1567
1568 $export_data = [
1569 'content' => $content,
1570 'page_settings' => $template_data['settings'],
1571 'version' => DB::DB_VERSION,
1572 'title' => $document->get_main_post()->post_title,
1573 'type' => self::get_template_type( $template_id ),
1574 ];
1575
1576 return [
1577 'name' => 'elementor-' . $template_id . '-' . gmdate( 'Y-m-d' ) . '.json',
1578 'content' => wp_json_encode( $export_data ),
1579 ];
1580 }
1581
1582 /**
1583 * Get template label by type.
1584 *
1585 * Retrieve the template label for any given template type.
1586 *
1587 * @since 2.0.0
1588 * @access private
1589 *
1590 * @param string $template_type Template type.
1591 *
1592 * @return string Template label.
1593 */
1594 private function get_template_label_by_type( $template_type ) {
1595 $document_types = Plugin::instance()->documents->get_document_types();
1596
1597 if ( isset( $document_types[ $template_type ] ) ) {
1598 $template_label = call_user_func( [ $document_types[ $template_type ], 'get_title' ] );
1599 } else {
1600 $template_label = ucwords( str_replace( [ '_', '-' ], ' ', $template_type ) );
1601 }
1602
1603 /**
1604 * Template label by template type.
1605 *
1606 * Filters the template label by template type in the template library .
1607 *
1608 * @since 2.0.0
1609 *
1610 * @param string $template_label Template label.
1611 * @param string $template_type Template type.
1612 */
1613 $template_label = apply_filters( 'elementor/template-library/get_template_label_by_type', $template_label, $template_type );
1614
1615 return $template_label;
1616 }
1617
1618 /**
1619 * Filter template types in admin query.
1620 *
1621 * Update the template types in the main admin query.
1622 *
1623 * Fired by `parse_query` action.
1624 *
1625 * @since 2.4.0
1626 * @access public
1627 *
1628 * @param \WP_Query $query The `WP_Query` instance.
1629 */
1630 public function admin_query_filter_types( \WP_Query $query ) {
1631 if ( ! $this->is_current_screen() || ! empty( $query->query_vars['meta_key'] ) ) {
1632 return;
1633 }
1634
1635 $current_tabs_group = $this->get_current_tab_group();
1636
1637 if ( isset( $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] ) && '-1' === $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] ) {
1638 unset( $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] );
1639 }
1640
1641 if ( empty( $current_tabs_group ) ) {
1642 return;
1643 }
1644
1645 $doc_types = Plugin::$instance->documents->get_document_types( [
1646 'admin_tab_group' => $current_tabs_group,
1647 ] );
1648
1649 $query->query_vars['meta_key'] = Document::TYPE_META_KEY;
1650 $query->query_vars['meta_value'] = array_keys( $doc_types );
1651 }
1652
1653 /**
1654 * Add template library actions.
1655 *
1656 * Register filters and actions for the template library.
1657 *
1658 * @since 2.0.0
1659 * @access private
1660 */
1661 private function add_actions() {
1662 if ( is_admin() ) {
1663 add_action( 'elementor/admin/menu/register', function ( Admin_Menu_Manager $admin_menu ) {
1664 $this->register_admin_menu( $admin_menu );
1665 }, static::ADMIN_MENU_PRIORITY );
1666
1667 add_action( 'elementor/editor-one/menu/register', function ( Menu_Data_Provider $menu_data_provider ) {
1668 $this->register_editor_one_menu( $menu_data_provider );
1669 } );
1670
1671 add_action( 'elementor/editor-one/menu/excluded_level4_slugs', function ( array $excluded_slugs ): array {
1672 $excluded_slugs[] = 'edit.php?post_type=elementor_library#add_new';
1673 $excluded_slugs[] = 'edit-tags.php?taxonomy=elementor_library_category&amp;post_type=elementor_library';
1674 return $excluded_slugs;
1675 } );
1676
1677 add_filter( 'elementor/editor-one/menu/elementor_post_types', function ( array $elementor_post_types ): array {
1678 $elementor_post_types[ self::CPT ] = [];
1679
1680 return $elementor_post_types;
1681 } );
1682
1683 add_action( 'elementor/admin/menu/register', function ( Admin_Menu_Manager $admin_menu ) {
1684 $this->admin_menu_reorder( $admin_menu );
1685 }, 800 );
1686
1687 add_action( 'elementor/admin/menu/after_register', function () {
1688 $this->admin_menu_set_current();
1689 } );
1690
1691 add_filter( 'admin_title', [ $this, 'admin_title' ], 10, 2 );
1692 add_action( 'all_admin_notices', [ $this, 'replace_admin_heading' ] );
1693 add_filter( 'post_row_actions', [ $this, 'post_row_actions' ], 10, 2 );
1694 add_action( 'admin_footer', [ $this, 'admin_import_template_form' ] );
1695 add_action( 'save_post', [ $this, 'on_save_post' ], 10, 2 );
1696 add_filter( 'display_post_states', [ $this, 'remove_elementor_post_state_from_library' ], 11, 2 );
1697
1698 add_action( 'parse_query', [ $this, 'admin_query_filter_types' ] );
1699
1700 // Template filter by category.
1701 add_action( 'restrict_manage_posts', [ $this, 'add_filter_by_category' ] );
1702
1703 // Template type column.
1704 add_action( 'manage_' . self::CPT . '_posts_columns', [ $this, 'admin_columns_headers' ] );
1705 add_action( 'manage_' . self::CPT . '_posts_custom_column', [ $this, 'admin_columns_content' ], 10, 2 );
1706
1707 // Template library bulk actions.
1708 add_filter( 'bulk_actions-edit-elementor_library', [ $this, 'admin_add_bulk_export_action' ] );
1709 add_filter( 'handle_bulk_actions-edit-elementor_library', [ $this, 'admin_export_multiple_templates' ], 10, 3 );
1710
1711 // Print template library tabs.
1712 add_filter( 'views_edit-' . self::CPT, [ $this, 'admin_print_tabs' ] );
1713
1714 // Show blank state.
1715 add_action( 'manage_posts_extra_tablenav', [ $this, 'maybe_render_blank_state' ] );
1716 }
1717
1718 add_action( 'elementor/document/after_save', [ $this, 'on_template_update' ], 10, 2 );
1719
1720 add_action( 'template_redirect', [ $this, 'block_template_frontend' ] );
1721
1722 // Remove elementor library templates from WP Sitemap
1723 add_filter(
1724 'wp_sitemaps_post_types',
1725 function( $post_types ) {
1726 return $this->remove_elementor_cpt_from_sitemap( $post_types );
1727 }
1728 );
1729 }
1730
1731 public function on_template_update( \Elementor\Core\Base\Document $document, array $data ) {
1732 if ( ! empty( $data['post_title'] ) ) {
1733 wp_update_post( [
1734 'ID' => $document->get_main_id(),
1735 'post_title' => $data['post_title'],
1736 ] );
1737 }
1738 }
1739
1740 /**
1741 * @since 2.0.6
1742 * @access public
1743 */
1744 public function admin_columns_content( $column_name, $post_id ) {
1745 if ( 'elementor_library_type' === $column_name ) {
1746 /** @var Document $document */
1747 $document = Plugin::$instance->documents->get( $post_id );
1748
1749 if ( $document && $document instanceof Library_Document ) {
1750 $document->print_admin_column_type();
1751 }
1752 }
1753 }
1754
1755 /**
1756 * @since 2.0.6
1757 * @access public
1758 */
1759 public function admin_columns_headers( $posts_columns ) {
1760 // Replace original column that bind to the taxonomy - with another column.
1761 unset( $posts_columns['taxonomy-elementor_library_type'] );
1762
1763 $offset = 2;
1764
1765 $posts_columns = array_slice( $posts_columns, 0, $offset, true ) + [
1766 'elementor_library_type' => esc_html__( 'Type', 'elementor' ),
1767 ] + array_slice( $posts_columns, $offset, null, true );
1768
1769 return $posts_columns;
1770 }
1771
1772 public function get_current_tab_group() {
1773 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not required here.
1774 $current_tabs_group = Utils::get_super_global_value( $_REQUEST, 'tabs_group' ) ?? '';
1775 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not required here.
1776 $type_slug = Utils::get_super_global_value( $_REQUEST, self::TAXONOMY_TYPE_SLUG );
1777
1778 if ( $type_slug ) {
1779 $doc_type = Plugin::$instance->documents->get_document_type( $type_slug, '' );
1780 if ( $doc_type ) {
1781 $current_tabs_group = $doc_type::get_property( 'admin_tab_group' );
1782 }
1783 }
1784 return $current_tabs_group;
1785 }
1786
1787 private function get_library_title() {
1788 $title = '';
1789
1790 if ( $this->is_current_screen() ) {
1791 $current_tab_group = $this->get_current_tab_group();
1792
1793 if ( $current_tab_group ) {
1794 $titles = [
1795 'library' => esc_html__( 'Saved Templates', 'elementor' ),
1796 'theme' => esc_html__( 'Theme Builder', 'elementor' ),
1797 'popup' => esc_html__( 'Popups', 'elementor' ),
1798 ];
1799
1800 if ( ! empty( $titles[ $current_tab_group ] ) ) {
1801 $title = $titles[ $current_tab_group ];
1802 }
1803 }
1804 }
1805
1806 return $title;
1807 }
1808
1809 private function is_current_screen() {
1810 global $pagenow, $typenow;
1811
1812 return 'edit.php' === $pagenow && self::CPT === $typenow;
1813 }
1814
1815 /**
1816 * @param array $post_types
1817 *
1818 * @return array
1819 */
1820 private function remove_elementor_cpt_from_sitemap( array $post_types ) {
1821 unset( $post_types[ self::CPT ] );
1822
1823 return $post_types;
1824 }
1825
1826 private function avoid_rest_access_for_non_admins(): void {
1827 add_filter( 'rest_pre_dispatch', function ( $value, \WP_REST_Server $server, \WP_REST_Request $request ) {
1828 if ( strpos( $request->get_route(), self::CPT ) !== false ) {
1829 if ( ! current_user_can( 'manage_options' ) ) {
1830 return new \WP_Error( 'rest_forbidden', esc_html__( 'Sorry, you are not allowed to do that.', 'elementor' ), [ 'status' => rest_authorization_required_code() ] );
1831 }
1832 }
1833
1834 return $value;
1835 }, 10, 3 );
1836 }
1837
1838 public function save_bulk_items( array $args = [] ) {
1839 $items = [];
1840
1841 foreach ( $args as $item ) {
1842 $items[] = $this->save_item( [
1843 'content' => $item['content'],
1844 'title' => $item['title'],
1845 'type' => $item['type'],
1846 'page_settings' => $item['page_settings'],
1847 ] );
1848 }
1849
1850 return $items;
1851 }
1852
1853 /**
1854 * Template library local source constructor.
1855 *
1856 * Initializing the template library local source base by registering custom
1857 * template data and running custom actions.
1858 *
1859 * @since 1.0.0
1860 * @access public
1861 */
1862 public function __construct() {
1863 parent::__construct();
1864
1865 $this->add_actions();
1866 }
1867
1868 public function format_args_for_bulk_action( $args ) {
1869 $bulk_args = [];
1870
1871 foreach ( $args['from_template_id'] as $from_template_id ) {
1872 if ( ! $this->is_allowed_to_read_template( [
1873 'template_id' => $from_template_id,
1874 ] ) ) {
1875 continue;
1876 }
1877
1878 $document = Plugin::$instance->documents->get( $from_template_id );
1879
1880 if ( ! $document ) {
1881 continue;
1882 }
1883
1884 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $from_template_id );
1885
1886 $bulk_args[] = array_merge(
1887 $args,
1888 [
1889 'title' => $document->get_post()->post_title,
1890 'type' => $document::get_type(),
1891 'content' => $document->get_elements_data(),
1892 'page_settings' => $page->get_data( 'settings' ),
1893 ]
1894 );
1895 }
1896
1897 return $bulk_args;
1898 }
1899
1900 public function format_args_for_single_action( $args ) {
1901 if ( ! $this->is_allowed_to_read_template( [
1902 'template_id' => $args['from_template_id'],
1903 ] ) ) {
1904 return new \WP_Error(
1905 'template_error',
1906 esc_html__( 'You do not have permission to access this template.', 'elementor' )
1907 );
1908 }
1909
1910 $document = Plugin::$instance->documents->get( $args['from_template_id'] );
1911
1912 if ( ! $document ) {
1913 return new \WP_Error( 'template_error', 'Document not found.' );
1914 }
1915
1916 $args['content'] = $document->get_elements_data();
1917
1918 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $args['from_template_id'] );
1919 $args['page_settings'] = $page->get_data( 'settings' );
1920
1921 return $args;
1922 }
1923
1924 public function is_allowed_to_read_template( array $args ): bool {
1925 if ( null === $this->wordpress_adapter ) {
1926 $this->set_wordpress_adapter( new WordPress_Adapter() );
1927 }
1928
1929 if ( ! $this->should_check_permissions( $args ) ) {
1930 return true;
1931 }
1932
1933 $post_id = intval( $args['template_id'] );
1934 $post_status = $this->wordpress_adapter->get_post_status( $post_id );
1935 $is_private_or_non_published = ( 'private' === $post_status && ! $this->wordpress_adapter->current_user_can( 'read_private_posts', $post_id ) ) || ( 'publish' !== $post_status );
1936
1937 $can_read_template = $is_private_or_non_published || $this->wordpress_adapter->current_user_can( 'edit_post', $post_id );
1938
1939 return apply_filters( 'elementor/template-library/is_allowed_to_read_template', $can_read_template, $args );
1940 }
1941
1942 private function should_check_permissions( array $args ): bool {
1943 if ( null === $this->elementor_adapter ) {
1944 $this->set_elementor_adapter( new Elementor_Adapter() );
1945 }
1946
1947 $check_permissions = isset( $args['check_permissions'] ) && false === $args['check_permissions'];
1948
1949 if ( $check_permissions ) {
1950 return false;
1951 }
1952
1953 return true;
1954 }
1955
1956 public function set_wordpress_adapter( Wordpress_Adapter_Interface $wordpress_adapter ) {
1957 $this->wordpress_adapter = $wordpress_adapter;
1958 }
1959
1960 public function set_elementor_adapter( Elementor_Adapter_Interface $elementor_adapter ): void {
1961 $this->elementor_adapter = $elementor_adapter;
1962 }
1963 }
1964