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

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