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

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