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

2,102 lines 59.8 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 /**
1160 * Is template library supports export.
1161 *
1162 * Whether the template library supports export.
1163 *
1164 * Template saved by the user locally on his site, support export by default
1165 * but this can be changed using a filter.
1166 *
1167 * @since 1.0.0
1168 * @access public
1169 *
1170 * @param int $template_id The template ID.
1171 *
1172 * @return bool Whether the template library supports export.
1173 */
1174 public function is_template_supports_export( $template_id ) {
1175 $export_support = true;
1176
1177 /**
1178 * Is template library supports export.
1179 *
1180 * Filters whether the template library supports export.
1181 *
1182 * @since 1.0.0
1183 *
1184 * @param bool $export_support Whether the template library supports export.
1185 * Default is true.
1186 * @param int $template_id Post ID.
1187 */
1188 $export_support = apply_filters( 'elementor/template_library/is_template_supports_export', $export_support, $template_id );
1189
1190 return $export_support;
1191 }
1192
1193 /**
1194 * Remove Elementor post state.
1195 *
1196 * Remove the 'elementor' post state from the display states of the post.
1197 *
1198 * Used to remove the 'elementor' post state from the template library items.
1199 *
1200 * Fired by `display_post_states` filter.
1201 *
1202 * @since 1.8.0
1203 * @access public
1204 *
1205 * @param array $post_states An array of post display states.
1206 * @param \WP_Post $post The current post object.
1207 *
1208 * @return array Updated array of post display states.
1209 */
1210 public function remove_elementor_post_state_from_library( $post_states, $post ) {
1211 if ( self::CPT === $post->post_type && isset( $post_states['elementor'] ) ) {
1212 unset( $post_states['elementor'] );
1213 }
1214 return $post_states;
1215 }
1216
1217 /**
1218 * Get template export link.
1219 *
1220 * Retrieve the link used to export a single template based on the template
1221 * ID.
1222 *
1223 * @since 2.0.0
1224 * @access private
1225 *
1226 * @param int $template_id The template ID.
1227 *
1228 * @return string Template export URL.
1229 */
1230 private function get_export_link( $template_id ) {
1231 // TODO: BC since 2.3.0 - Use `$ajax->create_nonce()`
1232 /** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
1233 // $ajax = Plugin::$instance->common->get_component( 'ajax' );
1234
1235 return add_query_arg(
1236 [
1237 'action' => 'elementor_library_direct_actions',
1238 'library_action' => 'export_template',
1239 'source' => $this->get_id(),
1240 '_nonce' => wp_create_nonce( 'elementor_ajax' ),
1241 'template_id' => $template_id,
1242 ],
1243 admin_url( 'admin-ajax.php' )
1244 );
1245 }
1246
1247 /**
1248 * On template save.
1249 *
1250 * Run this method when template is being saved.
1251 *
1252 * Fired by `save_post` action.
1253 *
1254 * @since 1.0.1
1255 * @access public
1256 *
1257 * @param int $post_id Post ID.
1258 * @param \WP_Post $post The current post object.
1259 */
1260 public function on_save_post( $post_id, \WP_Post $post ) {
1261 if ( self::CPT !== $post->post_type ) {
1262 return;
1263 }
1264
1265 if ( self::get_template_type( $post_id ) ) { // It's already with a type
1266 return;
1267 }
1268
1269 // Don't save type on import, the importer will do it.
1270 if ( did_action( 'import_start' ) ) {
1271 return;
1272 }
1273
1274 $this->save_item_type( $post_id, 'page' );
1275 }
1276
1277 /**
1278 * Save item type.
1279 *
1280 * When saving/updating templates, this method is used to update the post
1281 * meta data and the taxonomy.
1282 *
1283 * @since 1.0.1
1284 * @access private
1285 *
1286 * @param int $post_id Post ID.
1287 * @param string $type Item type.
1288 */
1289 private function save_item_type( $post_id, $type ) {
1290 update_post_meta( $post_id, Document::TYPE_META_KEY, $type );
1291
1292 wp_set_object_terms( $post_id, $type, self::TAXONOMY_TYPE_SLUG );
1293 }
1294
1295 /**
1296 * Bulk export action.
1297 *
1298 * Adds an 'Export' action to the Bulk Actions drop-down in the template
1299 * library.
1300 *
1301 * Fired by `bulk_actions-edit-elementor_library` filter.
1302 *
1303 * @since 1.6.0
1304 * @access public
1305 *
1306 * @param array $actions An array of the available bulk actions.
1307 *
1308 * @return array An array of the available bulk actions.
1309 */
1310 public function admin_add_bulk_export_action( $actions ) {
1311 $actions[ self::BULK_EXPORT_ACTION ] = esc_html__( 'Export', 'elementor' );
1312
1313 return $actions;
1314 }
1315
1316 /**
1317 * Add bulk export action.
1318 *
1319 * Handles the template library bulk export action.
1320 *
1321 * Fired by `handle_bulk_actions-edit-elementor_library` filter.
1322 *
1323 * @since 1.6.0
1324 * @access public
1325 *
1326 * @param string $redirect_to The redirect URL.
1327 * @param string $action The action being taken.
1328 * @param array $post_ids The items to take the action on.
1329 */
1330 public function admin_export_multiple_templates( $redirect_to, $action, $post_ids ) {
1331 if ( self::BULK_EXPORT_ACTION === $action ) {
1332 $result = $this->export_multiple_templates( $post_ids );
1333
1334 // If you reach this line, the export failed
1335 // PHPCS - Not user input.
1336 wp_die( $result->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1337 }
1338 }
1339
1340 /**
1341 * Print admin tabs.
1342 *
1343 * Used to output the template library tabs with their labels.
1344 *
1345 * Fired by `views_edit-elementor_library` filter.
1346 *
1347 * @since 2.0.0
1348 * @access public
1349 *
1350 * @param array $views An array of available list table views.
1351 *
1352 * @return array An updated array of available list table views.
1353 */
1354 public function admin_print_tabs( $views ) {
1355 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1356 $current_type = Utils::get_super_global_value( $_REQUEST, self::TAXONOMY_TYPE_SLUG ) ?? '';
1357 $active_class = $current_type ? '' : ' nav-tab-active';
1358 $current_tabs_group = $this->get_current_tab_group();
1359
1360 $url_args = [
1361 'post_type' => self::CPT,
1362 'tabs_group' => $current_tabs_group,
1363 ];
1364
1365 $baseurl = add_query_arg( $url_args, admin_url( 'edit.php' ) );
1366
1367 $filter = [
1368 'admin_tab_group' => $current_tabs_group,
1369 ];
1370 $operator = 'and';
1371
1372 if ( empty( $current_tabs_group ) ) {
1373 // Don't include 'not-supported' or other templates that don't set their `admin_tab_group`.
1374 $operator = 'NOT';
1375 }
1376
1377 $doc_types = Plugin::$instance->documents->get_document_types( $filter, $operator );
1378
1379 if ( 1 >= count( $doc_types ) ) {
1380 return $views;
1381 }
1382
1383 ?>
1384 <div id="elementor-template-library-tabs-wrapper" class="nav-tab-wrapper">
1385 <a class="nav-tab<?php echo esc_attr( $active_class ); ?>" href="<?php echo esc_url( $baseurl ); ?>">
1386 <?php
1387 $all_title = $this->get_library_title();
1388 if ( ! $all_title ) {
1389 $all_title = esc_html__( 'All', 'elementor' );
1390 }
1391 Utils::print_unescaped_internal_string( $all_title ); ?>
1392 </a>
1393 <?php
1394 foreach ( $doc_types as $type => $class_name ) :
1395 $active_class = '';
1396
1397 if ( $current_type === $type ) {
1398 $active_class = ' nav-tab-active';
1399 }
1400
1401 $type_url = esc_url( add_query_arg( self::TAXONOMY_TYPE_SLUG, $type, $baseurl ) );
1402 $type_label = $this->get_template_label_by_type( $type );
1403 Utils::print_unescaped_internal_string( "<a class='nav-tab{$active_class}' href='{$type_url}'>{$type_label}</a>" );
1404 endforeach;
1405 ?>
1406 </div>
1407 <?php
1408 return $views;
1409 }
1410
1411 /**
1412 * Maybe render blank state.
1413 *
1414 * When the template library has no saved templates, display a blank admin page offering
1415 * to create the very first template.
1416 *
1417 * Fired by `manage_posts_extra_tablenav` action.
1418 *
1419 * @since 2.0.0
1420 * @access public
1421 *
1422 * @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
1423 * @param array $args
1424 */
1425 public function maybe_render_blank_state( $which, array $args = [] ) {
1426 global $post_type;
1427
1428 $args = wp_parse_args( $args, [
1429 'cpt' => self::CPT,
1430 'post_type' => get_query_var( 'elementor_library_type' ),
1431 ] );
1432
1433 if ( $args['cpt'] !== $post_type || 'bottom' !== $which ) {
1434 return;
1435 }
1436
1437 global $wp_list_table;
1438
1439 $total_items = $wp_list_table->get_pagination_arg( 'total_items' );
1440
1441 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1442 if ( ! empty( $total_items ) || ! empty( $_REQUEST['s'] ) ) {
1443 return;
1444 }
1445
1446 $current_type = $args['post_type'];
1447
1448 $document_types = Plugin::instance()->documents->get_document_types();
1449
1450 if ( empty( $document_types[ $current_type ] ) ) {
1451 return;
1452 }
1453
1454 // TODO: Better way to exclude widget type.
1455 if ( 'widget' === $current_type ) {
1456 return;
1457 }
1458
1459 // TODO: This code maybe unreachable see if above `if ( empty( $document_types[ $current_type ] ) )`.
1460 if ( empty( $current_type ) ) {
1461 $counts = (array) wp_count_posts( self::CPT );
1462 unset( $counts['auto-draft'] );
1463 $count = array_sum( $counts );
1464
1465 if ( 0 < $count ) {
1466 return;
1467 }
1468
1469 $current_type = 'template';
1470
1471 $args['additional_inline_style'] = '#elementor-template-library-tabs-wrapper {display: none;}';
1472 }
1473
1474 $this->render_blank_state( $current_type, $args );
1475 }
1476
1477 private function render_blank_state( $current_type, array $args = [] ) {
1478 $current_type_label = $this->get_template_label_by_type( $current_type );
1479 $type_labels = $this->get_template_labels_by_type( $current_type );
1480 $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' );
1481
1482 if ( $type_labels['plural'] ) {
1483 $description = sprintf(
1484 /* translators: %s: Template label (plural). */
1485 esc_html__( 'Add %s and reuse them across your website. Easily export and import them to any other project, for an optimized workflow.', 'elementor' ),
1486 $type_labels['plural']
1487 );
1488 }
1489 $inline_style = '#posts-filter .wp-list-table, #posts-filter .tablenav.top, .tablenav.bottom .actions, .wrap .subsubsub { display:none;}';
1490
1491 $args = wp_parse_args( $args, [
1492 'additional_inline_style' => '',
1493 'href' => '',
1494 'description' => $description,
1495 ] );
1496 $inline_style .= $args['additional_inline_style'];
1497 ?>
1498 <style type="text/css"><?php Utils::print_unescaped_internal_string( $inline_style ); ?></style>
1499 <div class="elementor-template_library-blank_state">
1500 <?php $this->print_blank_state_template( $current_type_label, $args['href'], $args['description'] ); ?>
1501 </div>
1502 <?php
1503 }
1504
1505 /**
1506 * Print Blank State Template
1507 *
1508 * When the an entity (CPT, Taxonomy...etc) has no saved items, print a blank admin page offering
1509 * to create the very first item.
1510 *
1511 * This method is public because it needs to be accessed from outside the Source_Local
1512 *
1513 * @since 3.1.0
1514 * @access public
1515 *
1516 * @param string $current_type_label The Entity title.
1517 * @param string $href The URL for the 'Add New' button.
1518 * @param string $description The sub title describing the Entity (Post Type, Taxonomy, etc.).
1519 */
1520 public function print_blank_state_template( $current_type_label, $href, $description ) {
1521 ?>
1522 <div class="elementor-blank_state">
1523 <i class="eicon-folder"></i>
1524 <h3>
1525 <?php
1526 /* translators: %s: Template type label. */
1527 printf( esc_html__( 'Create Your First %s', 'elementor' ), esc_html( $current_type_label ) );
1528 ?>
1529 </h3>
1530 <p><?php echo wp_kses_post( $description ); ?></p>
1531 <a id="elementor-template-library-add-new" class="elementor-button e-primary" href="<?php echo esc_url( $href ); ?>">
1532 <?php
1533 /* translators: %s: Template type label. */
1534 printf( esc_html__( 'Add New %s', 'elementor' ), esc_html( $current_type_label ) );
1535 ?>
1536 </a>
1537 </div>
1538 <?php
1539 }
1540
1541 /**
1542 * Add filter by category.
1543 *
1544 * In the templates library, add a filter by Elementor library category.
1545 *
1546 * @access public
1547 *
1548 * @param string $post_type The post type slug.
1549 */
1550 public function add_filter_by_category( $post_type ) {
1551 if ( self::CPT !== $post_type ) {
1552 return;
1553 }
1554
1555 $all_items = get_taxonomy( self::TAXONOMY_CATEGORY_SLUG )->labels->all_items;
1556 $dropdown_options = [
1557 'show_option_all' => $all_items,
1558 'show_option_none' => $all_items,
1559 'hide_empty' => 0,
1560 'hierarchical' => 1,
1561 'show_count' => 0,
1562 'orderby' => 'name',
1563 'value_field' => 'slug',
1564 'taxonomy' => self::TAXONOMY_CATEGORY_SLUG,
1565 'name' => self::TAXONOMY_CATEGORY_SLUG,
1566 //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is not required to retrieve the value.
1567 'selected' => Utils::get_super_global_value( $_GET, self::TAXONOMY_CATEGORY_SLUG ) ?? '',
1568 ];
1569
1570 printf(
1571 '<label class="screen-reader-text" for="%1$s">%2$s</label>',
1572 esc_attr( self::TAXONOMY_CATEGORY_SLUG ),
1573 esc_html_x( 'Filter by category', 'Template Library', 'elementor' )
1574 );
1575 wp_dropdown_categories( $dropdown_options );
1576 }
1577
1578 /**
1579 * Import single template.
1580 *
1581 * Import template from a file to the database.
1582 *
1583 * @since 1.6.0
1584 * @access private
1585 *
1586 * @param string $file_path File name.
1587 *
1588 * @return \WP_Error|int|array Local template array, or template ID, or
1589 * `WP_Error`.
1590 */
1591 private function import_single_template( $file_path ) {
1592 $data = $this->prepare_import_template_data( $file_path );
1593
1594 if ( is_wp_error( $data ) ) {
1595 return $data;
1596 }
1597
1598 if ( empty( $data ) ) {
1599 return new \WP_Error( 'file_error', 'Invalid File' );
1600 }
1601
1602 $template_id = $this->save_item( [
1603 'content' => $data['content'],
1604 'title' => $data['title'],
1605 'type' => $data['type'],
1606 'page_settings' => $data['page_settings'],
1607 ] );
1608
1609 if ( is_wp_error( $template_id ) ) {
1610 return $template_id;
1611 }
1612
1613 return $this->get_item( $template_id );
1614 }
1615
1616 /**
1617 * Prepare template to export.
1618 *
1619 * Retrieve the relevant template data and return them as an array.
1620 *
1621 * @since 1.6.0
1622 * @access private
1623 *
1624 * @param int $template_id The template ID.
1625 *
1626 * @return \WP_Error|array Exported template data.
1627 */
1628 private function prepare_template_export( $template_id ) {
1629 $document = Plugin::$instance->documents->get( $template_id );
1630
1631 $template_data = $document->get_export_data();
1632
1633 if ( empty( $template_data['content'] ) ) {
1634 return new \WP_Error( 'empty_template', 'The template is empty' );
1635 }
1636
1637 $content = apply_filters(
1638 'elementor/template_library/sources/local/export/elements',
1639 $template_data['content']
1640 );
1641
1642 $export_data = [
1643 'content' => $content,
1644 'page_settings' => $template_data['settings'],
1645 'version' => DB::DB_VERSION,
1646 'title' => $document->get_main_post()->post_title,
1647 'type' => self::get_template_type( $template_id ),
1648 ];
1649
1650 return [
1651 'name' => 'elementor-' . $template_id . '-' . gmdate( 'Y-m-d' ) . '.json',
1652 'content' => wp_json_encode( $export_data ),
1653 ];
1654 }
1655
1656 /**
1657 * Get template label by type.
1658 *
1659 * Retrieve the template label for any given template type.
1660 *
1661 * @since 2.0.0
1662 * @access private
1663 *
1664 * @param string $template_type Template type.
1665 *
1666 * @return string Template label.
1667 */
1668 private function get_template_label_by_type( $template_type ) {
1669 $document_types = Plugin::instance()->documents->get_document_types();
1670
1671 if ( isset( $document_types[ $template_type ] ) ) {
1672 $template_label = call_user_func( [ $document_types[ $template_type ], 'get_title' ] );
1673 } else {
1674 $template_label = ucwords( str_replace( [ '_', '-' ], ' ', $template_type ) );
1675 }
1676
1677 /**
1678 * Template label by template type.
1679 *
1680 * Filters the template label by template type in the template library .
1681 *
1682 * @since 2.0.0
1683 *
1684 * @param string $template_label Template label.
1685 * @param string $template_type Template type.
1686 */
1687 $template_label = apply_filters( 'elementor/template-library/get_template_label_by_type', $template_label, $template_type );
1688
1689 return $template_label;
1690 }
1691
1692 private function get_template_labels_by_type( $template_type ) {
1693 $labels = [
1694 'singular' => '',
1695 'plural' => '',
1696 ];
1697
1698 if ( ! $template_type ) {
1699 return $labels;
1700 }
1701
1702 $document_types = Plugin::instance()->documents->get_document_types();
1703
1704 if ( isset( $document_types[ $template_type ] ) ) {
1705 $doc_type = $document_types[ $template_type ];
1706 $labels['singular'] = call_user_func( [ $doc_type, 'get_title' ] );
1707 $labels['plural'] = call_user_func( [ $doc_type, 'get_plural_title' ] );
1708 } else {
1709 $labels['singular'] = $this->get_template_label_by_type( $template_type );
1710 }
1711
1712 if ( ! $labels['plural'] ) {
1713 $labels['plural'] = $labels['singular'];
1714 }
1715
1716 return $labels;
1717 }
1718
1719 private function get_current_template_labels() {
1720 $labels = [
1721 'singular' => '',
1722 'plural' => '',
1723 ];
1724
1725 $template_type = Utils::get_super_global_value( $_GET, self::TAXONOMY_TYPE_SLUG );
1726
1727 if ( $template_type ) {
1728 return $this->get_template_labels_by_type( $template_type );
1729 }
1730
1731 $current_tabs_group = $this->get_current_tab_group();
1732
1733 if ( $current_tabs_group ) {
1734 $doc_types = Plugin::$instance->documents->get_document_types( [
1735 'admin_tab_group' => $current_tabs_group,
1736 ], 'and' );
1737
1738 if ( 1 === count( $doc_types ) ) {
1739 $doc_type = reset( $doc_types );
1740 $labels['singular'] = call_user_func( [ $doc_type, 'get_title' ] );
1741 $labels['plural'] = call_user_func( [ $doc_type, 'get_plural_title' ] );
1742 }
1743 }
1744
1745 if ( ! $labels['plural'] ) {
1746 $labels['plural'] = $labels['singular'];
1747 }
1748
1749 return $labels;
1750 }
1751
1752 /**
1753 * Filter template types in admin query.
1754 *
1755 * Update the template types in the main admin query.
1756 *
1757 * Fired by `parse_query` action.
1758 *
1759 * @since 2.4.0
1760 * @access public
1761 *
1762 * @param \WP_Query $query The `WP_Query` instance.
1763 */
1764 public function admin_query_filter_types( \WP_Query $query ) {
1765 if ( ! $this->is_current_screen() || ! empty( $query->query_vars['meta_key'] ) ) {
1766 return;
1767 }
1768
1769 $current_tabs_group = $this->get_current_tab_group();
1770
1771 if ( isset( $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] ) && '-1' === $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] ) {
1772 unset( $query->query_vars[ self::TAXONOMY_CATEGORY_SLUG ] );
1773 }
1774
1775 if ( empty( $current_tabs_group ) ) {
1776 return;
1777 }
1778
1779 $doc_types = Plugin::$instance->documents->get_document_types( [
1780 'admin_tab_group' => $current_tabs_group,
1781 ] );
1782
1783 $query->query_vars['meta_key'] = Document::TYPE_META_KEY;
1784 $query->query_vars['meta_value'] = array_keys( $doc_types );
1785 }
1786
1787 /**
1788 * Add template library actions.
1789 *
1790 * Register filters and actions for the template library.
1791 *
1792 * @since 2.0.0
1793 * @access private
1794 */
1795 private function add_actions() {
1796 if ( is_admin() ) {
1797 add_action( 'elementor/admin/menu/register', function ( Admin_Menu_Manager $admin_menu ) {
1798 $this->register_admin_menu( $admin_menu );
1799 }, static::ADMIN_MENU_PRIORITY );
1800
1801 add_action( 'elementor/editor-one/menu/register', function ( Menu_Data_Provider $menu_data_provider ) {
1802 $this->register_editor_one_menu( $menu_data_provider );
1803 } );
1804
1805 add_action( 'elementor/editor-one/menu/excluded_level4_slugs', function ( array $excluded_slugs ): array {
1806 $excluded_slugs[] = 'edit.php?post_type=elementor_library#add_new';
1807 $excluded_slugs[] = 'edit-tags.php?taxonomy=elementor_library_category&amp;post_type=elementor_library';
1808 return $excluded_slugs;
1809 } );
1810
1811 add_filter( 'elementor/editor-one/menu/elementor_post_types', function ( array $elementor_post_types ): array {
1812 $elementor_post_types[ self::CPT ] = [];
1813
1814 return $elementor_post_types;
1815 } );
1816
1817 add_filter( 'elementor/editor-one/admin-edit-post-types', function ( array $post_types ): array {
1818 $post_types[] = self::CPT;
1819
1820 return $post_types;
1821 } );
1822
1823 add_action( 'elementor/admin/menu/register', function ( Admin_Menu_Manager $admin_menu ) {
1824 $this->admin_menu_reorder( $admin_menu );
1825 }, 800 );
1826
1827 add_action( 'elementor/admin/menu/after_register', function () {
1828 $this->admin_menu_set_current();
1829 } );
1830
1831 add_filter( 'admin_title', [ $this, 'admin_title' ], 10, 2 );
1832 add_action( 'all_admin_notices', [ $this, 'replace_admin_heading' ] );
1833 add_filter( 'post_row_actions', [ $this, 'post_row_actions' ], 10, 2 );
1834 add_action( 'admin_footer', [ $this, 'admin_import_template_form' ] );
1835 add_action( 'save_post', [ $this, 'on_save_post' ], 10, 2 );
1836 add_filter( 'display_post_states', [ $this, 'remove_elementor_post_state_from_library' ], 11, 2 );
1837
1838 add_action( 'parse_query', [ $this, 'admin_query_filter_types' ] );
1839
1840 // Template filter by category.
1841 add_action( 'restrict_manage_posts', [ $this, 'add_filter_by_category' ] );
1842
1843 // Template type column.
1844 add_action( 'manage_' . self::CPT . '_posts_columns', [ $this, 'admin_columns_headers' ] );
1845 add_action( 'manage_' . self::CPT . '_posts_custom_column', [ $this, 'admin_columns_content' ], 10, 2 );
1846
1847 // Template library bulk actions.
1848 add_filter( 'bulk_actions-edit-elementor_library', [ $this, 'admin_add_bulk_export_action' ] );
1849 add_filter( 'handle_bulk_actions-edit-elementor_library', [ $this, 'admin_export_multiple_templates' ], 10, 3 );
1850
1851 // Print template library tabs.
1852 add_filter( 'views_edit-' . self::CPT, [ $this, 'admin_print_tabs' ] );
1853
1854 // Show blank state.
1855 add_action( 'manage_posts_extra_tablenav', [ $this, 'maybe_render_blank_state' ] );
1856 }
1857
1858 add_action( 'elementor/document/after_save', [ $this, 'on_template_update' ], 10, 2 );
1859
1860 add_action( 'template_redirect', [ $this, 'block_template_frontend' ] );
1861
1862 // Remove elementor library templates from WP Sitemap
1863 add_filter(
1864 'wp_sitemaps_post_types',
1865 function( $post_types ) {
1866 return $this->remove_elementor_cpt_from_sitemap( $post_types );
1867 }
1868 );
1869 }
1870
1871 public function on_template_update( \Elementor\Core\Base\Document $document, array $data ) {
1872 if ( ! empty( $data['post_title'] ) ) {
1873 wp_update_post( [
1874 'ID' => $document->get_main_id(),
1875 'post_title' => $data['post_title'],
1876 ] );
1877 }
1878 }
1879
1880 /**
1881 * @since 2.0.6
1882 * @access public
1883 */
1884 public function admin_columns_content( $column_name, $post_id ) {
1885 if ( 'elementor_library_type' === $column_name ) {
1886 /** @var Document $document */
1887 $document = Plugin::$instance->documents->get( $post_id );
1888
1889 if ( $document && $document instanceof Library_Document ) {
1890 $document->print_admin_column_type();
1891 }
1892 }
1893 }
1894
1895 /**
1896 * @since 2.0.6
1897 * @access public
1898 */
1899 public function admin_columns_headers( $posts_columns ) {
1900 // Replace original column that bind to the taxonomy - with another column.
1901 unset( $posts_columns['taxonomy-elementor_library_type'] );
1902
1903 $offset = 2;
1904
1905 $posts_columns = array_slice( $posts_columns, 0, $offset, true ) + [
1906 'elementor_library_type' => esc_html__( 'Type', 'elementor' ),
1907 ] + array_slice( $posts_columns, $offset, null, true );
1908
1909 return $posts_columns;
1910 }
1911
1912 public function get_current_tab_group() {
1913 $current_tabs_group = Utils::get_super_global_value( $_GET, 'tabs_group' ) ?? '';
1914 $type_slug = Utils::get_super_global_value( $_GET, self::TAXONOMY_TYPE_SLUG );
1915
1916 if ( $type_slug ) {
1917 $doc_type = Plugin::$instance->documents->get_document_type( $type_slug, '' );
1918 if ( $doc_type ) {
1919 $current_tabs_group = $doc_type::get_property( 'admin_tab_group' );
1920 }
1921 }
1922 return $current_tabs_group;
1923 }
1924
1925 private function get_library_title() {
1926 $title = '';
1927
1928 if ( $this->is_current_screen() ) {
1929 $current_tab_group = $this->get_current_tab_group();
1930
1931 if ( $current_tab_group ) {
1932 $titles = [
1933 'library' => esc_html__( 'Saved Templates', 'elementor' ),
1934 'theme' => esc_html__( 'Theme Builder', 'elementor' ),
1935 'popup' => esc_html__( 'Popups', 'elementor' ),
1936 ];
1937
1938 if ( ! empty( $titles[ $current_tab_group ] ) ) {
1939 $title = $titles[ $current_tab_group ];
1940 }
1941 }
1942 }
1943
1944 return $title;
1945 }
1946
1947 private function is_current_screen() {
1948 global $pagenow, $typenow;
1949
1950 return 'edit.php' === $pagenow && self::CPT === $typenow;
1951 }
1952
1953 /**
1954 * @param array $post_types
1955 *
1956 * @return array
1957 */
1958 private function remove_elementor_cpt_from_sitemap( array $post_types ) {
1959 unset( $post_types[ self::CPT ] );
1960
1961 return $post_types;
1962 }
1963
1964 private function avoid_rest_access_for_non_admins(): void {
1965 add_filter( 'rest_pre_dispatch', function ( $value, \WP_REST_Server $server, \WP_REST_Request $request ) {
1966 if ( strpos( $request->get_route(), self::CPT ) !== false ) {
1967 if ( ! current_user_can( 'manage_options' ) ) {
1968 return new \WP_Error( 'rest_forbidden', esc_html__( 'Sorry, you are not allowed to do that.', 'elementor' ), [ 'status' => rest_authorization_required_code() ] );
1969 }
1970 }
1971
1972 return $value;
1973 }, 10, 3 );
1974 }
1975
1976 public function save_bulk_items( array $args = [] ) {
1977 $items = [];
1978
1979 foreach ( $args as $item ) {
1980 $items[] = $this->save_item( [
1981 'content' => $item['content'],
1982 'title' => $item['title'],
1983 'type' => $item['type'],
1984 'page_settings' => $item['page_settings'],
1985 ] );
1986 }
1987
1988 return $items;
1989 }
1990
1991 /**
1992 * Template library local source constructor.
1993 *
1994 * Initializing the template library local source base by registering custom
1995 * template data and running custom actions.
1996 *
1997 * @since 1.0.0
1998 * @access public
1999 */
2000 public function __construct() {
2001 parent::__construct();
2002
2003 $this->add_actions();
2004 }
2005
2006 public function format_args_for_bulk_action( $args ) {
2007 $bulk_args = [];
2008
2009 foreach ( $args['from_template_id'] as $from_template_id ) {
2010 if ( ! $this->is_allowed_to_read_template( [
2011 'template_id' => $from_template_id,
2012 ] ) ) {
2013 continue;
2014 }
2015
2016 $document = Plugin::$instance->documents->get( $from_template_id );
2017
2018 if ( ! $document ) {
2019 continue;
2020 }
2021
2022 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $from_template_id );
2023
2024 $bulk_args[] = array_merge(
2025 $args,
2026 [
2027 'title' => $document->get_post()->post_title,
2028 'type' => $document::get_type(),
2029 'content' => $document->get_elements_data(),
2030 'page_settings' => $page->get_data( 'settings' ),
2031 ]
2032 );
2033 }
2034
2035 return $bulk_args;
2036 }
2037
2038 public function format_args_for_single_action( $args ) {
2039 if ( ! $this->is_allowed_to_read_template( [
2040 'template_id' => $args['from_template_id'],
2041 ] ) ) {
2042 return new \WP_Error(
2043 'template_error',
2044 esc_html__( 'You do not have permission to access this template.', 'elementor' )
2045 );
2046 }
2047
2048 $document = Plugin::$instance->documents->get( $args['from_template_id'] );
2049
2050 if ( ! $document ) {
2051 return new \WP_Error( 'template_error', 'Document not found.' );
2052 }
2053
2054 $args['content'] = $document->get_elements_data();
2055
2056 $page = SettingsManager::get_settings_managers( 'page' )->get_model( $args['from_template_id'] );
2057 $args['page_settings'] = $page->get_data( 'settings' );
2058
2059 return $args;
2060 }
2061
2062 public function is_allowed_to_read_template( array $args ): bool {
2063 if ( null === $this->wordpress_adapter ) {
2064 $this->set_wordpress_adapter( new WordPress_Adapter() );
2065 }
2066
2067 if ( ! $this->should_check_permissions( $args ) ) {
2068 return true;
2069 }
2070
2071 $post_id = intval( $args['template_id'] );
2072 $post_status = $this->wordpress_adapter->get_post_status( $post_id );
2073 $is_private_or_non_published = ( 'private' === $post_status && ! $this->wordpress_adapter->current_user_can( 'read_private_posts', $post_id ) ) || ( 'publish' !== $post_status );
2074
2075 $can_read_template = $is_private_or_non_published || $this->wordpress_adapter->current_user_can( 'edit_post', $post_id );
2076
2077 return apply_filters( 'elementor/template-library/is_allowed_to_read_template', $can_read_template, $args );
2078 }
2079
2080 private function should_check_permissions( array $args ): bool {
2081 if ( null === $this->elementor_adapter ) {
2082 $this->set_elementor_adapter( new Elementor_Adapter() );
2083 }
2084
2085 $check_permissions = isset( $args['check_permissions'] ) && false === $args['check_permissions'];
2086
2087 if ( $check_permissions ) {
2088 return false;
2089 }
2090
2091 return true;
2092 }
2093
2094 public function set_wordpress_adapter( Wordpress_Adapter_Interface $wordpress_adapter ) {
2095 $this->wordpress_adapter = $wordpress_adapter;
2096 }
2097
2098 public function set_elementor_adapter( Elementor_Adapter_Interface $elementor_adapter ): void {
2099 $this->elementor_adapter = $elementor_adapter;
2100 }
2101 }
2102