PluginProbe
Elementor Website Builder – more than just a page builder / 3.35.9
Elementor Website Builder – more than just a page builder v3.35.9
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.35.9, at includes/template-library/sources/local.php

2,119 lines 60.5 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 if ( ! $this->is_current_screen() ) {
451 return;
452 }
453
454 global $post_type_object;
455
456 $library_title = $this->get_library_title();
457
458 if ( $library_title ) {
459 $post_type_object->labels->name = $library_title;
460 }
461
462 $labels = $this->get_current_template_labels();
463 $template_singular = $labels['singular'];
464 $template_plural = $labels['plural'];
465
466 if ( ! $template_plural && $library_title ) {
467 $template_plural = $library_title;
468 }
469
470 if ( $template_singular ) {
471 $labels = $post_type_object->labels;
472 $labels->name = $template_plural;
473 $labels->singular_name = $template_singular;
474 /* translators: %s: Template label (plural). */
475 $labels->all_items = sprintf( esc_html__( 'All %s', 'elementor' ), $template_plural );
476 /* translators: %s: Template label (singular). */
477 $labels->add_new = sprintf( esc_html__( 'Add New %s', 'elementor' ), $template_singular );
478 $labels->add_new_item = $labels->add_new;
479 /* translators: %s: Template label (singular). */
480 $labels->edit_item = sprintf( esc_html__( 'Edit %s', 'elementor' ), $template_singular );
481 /* translators: %s: Template label (singular). */
482 $labels->new_item = sprintf( esc_html__( 'New %s', 'elementor' ), $template_singular );
483 /* translators: %s: Template label (singular). */
484 $labels->view_item = sprintf( esc_html__( 'View %s', 'elementor' ), $template_singular );
485 /* translators: %s: Template label (plural). */
486 $labels->search_items = sprintf( esc_html__( 'Search %s', 'elementor' ), $template_plural );
487 /* translators: %s: Template label (plural). */
488 $labels->not_found = sprintf( esc_html__( 'No %s found', 'elementor' ), $template_plural );
489 /* translators: %s: Template label (plural). */
490 $labels->not_found_in_trash = sprintf( esc_html__( 'No %s found in Trash', 'elementor' ), $template_plural );
491 /* translators: %s: Template label (singular). */
492 $labels->parent_item_colon = sprintf( esc_html__( 'Parent %s:', 'elementor' ), $template_singular );
493 $labels->menu_name = $template_plural;
494 $post_type_object->labels = $labels;
495 }
496 }
497
498 /**
499 * Get local templates.
500 *
501 * Retrieve local templates saved by the user on his site.
502 *
503 * @since 1.0.0
504 * @access public
505 *
506 * @param array $args Optional. Filter templates based on a set of
507 * arguments. Default is an empty array.
508 *
509 * @return array Local templates.
510 */
511 public function get_items( $args = [] ) {
512 $template_types = array_values( self::$template_types );
513
514 if ( ! empty( $args['type'] ) ) {
515 $template_types = $args['type'];
516 unset( $args['type'] );
517 }
518
519 $defaults = [
520 'post_type' => self::CPT,
521 'post_status' => 'publish',
522 'posts_per_page' => -1,
523 'orderby' => 'title',
524 'order' => 'ASC',
525 'meta_query' => [
526 [
527 'key' => Document::TYPE_META_KEY,
528 'value' => $template_types,
529 ],
530 ],
531 ];
532
533 $query_args = wp_parse_args( $args, $defaults );
534
535 $templates_query = new \WP_Query( $query_args );
536
537 $templates = [];
538
539 if ( $templates_query->have_posts() ) {
540 foreach ( $templates_query->get_posts() as $post ) {
541 $templates[] = $this->get_item( $post->ID );
542 }
543 }
544
545 return $templates;
546 }
547
548 /**
549 * Save local template.
550 *
551 * Save new or update existing template on the database.
552 *
553 * @since 1.0.0
554 * @access public
555 *
556 * @param array $template_data Local template data.
557 *
558 * @return \WP_Error|int The ID of the saved/updated template, `WP_Error` otherwise.
559 */
560 public function save_item( $template_data ) {
561 if ( ! current_user_can( $this->post_type_object->cap->edit_posts ) ) {
562 return new \WP_Error( 'save_error', esc_html__( 'Access denied.', 'elementor' ) );
563 }
564
565 $defaults = [
566 'title' => esc_html__( '(no title)', 'elementor' ),
567 'page_settings' => [],
568 ];
569
570 $template_data = wp_parse_args( $template_data, $defaults );
571 $template_data['status'] = current_user_can( 'publish_posts' ) ? 'publish' : 'pending';
572
573 // BC: Allow importing any template type when using CLI
574 // to support users that rely on this mechanism.
575 $should_check_template_type = ! $this->is_wp_cli();
576
577 if (
578 $should_check_template_type &&
579 ! $this->is_valid_template_type( $template_data['type'] )
580 ) {
581 return new \WP_Error( 'invalid_template_type', esc_html__( 'Invalid template type.', 'elementor' ) );
582 }
583
584 $document = Plugin::$instance->documents->create(
585 $template_data['type'],
586 [
587 'post_title' => $template_data['title'],
588 'post_status' => $template_data['status'],
589 ]
590 );
591
592 if ( is_wp_error( $document ) ) {
593 /**
594 * @var \WP_Error $document
595 */
596 return $document;
597 }
598
599 if ( ! empty( $template_data['content'] ) ) {
600 $template_data['content'] = $this->replace_elements_ids( $template_data['content'] );
601 }
602
603 $document->save( [
604 'elements' => $template_data['content'],
605 'settings' => $template_data['page_settings'],
606 ] );
607
608 $template_id = $document->get_main_id();
609
610 /**
611 * After template library save.
612 *
613 * Fires after Elementor template library was saved.
614 *
615 * @since 1.0.1
616 *
617 * @param int $template_id The ID of the template.
618 * @param array $template_data The template data.
619 */
620 do_action( 'elementor/template-library/after_save_template', $template_id, $template_data );
621
622 /**
623 * After template library update.
624 *
625 * Fires after Elementor template library was updated.
626 *
627 * @since 1.0.1
628 *
629 * @param int $template_id The ID of the template.
630 * @param array $template_data The template data.
631 */
632 do_action( 'elementor/template-library/after_update_template', $template_id, $template_data );
633
634 return $template_id;
635 }
636
637 protected function is_valid_template_type( $type ) {
638 $document_class = Plugin::$instance->documents->get_document_type( $type, false );
639
640 if ( ! $document_class ) {
641 return false;
642 }
643
644 $cpt = $document_class::get_property( 'cpt' );
645
646 if ( ! $cpt || ! is_array( $cpt ) || 1 !== count( $cpt ) ) {
647 return false;
648 }
649
650 $is_valid_template_type = in_array( static::CPT, $cpt, true );
651
652 return apply_filters(
653 'elementor/template_library/sources/local/is_valid_template_type',
654 $is_valid_template_type,
655 $cpt,
656 );
657 }
658
659 /** For testing purposes only, in order to be able to mock the `WP_CLI` constant. */
660 protected function is_wp_cli() {
661 return Utils::is_wp_cli();
662 }
663
664 /**
665 * Update local template.
666 *
667 * Update template on the database.
668 *
669 * @since 1.0.0
670 * @access public
671 *
672 * @param array $new_data New template data.
673 *
674 * @return \WP_Error|true True if template updated, `WP_Error` otherwise.
675 */
676 public function update_item( $new_data ) {
677 if ( ! current_user_can( $this->post_type_object->cap->edit_post, $new_data['id'] ) ) {
678 return new \WP_Error( 'save_error', esc_html__( 'Access denied.', 'elementor' ) );
679 }
680
681 $document = Plugin::$instance->documents->get( $new_data['id'] );
682
683 if ( ! $document ) {
684 return new \WP_Error( 'save_error', esc_html__( 'Template not exist.', 'elementor' ) );
685 }
686
687 $save_data = [];
688
689 if ( isset( $new_data['title'] ) ) {
690 $save_data['post_title'] = $new_data['title'];
691 }
692
693 if ( isset( $new_data['content'] ) ) {
694 $save_data['elements'] = $new_data['content'];
695 }
696
697 $document->save( $save_data );
698
699 /**
700 * After template library update.
701 *
702 * Fires after Elementor template library was updated.
703 *
704 * @since 1.0.0
705 *
706 * @param int $new_data_id The ID of the new template.
707 * @param array $new_data The new template data.
708 */
709 do_action( 'elementor/template-library/after_update_template', $new_data['id'], $new_data );
710
711 return true;
712 }
713
714 /**
715 * Get local template.
716 *
717 * Retrieve a single local template saved by the user on his site.
718 *
719 * @since 1.0.0
720 * @access public
721 *
722 * @param int $template_id The template ID.
723 *
724 * @return array Local template.
725 */
726 public function get_item( $template_id ) {
727 $post = get_post( $template_id );
728
729 $user = get_user_by( 'id', $post->post_author );
730
731 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $template_id );
732
733 $page_settings = $page->get_data( 'settings' );
734
735 $date = strtotime( $post->post_date );
736
737 $data = [
738 'template_id' => $post->ID,
739 'source' => $this->get_id(),
740 'type' => self::get_template_type( $post->ID ),
741 'title' => $post->post_title,
742 'thumbnail' => get_the_post_thumbnail_url( $post ),
743 'date' => $date,
744 'human_date' => date_i18n( get_option( 'date_format' ), $date ),
745 'human_modified_date' => date_i18n( get_option( 'date_format' ), strtotime( $post->post_modified ) ),
746 'author' => $user->display_name,
747 'status' => $post->post_status,
748 'hasPageSettings' => ! empty( $page_settings ),
749 'tags' => [],
750 'export_link' => $this->get_export_link( $template_id ),
751 'url' => get_permalink( $post->ID ),
752 ];
753
754 /**
755 * Get template library template.
756 *
757 * Filters the template data when retrieving a single template from the
758 * template library.
759 *
760 * @since 1.0.0
761 *
762 * @param array $data Template data.
763 */
764 $data = apply_filters( 'elementor/template-library/get_template', $data );
765
766 return $data;
767 }
768
769 /**
770 * Get template data.
771 *
772 * Retrieve the data of a single local template saved by the user on his site.
773 *
774 * @since 1.5.0
775 * @access public
776 *
777 * @param array $args Custom template arguments.
778 *
779 * @return array Local template data.
780 */
781 public function get_data( array $args ) {
782 $template_id = $args['template_id'];
783
784 $document = Plugin::$instance->documents->get( $template_id );
785 $content = [];
786
787 if ( $document ) {
788 // TODO: Validate the data (in JS too!).
789 if ( ! empty( $args['display'] ) ) {
790 $content = $document->get_elements_raw_data( null, true );
791 } else {
792 $content = $document->get_elements_data();
793 }
794
795 if ( ! empty( $content ) ) {
796 $content = $this->replace_elements_ids( $content );
797
798 /**
799 * Filters the template content data.
800 *
801 * This filter allows third-party plugins to modify template content
802 * when loaded via get_template_data(), making the behavior consistent
803 * with Frontend::get_builder_content().
804 *
805 * @since 3.34.0
806 *
807 * @param array $content The template content data.
808 * @param int $template_id The template ID.
809 */
810 $content = apply_filters( 'elementor/frontend/builder_content_data', $content, $template_id );
811 }
812 }
813
814 $data = [
815 'content' => $content,
816 ];
817
818 if ( ! empty( $args['with_page_settings'] ) ) {
819 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $args['template_id'] );
820
821 $data['page_settings'] = $page->get_data( 'settings' );
822 }
823
824 return $data;
825 }
826
827 /**
828 * Delete local template.
829 *
830 * Delete template from the database.
831 *
832 * @since 1.0.0
833 * @access public
834 *
835 * @param int $template_id The template ID.
836 *
837 * @return \WP_Post|\WP_Error|false|null Post data on success, false or null
838 * or 'WP_Error' on failure.
839 */
840 public function delete_template( $template_id ) {
841 if ( ! current_user_can( $this->post_type_object->cap->delete_post, $template_id ) ) {
842 return new \WP_Error( 'template_error', esc_html__( 'Access denied.', 'elementor' ) );
843 }
844
845 return wp_delete_post( $template_id, true );
846 }
847
848 public function bulk_delete_items( array $template_ids ) {
849 foreach ( $template_ids as $template_id ) {
850 if ( ! current_user_can( $this->post_type_object->cap->delete_post, $template_id ) ) {
851 return new \WP_Error( 'template_error', esc_html__( 'Access denied.', 'elementor' ) );
852 }
853 }
854
855 foreach ( $template_ids as $template_id ) {
856 wp_delete_post( $template_id, true );
857 }
858
859 return true;
860 }
861
862 /**
863 * Export local template.
864 *
865 * Export template to a file.
866 *
867 * @since 1.0.0
868 * @access public
869 *
870 * @param int $template_id The template ID.
871 *
872 * @return \WP_Error WordPress error if template export failed.
873 */
874 public function export_template( $template_id ) {
875 $permissions_error = $this->validate_template_export_permissions( $template_id );
876
877 if ( is_wp_error( $permissions_error ) ) {
878 return $permissions_error;
879 }
880
881 $file_data = $this->prepare_template_export( $template_id );
882
883 if ( is_wp_error( $file_data ) ) {
884 return $file_data;
885 }
886
887 $this->send_file_headers( $file_data['name'], strlen( $file_data['content'] ) );
888
889 $this->serve_file( $file_data['content'] );
890
891 die;
892 }
893
894 private function validate_template_export_permissions( $template_id ) {
895 $post_id = intval( $template_id );
896 if ( get_post_type( $post_id ) !== self::CPT ) {
897 return new \WP_Error( 'template_error', esc_html__( 'Invalid template type or template does not exist.', 'elementor' ) );
898 }
899
900 $post_status = get_post_status( $post_id );
901 if ( 'private' === $post_status && ! current_user_can( 'read_private_posts', $post_id ) ) {
902 return new \WP_Error( 'template_error', esc_html__( 'You do not have permission to access this template.', 'elementor' ) );
903 }
904
905 if ( 'publish' !== $post_status && ! current_user_can( 'edit_post', $post_id ) ) {
906 return new \WP_Error( 'template_error', esc_html__( 'You do not have permission to export this template.', 'elementor' ) );
907 }
908
909 return null;
910 }
911
912 /**
913 * Export multiple local templates.
914 *
915 * Export multiple template to a ZIP file.
916 *
917 * @since 1.6.0
918 * @access public
919 *
920 * @param array $template_ids An array of template IDs.
921 *
922 * @return \WP_Error WordPress error if export failed.
923 */
924 public function export_multiple_templates( array $template_ids ) {
925 $files = [];
926
927 $wp_upload_dir = wp_upload_dir();
928
929 $temp_path = $wp_upload_dir['basedir'] . '/' . self::TEMP_FILES_DIR;
930
931 // Create temp path if it doesn't exist
932 wp_mkdir_p( $temp_path );
933
934 // Create all json files
935 foreach ( $template_ids as $template_id ) {
936 $file_data = $this->prepare_template_export( $template_id );
937
938 if ( is_wp_error( $file_data ) ) {
939 continue;
940 }
941
942 $complete_path = $temp_path . '/' . $file_data['name'];
943
944 $put_contents = file_put_contents( $complete_path, $file_data['content'] );
945
946 if ( ! $put_contents ) {
947 return new \WP_Error( '404', sprintf( 'Cannot create file "%s".', $file_data['name'] ) );
948 }
949
950 $files[] = [
951 'path' => $complete_path,
952 'name' => $file_data['name'],
953 ];
954 }
955
956 if ( ! $files ) {
957 return new \WP_Error( 'empty_files', 'There is no files to export (probably all the requested templates are empty).' );
958 }
959
960 // Create temporary .zip file
961 $zip_archive_filename = 'elementor-templates-' . gmdate( 'Y-m-d' ) . '.zip';
962
963 $zip_archive = new \ZipArchive();
964
965 $zip_complete_path = $temp_path . '/' . $zip_archive_filename;
966
967 $zip_archive->open( $zip_complete_path, \ZipArchive::CREATE );
968
969 foreach ( $files as $file ) {
970 $zip_archive->addFile( $file['path'], $file['name'] );
971 }
972
973 $zip_archive->close();
974
975 foreach ( $files as $file ) {
976 unlink( $file['path'] );
977 }
978
979 $this->send_file_headers( $zip_archive_filename, $this->filesize( $zip_complete_path ) );
980
981 $this->serve_zip( $zip_complete_path );
982
983 unlink( $zip_complete_path );
984
985 die;
986 }
987
988 /**
989 * Import local template.
990 *
991 * Import template from a file.
992 *
993 * @since 1.0.0
994 * @access public
995 *
996 * @param string $name - The file name.
997 * @param string $path - The file path.
998 * @return \WP_Error|array An array of items on success, 'WP_Error' on failure.
999 */
1000 public function import_template( $name, $path ) {
1001 if ( empty( $path ) ) {
1002 return new \WP_Error( 'file_error', 'Please upload a file to import' );
1003 }
1004
1005 // Set the Request's state as an Elementor upload request, in order to support unfiltered file uploads.
1006 Plugin::$instance->uploads_manager->set_elementor_upload_state( true );
1007
1008 $items = [];
1009
1010 // If the import file is a Zip file with potentially multiple JSON files
1011 if ( 'zip' === pathinfo( $name, PATHINFO_EXTENSION ) ) {
1012 $extracted_files = Plugin::$instance->uploads_manager->extract_and_validate_zip( $path, [ 'json' ] );
1013
1014 if ( is_wp_error( $extracted_files ) ) {
1015 // Delete the temporary extraction directory, since it's now not necessary.
1016 Plugin::$instance->uploads_manager->remove_file_or_dir( $extracted_files['extraction_directory'] );
1017
1018 return $extracted_files;
1019 }
1020
1021 foreach ( $extracted_files['files'] as $file_path ) {
1022 // Skip macOS metadata files and folders
1023 if ( false !== strpos( $file_path, '__MACOSX' ) || '.' === basename( $file_path )[0] ) {
1024 continue;
1025 }
1026
1027 $import_result = $this->import_single_template( $file_path );
1028
1029 if ( is_wp_error( $import_result ) ) {
1030 // Skip failed files
1031 continue;
1032 }
1033
1034 $items[] = $import_result;
1035 }
1036
1037 // Delete the temporary extraction directory, since it's now not necessary.
1038 Plugin::$instance->uploads_manager->remove_file_or_dir( $extracted_files['extraction_directory'] );
1039 } else {
1040 // If the import file is a single JSON file
1041 $import_result = $this->import_single_template( $path );
1042
1043 if ( is_wp_error( $import_result ) ) {
1044 return $import_result;
1045 }
1046
1047 $items[] = $import_result;
1048 }
1049
1050 return $items;
1051 }
1052
1053 /**
1054 * Post row actions.
1055 *
1056 * Add an export link to the template library action links table list.
1057 *
1058 * Fired by `post_row_actions` filter.
1059 *
1060 * @since 1.0.0
1061 * @access public
1062 *
1063 * @param array $actions An array of row action links.
1064 * @param \WP_Post $post The post object.
1065 *
1066 * @return array An updated array of row action links.
1067 */
1068 public function post_row_actions( $actions, \WP_Post $post ) {
1069 if ( self::is_base_templates_screen() ) {
1070 if ( $this->is_template_supports_export( $post->ID ) ) {
1071 $template_labels = $this->get_template_labels_by_type( self::get_template_type( $post->ID ) );
1072 $export_label = esc_html__( 'Export Template', 'elementor' );
1073
1074 if ( $template_labels['singular'] ) {
1075 /* translators: %s: Template label (singular). */
1076 $export_label = sprintf( esc_html__( 'Export %s', 'elementor' ), $template_labels['singular'] );
1077 }
1078
1079 $actions['export-template'] = sprintf( '<a href="%1$s">%2$s</a>', $this->get_export_link( $post->ID ), $export_label );
1080 }
1081 }
1082
1083 return $actions;
1084 }
1085
1086 /**
1087 * Admin import template form.
1088 *
1089 * The import form displayed in "My Library" screen in WordPress dashboard.
1090 *
1091 * The form allows the user to import template in json/zip format to the site.
1092 *
1093 * Fired by `admin_footer` action.
1094 *
1095 * @since 1.0.0
1096 * @access public
1097 */
1098 public function admin_import_template_form() {
1099 if ( ! self::is_base_templates_screen() || ! User::is_current_user_can_upload_json() ) {
1100 return;
1101 }
1102
1103 /** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
1104 $ajax = Plugin::$instance->common->get_component( 'ajax' );
1105 $template_labels = $this->get_current_template_labels();
1106 $import_label = esc_html__( 'Import Templates', 'elementor' );
1107 $description = 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' );
1108
1109 if ( $template_labels['plural'] ) {
1110 /* translators: %s: Template label (plural). */
1111 $import_label = sprintf( esc_html__( 'Import %s', 'elementor' ), $template_labels['plural'] );
1112 }
1113
1114 if ( $template_labels['singular'] && $template_labels['plural'] ) {
1115 $description = sprintf(
1116 /* translators: 1: Template label (singular). 2: Template label (plural). */
1117 esc_html__( 'Choose an Elementor %1$s JSON file or a .zip archive of Elementor %2$s, and add them to the list of %2$s available in your library.', 'elementor' ),
1118 $template_labels['singular'],
1119 $template_labels['plural']
1120 );
1121 }
1122 ?>
1123 <div id="elementor-hidden-area">
1124 <a id="elementor-import-template-trigger" class="page-title-action button button-secondary"><?php echo esc_html( $import_label ); ?></a>
1125 <div id="elementor-import-template-area">
1126 <div id="elementor-import-template-title"><?php echo esc_html( $description ); ?></div>
1127 <form id="elementor-import-template-form" method="post" action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" enctype="multipart/form-data">
1128 <input type="hidden" name="action" value="elementor_library_direct_actions">
1129 <input type="hidden" name="library_action" value="direct_import_template">
1130 <input type="hidden" name="_nonce" value="<?php Utils::print_unescaped_internal_string( $ajax->create_nonce() ); ?>">
1131 <fieldset id="elementor-import-template-form-inputs">
1132 <input type="file" name="file" accept=".json,application/json,.zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" required>
1133 <input id="e-import-template-action" type="submit" class="button" value="<?php echo esc_attr__( 'Import Now', 'elementor' ); ?>">
1134 </fieldset>
1135 </form>
1136 </div>
1137 </div>
1138 <?php
1139 }
1140
1141 /**
1142 * Block template frontend
1143 *
1144 * Don't display the single view of the template library post type in the
1145 * frontend, for users that don't have the proper permissions.
1146 *
1147 * Fired by `template_redirect` action.
1148 *
1149 * @since 1.0.0
1150 * @access public
1151 */
1152 public function block_template_frontend() {
1153 if ( is_singular( self::CPT ) && ! current_user_can( Editor::EDITING_CAPABILITY ) ) {
1154 wp_safe_redirect( site_url(), 301 );
1155 die;
1156 }
1157 }
1158
1159 public function redirect_categories_page_to_saved_templates_page() {
1160 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1161 $taxonomy = sanitize_key( wp_unslash( $_GET['taxonomy'] ?? '' ) );
1162 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1163 $post_type = sanitize_key( wp_unslash( $_GET['post_type'] ?? '' ) );
1164 $is_categories_page = 'edit-tags.php' === $GLOBALS['pagenow']
1165 && self::TAXONOMY_CATEGORY_SLUG === $taxonomy
1166 && self::CPT === $post_type;
1167
1168 if ( $is_categories_page ) {
1169 wp_safe_redirect( admin_url( 'edit.php?post_type=' . self::CPT . '&tabs_group=library' ) );
1170 die;
1171 }
1172 }
1173
1174 /**
1175 * Is template library supports export.
1176 *
1177 * Whether the template library supports export.
1178 *
1179 * Template saved by the user locally on his site, support export by default
1180 * but this can be changed using a filter.
1181 *
1182 * @since 1.0.0
1183 * @access public
1184 *
1185 * @param int $template_id The template ID.
1186 *
1187 * @return bool Whether the template library supports export.
1188 */
1189 public function is_template_supports_export( $template_id ) {
1190 $export_support = true;
1191
1192 /**
1193 * Is template library supports export.
1194 *
1195 * Filters whether the template library supports export.
1196 *
1197 * @since 1.0.0
1198 *
1199 * @param bool $export_support Whether the template library supports export.
1200 * Default is true.
1201 * @param int $template_id Post ID.
1202 */
1203 $export_support = apply_filters( 'elementor/template_library/is_template_supports_export', $export_support, $template_id );
1204
1205 return $export_support;
1206 }
1207
1208 /**
1209 * Remove Elementor post state.
1210 *
1211 * Remove the 'elementor' post state from the display states of the post.
1212 *
1213 * Used to remove the 'elementor' post state from the template library items.
1214 *
1215 * Fired by `display_post_states` filter.
1216 *
1217 * @since 1.8.0
1218 * @access public
1219 *
1220 * @param array $post_states An array of post display states.
1221 * @param \WP_Post $post The current post object.
1222 *
1223 * @return array Updated array of post display states.
1224 */
1225 public function remove_elementor_post_state_from_library( $post_states, $post ) {
1226 if ( self::CPT === $post->post_type && isset( $post_states['elementor'] ) ) {
1227 unset( $post_states['elementor'] );
1228 }
1229 return $post_states;
1230 }
1231
1232 /**
1233 * Get template export link.
1234 *
1235 * Retrieve the link used to export a single template based on the template
1236 * ID.
1237 *
1238 * @since 2.0.0
1239 * @access private
1240 *
1241 * @param int $template_id The template ID.
1242 *
1243 * @return string Template export URL.
1244 */
1245 private function get_export_link( $template_id ) {
1246 // TODO: BC since 2.3.0 - Use `$ajax->create_nonce()`
1247 /** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
1248 // $ajax = Plugin::$instance->common->get_component( 'ajax' );
1249
1250 return add_query_arg(
1251 [
1252 'action' => 'elementor_library_direct_actions',
1253 'library_action' => 'export_template',
1254 'source' => $this->get_id(),
1255 '_nonce' => wp_create_nonce( 'elementor_ajax' ),
1256 'template_id' => $template_id,
1257 ],
1258 admin_url( 'admin-ajax.php' )
1259 );
1260 }
1261
1262 /**
1263 * On template save.
1264 *
1265 * Run this method when template is being saved.
1266 *
1267 * Fired by `save_post` action.
1268 *
1269 * @since 1.0.1
1270 * @access public
1271 *
1272 * @param int $post_id Post ID.
1273 * @param \WP_Post $post The current post object.
1274 */
1275 public function on_save_post( $post_id, \WP_Post $post ) {
1276 if ( self::CPT !== $post->post_type ) {
1277 return;
1278 }
1279
1280 if ( self::get_template_type( $post_id ) ) { // It's already with a type
1281 return;
1282 }
1283
1284 // Don't save type on import, the importer will do it.
1285 if ( did_action( 'import_start' ) ) {
1286 return;
1287 }
1288
1289 $this->save_item_type( $post_id, 'page' );
1290 }
1291
1292 /**
1293 * Save item type.
1294 *
1295 * When saving/updating templates, this method is used to update the post
1296 * meta data and the taxonomy.
1297 *
1298 * @since 1.0.1
1299 * @access private
1300 *
1301 * @param int $post_id Post ID.
1302 * @param string $type Item type.
1303 */
1304 private function save_item_type( $post_id, $type ) {
1305 update_post_meta( $post_id, Document::TYPE_META_KEY, $type );
1306
1307 wp_set_object_terms( $post_id, $type, self::TAXONOMY_TYPE_SLUG );
1308 }
1309
1310 /**
1311 * Bulk export action.
1312 *
1313 * Adds an 'Export' action to the Bulk Actions drop-down in the template
1314 * library.
1315 *
1316 * Fired by `bulk_actions-edit-elementor_library` filter.
1317 *
1318 * @since 1.6.0
1319 * @access public
1320 *
1321 * @param array $actions An array of the available bulk actions.
1322 *
1323 * @return array An array of the available bulk actions.
1324 */
1325 public function admin_add_bulk_export_action( $actions ) {
1326 $actions[ self::BULK_EXPORT_ACTION ] = esc_html__( 'Export', 'elementor' );
1327
1328 return $actions;
1329 }
1330
1331 /**
1332 * Add bulk export action.
1333 *
1334 * Handles the template library bulk export action.
1335 *
1336 * Fired by `handle_bulk_actions-edit-elementor_library` filter.
1337 *
1338 * @since 1.6.0
1339 * @access public
1340 *
1341 * @param string $redirect_to The redirect URL.
1342 * @param string $action The action being taken.
1343 * @param array $post_ids The items to take the action on.
1344 */
1345 public function admin_export_multiple_templates( $redirect_to, $action, $post_ids ) {
1346 if ( self::BULK_EXPORT_ACTION === $action ) {
1347 $result = $this->export_multiple_templates( $post_ids );
1348
1349 // If you reach this line, the export failed
1350 // PHPCS - Not user input.
1351 wp_die( $result->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1352 }
1353 }
1354
1355 /**
1356 * Print admin tabs.
1357 *
1358 * Used to output the template library tabs with their labels.
1359 *
1360 * Fired by `views_edit-elementor_library` filter.
1361 *
1362 * @since 2.0.0
1363 * @access public
1364 *
1365 * @param array $views An array of available list table views.
1366 *
1367 * @return array An updated array of available list table views.
1368 */
1369 public function admin_print_tabs( $views ) {
1370 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1371 $current_type = Utils::get_super_global_value( $_REQUEST, self::TAXONOMY_TYPE_SLUG ) ?? '';
1372 $active_class = $current_type ? '' : ' nav-tab-active';
1373 $current_tabs_group = $this->get_current_tab_group();
1374
1375 $url_args = [
1376 'post_type' => self::CPT,
1377 'tabs_group' => $current_tabs_group,
1378 ];
1379
1380 $baseurl = add_query_arg( $url_args, admin_url( 'edit.php' ) );
1381
1382 $filter = [
1383 'admin_tab_group' => $current_tabs_group,
1384 ];
1385 $operator = 'and';
1386
1387 if ( empty( $current_tabs_group ) ) {
1388 // Don't include 'not-supported' or other templates that don't set their `admin_tab_group`.
1389 $operator = 'NOT';
1390 }
1391
1392 $doc_types = Plugin::$instance->documents->get_document_types( $filter, $operator );
1393
1394 if ( 1 >= count( $doc_types ) ) {
1395 return $views;
1396 }
1397
1398 ?>
1399 <div id="elementor-template-library-tabs-wrapper" class="nav-tab-wrapper">
1400 <a class="nav-tab<?php echo esc_attr( $active_class ); ?>" href="<?php echo esc_url( $baseurl ); ?>">
1401 <?php
1402 $all_title = $this->get_library_title();
1403 if ( ! $all_title ) {
1404 $all_title = esc_html__( 'All', 'elementor' );
1405 }
1406 Utils::print_unescaped_internal_string( $all_title ); ?>
1407 </a>
1408 <?php
1409 foreach ( $doc_types as $type => $class_name ) :
1410 $active_class = '';
1411
1412 if ( $current_type === $type ) {
1413 $active_class = ' nav-tab-active';
1414 }
1415
1416 $type_url = esc_url( add_query_arg( self::TAXONOMY_TYPE_SLUG, $type, $baseurl ) );
1417 $type_label = $this->get_template_label_by_type( $type );
1418 Utils::print_unescaped_internal_string( "<a class='nav-tab{$active_class}' href='{$type_url}'>{$type_label}</a>" );
1419 endforeach;
1420 ?>
1421 </div>
1422 <?php
1423 return $views;
1424 }
1425
1426 /**
1427 * Maybe render blank state.
1428 *
1429 * When the template library has no saved templates, display a blank admin page offering
1430 * to create the very first template.
1431 *
1432 * Fired by `manage_posts_extra_tablenav` action.
1433 *
1434 * @since 2.0.0
1435 * @access public
1436 *
1437 * @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
1438 * @param array $args
1439 */
1440 public function maybe_render_blank_state( $which, array $args = [] ) {
1441 global $post_type;
1442
1443 $args = wp_parse_args( $args, [
1444 'cpt' => self::CPT,
1445 'post_type' => get_query_var( 'elementor_library_type' ),
1446 ] );
1447
1448 if ( $args['cpt'] !== $post_type || 'bottom' !== $which ) {
1449 return;
1450 }
1451
1452 global $wp_list_table;
1453
1454 $total_items = $wp_list_table->get_pagination_arg( 'total_items' );
1455
1456 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1457 if ( ! empty( $total_items ) || ! empty( $_REQUEST['s'] ) ) {
1458 return;
1459 }
1460
1461 $current_type = $args['post_type'];
1462
1463 $document_types = Plugin::instance()->documents->get_document_types();
1464
1465 if ( empty( $document_types[ $current_type ] ) ) {
1466 return;
1467 }
1468
1469 // TODO: Better way to exclude widget type.
1470 if ( 'widget' === $current_type ) {
1471 return;
1472 }
1473
1474 // TODO: This code maybe unreachable see if above `if ( empty( $document_types[ $current_type ] ) )`.
1475 if ( empty( $current_type ) ) {
1476 $counts = (array) wp_count_posts( self::CPT );
1477 unset( $counts['auto-draft'] );
1478 $count = array_sum( $counts );
1479
1480 if ( 0 < $count ) {
1481 return;
1482 }
1483
1484 $current_type = 'template';
1485
1486 $args['additional_inline_style'] = '#elementor-template-library-tabs-wrapper {display: none;}';
1487 }
1488
1489 $this->render_blank_state( $current_type, $args );
1490 }
1491
1492 private function render_blank_state( $current_type, array $args = [] ) {
1493 $current_type_label = $this->get_template_label_by_type( $current_type );
1494 $type_labels = $this->get_template_labels_by_type( $current_type );
1495 $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' );
1496
1497 if ( $type_labels['plural'] ) {
1498 $description = sprintf(
1499 /* translators: %s: Template label (plural). */
1500 esc_html__( 'Add %s and reuse them across your website. Easily export and import them to any other project, for an optimized workflow.', 'elementor' ),
1501 $type_labels['plural']
1502 );
1503 }
1504 $inline_style = '#posts-filter .wp-list-table, #posts-filter .tablenav.top, .tablenav.bottom .actions, .wrap .subsubsub { display:none;}';
1505
1506 $args = wp_parse_args( $args, [
1507 'additional_inline_style' => '',
1508 'href' => '',
1509 'description' => $description,
1510 ] );
1511 $inline_style .= $args['additional_inline_style'];
1512 ?>
1513 <style type="text/css"><?php Utils::print_unescaped_internal_string( $inline_style ); ?></style>
1514 <div class="elementor-template_library-blank_state">
1515 <?php $this->print_blank_state_template( $current_type_label, $args['href'], $args['description'] ); ?>
1516 </div>
1517 <?php
1518 }
1519
1520 /**
1521 * Print Blank State Template
1522 *
1523 * When the an entity (CPT, Taxonomy...etc) has no saved items, print a blank admin page offering
1524 * to create the very first item.
1525 *
1526 * This method is public because it needs to be accessed from outside the Source_Local
1527 *
1528 * @since 3.1.0
1529 * @access public
1530 *
1531 * @param string $current_type_label The Entity title.
1532 * @param string $href The URL for the 'Add New' button.
1533 * @param string $description The sub title describing the Entity (Post Type, Taxonomy, etc.).
1534 */
1535 public function print_blank_state_template( $current_type_label, $href, $description ) {
1536 ?>
1537 <div class="elementor-blank_state">
1538 <i class="eicon-folder"></i>
1539 <h3>
1540 <?php
1541 /* translators: %s: Template type label. */
1542 printf( esc_html__( 'Create Your First %s', 'elementor' ), esc_html( $current_type_label ) );
1543 ?>
1544 </h3>
1545 <p><?php echo wp_kses_post( $description ); ?></p>
1546 <a id="elementor-template-library-add-new" class="elementor-button e-primary" href="<?php echo esc_url( $href ); ?>">
1547 <?php
1548 /* translators: %s: Template type label. */
1549 printf( esc_html__( 'Add New %s', 'elementor' ), esc_html( $current_type_label ) );
1550 ?>
1551 </a>
1552 </div>
1553 <?php
1554 }
1555
1556 /**
1557 * Add filter by category.
1558 *
1559 * In the templates library, add a filter by Elementor library category.
1560 *
1561 * @access public
1562 *
1563 * @param string $post_type The post type slug.
1564 */
1565 public function add_filter_by_category( $post_type ) {
1566 if ( self::CPT !== $post_type ) {
1567 return;
1568 }
1569
1570 $all_items = get_taxonomy( self::TAXONOMY_CATEGORY_SLUG )->labels->all_items;
1571 $dropdown_options = [
1572 'show_option_all' => $all_items,
1573 'show_option_none' => $all_items,
1574 'hide_empty' => 0,
1575 'hierarchical' => 1,
1576 'show_count' => 0,
1577 'orderby' => 'name',
1578 'value_field' => 'slug',
1579 'taxonomy' => self::TAXONOMY_CATEGORY_SLUG,
1580 'name' => self::TAXONOMY_CATEGORY_SLUG,
1581 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1582 'selected' => Utils::get_super_global_value( $_GET, self::TAXONOMY_CATEGORY_SLUG ) ?? '',
1583 ];
1584
1585 printf(
1586 '<label class="screen-reader-text" for="%1$s">%2$s</label>',
1587 esc_attr( self::TAXONOMY_CATEGORY_SLUG ),
1588 esc_html_x( 'Filter by category', 'Template Library', 'elementor' )
1589 );
1590 wp_dropdown_categories( $dropdown_options );
1591 }
1592
1593 /**
1594 * Import single template.
1595 *
1596 * Import template from a file to the database.
1597 *
1598 * @since 1.6.0
1599 * @access private
1600 *
1601 * @param string $file_path File name.
1602 *
1603 * @return \WP_Error|int|array Local template array, or template ID, or
1604 * `WP_Error`.
1605 */
1606 private function import_single_template( $file_path ) {
1607 $data = $this->prepare_import_template_data( $file_path );
1608
1609 if ( is_wp_error( $data ) ) {
1610 return $data;
1611 }
1612
1613 if ( empty( $data ) ) {
1614 return new \WP_Error( 'file_error', 'Invalid File' );
1615 }
1616
1617 $template_id = $this->save_item( [
1618 'content' => $data['content'],
1619 'title' => $data['title'],
1620 'type' => $data['type'],
1621 'page_settings' => $data['page_settings'],
1622 ] );
1623
1624 if ( is_wp_error( $template_id ) ) {
1625 return $template_id;
1626 }
1627
1628 return $this->get_item( $template_id );
1629 }
1630
1631 /**
1632 * Prepare template to export.
1633 *
1634 * Retrieve the relevant template data and return them as an array.
1635 *
1636 * @since 1.6.0
1637 * @access private
1638 *
1639 * @param int $template_id The template ID.
1640 *
1641 * @return \WP_Error|array Exported template data.
1642 */
1643 private function prepare_template_export( $template_id ) {
1644 $document = Plugin::$instance->documents->get( $template_id );
1645
1646 $template_data = $document->get_export_data();
1647
1648 if ( empty( $template_data['content'] ) ) {
1649 return new \WP_Error( 'empty_template', 'The template is empty' );
1650 }
1651
1652 $content = apply_filters(
1653 'elementor/template_library/sources/local/export/elements',
1654 $template_data['content']
1655 );
1656
1657 $export_data = [
1658 'content' => $content,
1659 'page_settings' => $template_data['settings'],
1660 'version' => DB::DB_VERSION,
1661 'title' => $document->get_main_post()->post_title,
1662 'type' => self::get_template_type( $template_id ),
1663 ];
1664
1665 return [
1666 'name' => 'elementor-' . $template_id . '-' . gmdate( 'Y-m-d' ) . '.json',
1667 'content' => wp_json_encode( $export_data ),
1668 ];
1669 }
1670
1671 /**
1672 * Get template label by type.
1673 *
1674 * Retrieve the template label for any given template type.
1675 *
1676 * @since 2.0.0
1677 * @access private
1678 *
1679 * @param string $template_type Template type.
1680 *
1681 * @return string Template label.
1682 */
1683 private function get_template_label_by_type( $template_type ) {
1684 $document_types = Plugin::instance()->documents->get_document_types();
1685
1686 if ( isset( $document_types[ $template_type ] ) ) {
1687 $template_label = call_user_func( [ $document_types[ $template_type ], 'get_title' ] );
1688 } else {
1689 $template_label = ucwords( str_replace( [ '_', '-' ], ' ', $template_type ) );
1690 }
1691
1692 /**
1693 * Template label by template type.
1694 *
1695 * Filters the template label by template type in the template library .
1696 *
1697 * @since 2.0.0
1698 *
1699 * @param string $template_label Template label.
1700 * @param string $template_type Template type.
1701 */
1702 $template_label = apply_filters( 'elementor/template-library/get_template_label_by_type', $template_label, $template_type );
1703
1704 return $template_label;
1705 }
1706
1707 private function get_template_labels_by_type( $template_type ) {
1708 $labels = [
1709 'singular' => '',
1710 'plural' => '',
1711 ];
1712
1713 if ( ! $template_type ) {
1714 return $labels;
1715 }
1716
1717 $document_types = Plugin::instance()->documents->get_document_types();
1718
1719 if ( isset( $document_types[ $template_type ] ) ) {
1720 $doc_type = $document_types[ $template_type ];
1721 $labels['singular'] = call_user_func( [ $doc_type, 'get_title' ] );
1722 $labels['plural'] = call_user_func( [ $doc_type, 'get_plural_title' ] );
1723 } else {
1724 $labels['singular'] = $this->get_template_label_by_type( $template_type );
1725 }
1726
1727 if ( ! $labels['plural'] ) {
1728 $labels['plural'] = $labels['singular'];
1729 }
1730
1731 return $labels;
1732 }
1733
1734 private function get_current_template_labels() {
1735 $labels = [
1736 'singular' => '',
1737 'plural' => '',
1738 ];
1739
1740 $template_type = Utils::get_super_global_value( $_GET, self::TAXONOMY_TYPE_SLUG );
1741
1742 if ( $template_type ) {
1743 return $this->get_template_labels_by_type( $template_type );
1744 }
1745
1746 $current_tabs_group = $this->get_current_tab_group();
1747
1748 if ( $current_tabs_group ) {
1749 $doc_types = Plugin::$instance->documents->get_document_types( [
1750 'admin_tab_group' => $current_tabs_group,
1751 ], 'and' );
1752
1753 if ( 1 === count( $doc_types ) ) {
1754 $doc_type = reset( $doc_types );
1755 $labels['singular'] = call_user_func( [ $doc_type, 'get_title' ] );
1756 $labels['plural'] = call_user_func( [ $doc_type, 'get_plural_title' ] );
1757 }
1758 }
1759
1760 if ( ! $labels['plural'] ) {
1761 $labels['plural'] = $labels['singular'];
1762 }
1763
1764 return $labels;
1765 }
1766
1767 /**
1768 * Filter template types in admin query.
1769 *
1770 * Update the template types in the main admin query.
1771 *
1772 * Fired by `parse_query` action.
1773 *
1774 * @since 2.4.0
1775 * @access public
1776 *
1777 * @param \WP_Query $query The `WP_Query` instance.
1778 */
1779 public function admin_query_filter_types( \WP_Query $query ) {
1780 if ( ! $this->is_current_screen() || ! empty( $query->query_vars['meta_key'] ) ) {
1781 return;
1782 }
1783
1784 $current_tabs_group = $this->get_current_tab_group();
1785
1786 if ( isset( $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] ) && '-1' === $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] ) {
1787 unset( $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] );
1788 }
1789
1790 if ( empty( $current_tabs_group ) ) {
1791 return;
1792 }
1793
1794 $doc_types = Plugin::$instance->documents->get_document_types( [
1795 'admin_tab_group' => $current_tabs_group,
1796 ] );
1797
1798 $query->query_vars['meta_key'] = Document::TYPE_META_KEY;
1799 $query->query_vars['meta_value'] = array_keys( $doc_types );
1800 }
1801
1802 /**
1803 * Add template library actions.
1804 *
1805 * Register filters and actions for the template library.
1806 *
1807 * @since 2.0.0
1808 * @access private
1809 */
1810 private function add_actions() {
1811 if ( is_admin() ) {
1812 add_action( 'elementor/admin/menu/register', function ( Admin_Menu_Manager $admin_menu ) {
1813 $this->register_admin_menu( $admin_menu );
1814 }, static::ADMIN_MENU_PRIORITY );
1815
1816 add_action( 'admin_init', [ $this, 'redirect_categories_page_to_saved_templates_page' ] );
1817
1818 add_action( 'elementor/editor-one/menu/register', function ( Menu_Data_Provider $menu_data_provider ) {
1819 $this->register_editor_one_menu( $menu_data_provider );
1820 } );
1821
1822 add_action( 'elementor/editor-one/menu/excluded_level4_slugs', function ( array $excluded_slugs ): array {
1823 $excluded_slugs[] = 'edit.php?post_type=elementor_library#add_new';
1824 $excluded_slugs[] = 'edit-tags.php?taxonomy=elementor_library_category&amp;post_type=elementor_library';
1825 return $excluded_slugs;
1826 } );
1827
1828 add_filter( 'elementor/editor-one/menu/elementor_post_types', function ( array $elementor_post_types ): array {
1829 $elementor_post_types[ self::CPT ] = [];
1830
1831 return $elementor_post_types;
1832 } );
1833
1834 add_filter( 'elementor/editor-one/admin-edit-post-types', function ( array $post_types ): array {
1835 $post_types[] = self::CPT;
1836
1837 return $post_types;
1838 } );
1839
1840 add_action( 'elementor/admin/menu/register', function ( Admin_Menu_Manager $admin_menu ) {
1841 $this->admin_menu_reorder( $admin_menu );
1842 }, 800 );
1843
1844 add_action( 'elementor/admin/menu/after_register', function () {
1845 $this->admin_menu_set_current();
1846 } );
1847
1848 add_filter( 'admin_title', [ $this, 'admin_title' ], 10, 2 );
1849 add_action( 'all_admin_notices', [ $this, 'replace_admin_heading' ] );
1850 add_filter( 'post_row_actions', [ $this, 'post_row_actions' ], 10, 2 );
1851 add_action( 'admin_footer', [ $this, 'admin_import_template_form' ] );
1852 add_action( 'save_post', [ $this, 'on_save_post' ], 10, 2 );
1853 add_filter( 'display_post_states', [ $this, 'remove_elementor_post_state_from_library' ], 11, 2 );
1854
1855 add_action( 'parse_query', [ $this, 'admin_query_filter_types' ] );
1856
1857 // Template filter by category.
1858 add_action( 'restrict_manage_posts', [ $this, 'add_filter_by_category' ] );
1859
1860 // Template type column.
1861 add_action( 'manage_' . self::CPT . '_posts_columns', [ $this, 'admin_columns_headers' ] );
1862 add_action( 'manage_' . self::CPT . '_posts_custom_column', [ $this, 'admin_columns_content' ], 10, 2 );
1863
1864 // Template library bulk actions.
1865 add_filter( 'bulk_actions-edit-elementor_library', [ $this, 'admin_add_bulk_export_action' ] );
1866 add_filter( 'handle_bulk_actions-edit-elementor_library', [ $this, 'admin_export_multiple_templates' ], 10, 3 );
1867
1868 // Print template library tabs.
1869 add_filter( 'views_edit-' . self::CPT, [ $this, 'admin_print_tabs' ] );
1870
1871 // Show blank state.
1872 add_action( 'manage_posts_extra_tablenav', [ $this, 'maybe_render_blank_state' ] );
1873 }
1874
1875 add_action( 'elementor/document/after_save', [ $this, 'on_template_update' ], 10, 2 );
1876
1877 add_action( 'template_redirect', [ $this, 'block_template_frontend' ] );
1878
1879 // Remove elementor library templates from WP Sitemap
1880 add_filter(
1881 'wp_sitemaps_post_types',
1882 function( $post_types ) {
1883 return $this->remove_elementor_cpt_from_sitemap( $post_types );
1884 }
1885 );
1886 }
1887
1888 public function on_template_update( \Elementor\Core\Base\Document $document, array $data ) {
1889 if ( ! empty( $data['post_title'] ) ) {
1890 wp_update_post( [
1891 'ID' => $document->get_main_id(),
1892 'post_title' => $data['post_title'],
1893 ] );
1894 }
1895 }
1896
1897 /**
1898 * @since 2.0.6
1899 * @access public
1900 */
1901 public function admin_columns_content( $column_name, $post_id ) {
1902 if ( 'elementor_library_type' === $column_name ) {
1903 /** @var Document $document */
1904 $document = Plugin::$instance->documents->get( $post_id );
1905
1906 if ( $document && $document instanceof Library_Document ) {
1907 $document->print_admin_column_type();
1908 }
1909 }
1910 }
1911
1912 /**
1913 * @since 2.0.6
1914 * @access public
1915 */
1916 public function admin_columns_headers( $posts_columns ) {
1917 // Replace original column that bind to the taxonomy - with another column.
1918 unset( $posts_columns['taxonomy-elementor_library_type'] );
1919
1920 $offset = 2;
1921
1922 $posts_columns = array_slice( $posts_columns, 0, $offset, true ) + [
1923 'elementor_library_type' => esc_html__( 'Type', 'elementor' ),
1924 ] + array_slice( $posts_columns, $offset, null, true );
1925
1926 return $posts_columns;
1927 }
1928
1929 public function get_current_tab_group() {
1930 $current_tabs_group = Utils::get_super_global_value( $_GET, 'tabs_group' ) ?? '';
1931 $type_slug = Utils::get_super_global_value( $_GET, self::TAXONOMY_TYPE_SLUG );
1932
1933 if ( $type_slug ) {
1934 $doc_type = Plugin::$instance->documents->get_document_type( $type_slug, '' );
1935 if ( $doc_type ) {
1936 $current_tabs_group = $doc_type::get_property( 'admin_tab_group' );
1937 }
1938 }
1939 return $current_tabs_group;
1940 }
1941
1942 private function get_library_title() {
1943 $title = '';
1944
1945 if ( $this->is_current_screen() ) {
1946 $current_tab_group = $this->get_current_tab_group();
1947
1948 if ( $current_tab_group ) {
1949 $titles = [
1950 'library' => esc_html__( 'Saved Templates', 'elementor' ),
1951 'theme' => esc_html__( 'Theme Builder', 'elementor' ),
1952 'popup' => esc_html__( 'Popups', 'elementor' ),
1953 ];
1954
1955 if ( ! empty( $titles[ $current_tab_group ] ) ) {
1956 $title = $titles[ $current_tab_group ];
1957 }
1958 }
1959 }
1960
1961 return $title;
1962 }
1963
1964 private function is_current_screen() {
1965 global $pagenow, $typenow;
1966
1967 return 'edit.php' === $pagenow && self::CPT === $typenow;
1968 }
1969
1970 /**
1971 * @param array $post_types
1972 *
1973 * @return array
1974 */
1975 private function remove_elementor_cpt_from_sitemap( array $post_types ) {
1976 unset( $post_types[ self::CPT ] );
1977
1978 return $post_types;
1979 }
1980
1981 private function avoid_rest_access_for_non_admins(): void {
1982 add_filter( 'rest_pre_dispatch', function ( $value, \WP_REST_Server $server, \WP_REST_Request $request ) {
1983 if ( strpos( $request->get_route(), self::CPT ) !== false ) {
1984 if ( ! current_user_can( 'manage_options' ) ) {
1985 return new \WP_Error( 'rest_forbidden', esc_html__( 'Sorry, you are not allowed to do that.', 'elementor' ), [ 'status' => rest_authorization_required_code() ] );
1986 }
1987 }
1988
1989 return $value;
1990 }, 10, 3 );
1991 }
1992
1993 public function save_bulk_items( array $args = [] ) {
1994 $items = [];
1995
1996 foreach ( $args as $item ) {
1997 $items[] = $this->save_item( [
1998 'content' => $item['content'],
1999 'title' => $item['title'],
2000 'type' => $item['type'],
2001 'page_settings' => $item['page_settings'],
2002 ] );
2003 }
2004
2005 return $items;
2006 }
2007
2008 /**
2009 * Template library local source constructor.
2010 *
2011 * Initializing the template library local source base by registering custom
2012 * template data and running custom actions.
2013 *
2014 * @since 1.0.0
2015 * @access public
2016 */
2017 public function __construct() {
2018 parent::__construct();
2019
2020 $this->add_actions();
2021 }
2022
2023 public function format_args_for_bulk_action( $args ) {
2024 $bulk_args = [];
2025
2026 foreach ( $args['from_template_id'] as $from_template_id ) {
2027 if ( ! $this->is_allowed_to_read_template( [
2028 'template_id' => $from_template_id,
2029 ] ) ) {
2030 continue;
2031 }
2032
2033 $document = Plugin::$instance->documents->get( $from_template_id );
2034
2035 if ( ! $document ) {
2036 continue;
2037 }
2038
2039 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $from_template_id );
2040
2041 $bulk_args[] = array_merge(
2042 $args,
2043 [
2044 'title' => $document->get_post()->post_title,
2045 'type' => $document::get_type(),
2046 'content' => $document->get_elements_data(),
2047 'page_settings' => $page->get_data( 'settings' ),
2048 ]
2049 );
2050 }
2051
2052 return $bulk_args;
2053 }
2054
2055 public function format_args_for_single_action( $args ) {
2056 if ( ! $this->is_allowed_to_read_template( [
2057 'template_id' => $args['from_template_id'],
2058 ] ) ) {
2059 return new \WP_Error(
2060 'template_error',
2061 esc_html__( 'You do not have permission to access this template.', 'elementor' )
2062 );
2063 }
2064
2065 $document = Plugin::$instance->documents->get( $args['from_template_id'] );
2066
2067 if ( ! $document ) {
2068 return new \WP_Error( 'template_error', 'Document not found.' );
2069 }
2070
2071 $args['content'] = $document->get_elements_data();
2072
2073 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $args['from_template_id'] );
2074 $args['page_settings'] = $page->get_data( 'settings' );
2075
2076 return $args;
2077 }
2078
2079 public function is_allowed_to_read_template( array $args ): bool {
2080 if ( null === $this->wordpress_adapter ) {
2081 $this->set_wordpress_adapter( new WordPress_Adapter() );
2082 }
2083
2084 if ( ! $this->should_check_permissions( $args ) ) {
2085 return true;
2086 }
2087
2088 $post_id = intval( $args['template_id'] );
2089 $post_status = $this->wordpress_adapter->get_post_status( $post_id );
2090 $is_private_or_non_published = ( 'private' === $post_status && ! $this->wordpress_adapter->current_user_can( 'read_private_posts', $post_id ) ) || ( 'publish' !== $post_status );
2091
2092 $can_read_template = ! $is_private_or_non_published || $this->wordpress_adapter->current_user_can( 'edit_post', $post_id );
2093
2094 return apply_filters( 'elementor/template-library/is_allowed_to_read_template', $can_read_template, $args );
2095 }
2096
2097 private function should_check_permissions( array $args ): bool {
2098 if ( null === $this->elementor_adapter ) {
2099 $this->set_elementor_adapter( new Elementor_Adapter() );
2100 }
2101
2102 $check_permissions = isset( $args['check_permissions'] ) && false === $args['check_permissions'];
2103
2104 if ( $check_permissions ) {
2105 return false;
2106 }
2107
2108 return true;
2109 }
2110
2111 public function set_wordpress_adapter( Wordpress_Adapter_Interface $wordpress_adapter ) {
2112 $this->wordpress_adapter = $wordpress_adapter;
2113 }
2114
2115 public function set_elementor_adapter( Elementor_Adapter_Interface $elementor_adapter ): void {
2116 $this->elementor_adapter = $elementor_adapter;
2117 }
2118 }
2119