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

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