1: <?php
2: /**
3: * Elementor Bundled Templates
4: *
5: * Installs the design templates that ship inside the plugin as real
6: * `elementor_library` posts, so they are immediately available (and editable)
7: * in Elementor without the user having to import anything.
8: *
9: * @package EPL
10: * @subpackage Elementor/Seeder
11: * @copyright Copyright (c) 2020, Merv Barrett
12: * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
13: * @since 3.5.0
14: */
15:
16: // Exit if accessed directly.
17: if ( ! defined( 'ABSPATH' ) ) {
18: exit;
19: }
20:
21: /**
22: * EPL_Elementor_Template_Seeder Class
23: *
24: * Seeds the plugin's bundled Elementor templates on install and on upgrade.
25: *
26: * Seeding is deliberately idempotent and non-destructive:
27: *
28: * - Each bundled template is installed once and tracked by slug in the
29: * `epl_elementor_bundled_templates` option, so an upgrade never produces
30: * duplicates.
31: * - The checksum of the JSON that was written is recorded. When a newer plugin
32: * ships a revised design, the template is only refreshed if the user has not
33: * edited it. A user-modified template is left completely alone — their work
34: * is never silently overwritten.
35: * - Deleting a seeded template is respected. It is not silently resurrected on
36: * the next upgrade.
37: *
38: * @since 3.5.0
39: */
40: class EPL_Elementor_Template_Seeder {
41:
42: /**
43: * Option storing the install state of each bundled template.
44: *
45: * Shape: array( slug => array( 'post_id' => int, 'checksum' => string, 'version' => string ) ).
46: *
47: * @var string
48: */
49: const STATE_OPTION = 'epl_elementor_bundled_templates';
50:
51: /**
52: * Marks a post as having been created by this seeder, and with which slug.
53: *
54: * @var string
55: */
56: const SLUG_META = '_epl_bundled_template';
57:
58: /**
59: * Class constructor.
60: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
61: */
62: public function __construct() {
63: // Runs for installs, plugin updates, and the case where Elementor is
64: // activated after EPL. Cheap: the option check short-circuits at once
65: // when everything is already seeded.
66: add_action( 'admin_init', array( $this, 'maybe_seed' ), 20 );
67: }
68:
69: /**
70: * The templates bundled with this plugin.
71: *
72: * `version` is a content version for the bundled design. Bump it when the
73: * shipped JSON changes and the new design should reach existing sites that
74: * have not customised it.
75: *
76: * @return array
77: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
78: */
79: public static function get_bundled_templates() {
80: return array(
81: 'epl-card' => array(
82: 'title' => __( 'EPL Card', 'easy-property-listings' ),
83: 'type' => EPL_Elementor_Loop_Card_Document::TYPE,
84: 'context' => 'listing',
85: 'file' => EPL_PATH_LIB . 'page-builders/elementor/templates/epl-card.json',
86: 'version' => '1.0',
87: ),
88: );
89: }
90:
91: /**
92: * Install any bundled template that is not yet present, and refresh any
93: * that the user has left untouched when a newer design ships.
94: *
95: * @return void
96: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
97: * @since 3.6.0 Fix: returns early when the bundled templates are current, and seeds one request at a time.
98: */
99: public function maybe_seed() {
100: if ( ! did_action( 'elementor/loaded' ) ) {
101: return;
102: }
103:
104: if ( ! current_user_can( 'edit_theme_options' ) ) {
105: return;
106: }
107:
108: $state = (array) get_option( self::STATE_OPTION, array() );
109: $changed = false;
110:
111: // Nothing to do when every bundled template is recorded at its current version.
112: $current = true;
113: foreach ( self::get_bundled_templates() as $slug => $template ) {
114: if ( ! isset( $state[ $slug ]['version'] ) || $state[ $slug ]['version'] !== $template['version'] ) {
115: $current = false;
116: break;
117: }
118: }
119: if ( $current ) {
120: return;
121: }
122:
123: // One request at a time, so two admin requests can't both create the template.
124: if ( ! add_option( 'epl_elementor_seeding', time(), '', false ) ) {
125: if ( (int) get_option( 'epl_elementor_seeding' ) > time() - 60 ) {
126: return;
127: }
128: update_option( 'epl_elementor_seeding', time(), false ); // A stale lock from a failed request.
129: }
130:
131: foreach ( self::get_bundled_templates() as $slug => $template ) {
132: $result = $this->seed_template( $slug, $template, $state );
133:
134: if ( null !== $result ) {
135: $state[ $slug ] = $result;
136: $changed = true;
137: }
138: }
139:
140: if ( $changed ) {
141: update_option( self::STATE_OPTION, $state );
142: }
143:
144: delete_option( 'epl_elementor_seeding' );
145: }
146:
147: /**
148: * Install or refresh a single bundled template.
149: *
150: * @param string $slug Bundled template slug.
151: * @param array $template Template definition.
152: * @param array $state Current seeder state for all templates.
153: * @return array|null New state for this slug, or null when nothing was done.
154: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
155: */
156: private function seed_template( $slug, $template, $state ) {
157: $json = $this->read_template_file( $template['file'] );
158:
159: if ( '' === $json ) {
160: return null;
161: }
162:
163: $checksum = md5( $json );
164: $existing = isset( $state[ $slug ] ) ? $state[ $slug ] : array();
165: $post_id = isset( $existing['post_id'] ) ? absint( $existing['post_id'] ) : 0;
166:
167: // Never seed twice for the same slug, even if the tracked post was
168: // deleted — a user removing a bundled template means they do not want
169: // it, so it must not reappear on the next upgrade.
170: if ( $post_id ) {
171: if ( 'publish' !== get_post_status( $post_id ) ) {
172: return null;
173: }
174:
175: $installed_checksum = isset( $existing['checksum'] ) ? $existing['checksum'] : '';
176: $current_checksum = md5( (string) get_post_meta( $post_id, '_elementor_data', true ) );
177:
178: // Same design already installed, or the user has customised it.
179: if ( $checksum === $installed_checksum || $current_checksum !== $installed_checksum ) {
180: return null;
181: }
182:
183: $this->write_template_data( $post_id, $json );
184:
185: return array(
186: 'post_id' => $post_id,
187: 'checksum' => $checksum,
188: 'version' => $template['version'],
189: );
190: }
191:
192: if ( ! empty( $existing ) ) {
193: return null;
194: }
195:
196: // The tracking option can be lost independently of the templates it
197: // tracks — a partial migration, a cloned staging database, a reset
198: // options table. Adopt a template this seeder already created rather
199: // than installing a second copy of it.
200: $orphan = $this->find_seeded_post( $slug );
201:
202: if ( $orphan ) {
203: return array(
204: 'post_id' => $orphan,
205: 'checksum' => md5( (string) get_post_meta( $orphan, '_elementor_data', true ) ),
206: 'version' => $template['version'],
207: );
208: }
209:
210: $post_id = wp_insert_post(
211: array(
212: 'post_title' => $template['title'],
213: 'post_type' => 'elementor_library',
214: 'post_status' => 'publish',
215: ),
216: true
217: );
218:
219: if ( is_wp_error( $post_id ) || ! $post_id ) {
220: return null;
221: }
222:
223: update_metadata( 'post', $post_id, '_elementor_edit_mode', 'builder' );
224: update_metadata( 'post', $post_id, '_elementor_template_type', $template['type'] );
225: update_metadata( 'post', $post_id, '_epl_elementor_template_context', $template['context'] );
226: update_metadata( 'post', $post_id, self::SLUG_META, $slug );
227:
228: if ( defined( 'ELEMENTOR_VERSION' ) ) {
229: update_metadata( 'post', $post_id, '_elementor_version', ELEMENTOR_VERSION );
230: }
231:
232: $this->write_template_data( $post_id, $json );
233:
234: return array(
235: 'post_id' => $post_id,
236: 'checksum' => $checksum,
237: 'version' => $template['version'],
238: );
239: }
240:
241: /**
242: * Find a template this seeder previously created for a slug.
243: *
244: * @param string $slug Bundled template slug.
245: * @return int Post ID, or 0 when none exists.
246: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
247: * @since 3.6.0 Removed suppress_filters (get_posts() already suppresses filters; Plugin Check flags it).
248: */
249: private function find_seeded_post( $slug ) {
250: $found = get_posts(
251: array(
252: 'post_type' => 'elementor_library',
253: 'post_status' => 'publish',
254: 'posts_per_page' => 1,
255: 'orderby' => 'ID',
256: 'order' => 'ASC',
257: 'fields' => 'ids',
258: 'no_found_rows' => true,
259: 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Runs once per install/upgrade.
260: array(
261: 'key' => self::SLUG_META,
262: 'value' => $slug,
263: ),
264: ),
265: )
266: );
267:
268: return empty( $found ) ? 0 : absint( $found[0] );
269: }
270:
271: /**
272: * Write the Elementor element tree onto a template post and drop its
273: * generated CSS so it regenerates from the new markup.
274: *
275: * @param int $post_id Template post ID.
276: * @param string $json Element tree as JSON.
277: * @return void
278: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
279: */
280: private function write_template_data( $post_id, $json ) {
281: // Elementor stores this slashed; `update_metadata()` unslashes once.
282: update_metadata( 'post', $post_id, '_elementor_data', wp_slash( $json ) );
283: delete_metadata( 'post', $post_id, '_elementor_css' );
284: delete_metadata( 'post', $post_id, '_elementor_element_cache' );
285:
286: if ( class_exists( '\Elementor\Plugin' ) && isset( \Elementor\Plugin::$instance->files_manager ) ) {
287: \Elementor\Plugin::$instance->files_manager->clear_cache();
288: }
289: }
290:
291: /**
292: * Read and validate a bundled template JSON file.
293: *
294: * @param string $file Absolute path to the JSON file.
295: * @return string Compact JSON, or '' when the file is missing or invalid.
296: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
297: */
298: private function read_template_file( $file ) {
299: if ( ! is_readable( $file ) ) {
300: return '';
301: }
302:
303: $raw = file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local bundled asset.
304:
305: if ( false === $raw ) {
306: return '';
307: }
308:
309: $decoded = json_decode( $raw, true );
310:
311: if ( ! is_array( $decoded ) || empty( $decoded ) ) {
312: return '';
313: }
314:
315: return wp_json_encode( $decoded );
316: }
317:
318: /**
319: * The post ID of an installed bundled template.
320: *
321: * @param string $slug Bundled template slug.
322: * @return int Post ID, or 0 when not installed or no longer published.
323: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
324: */
325: public static function get_template_id( $slug ) {
326: $state = (array) get_option( self::STATE_OPTION, array() );
327:
328: if ( empty( $state[ $slug ]['post_id'] ) ) {
329: return 0;
330: }
331:
332: $post_id = absint( $state[ $slug ]['post_id'] );
333:
334: return ( 'publish' === get_post_status( $post_id ) ) ? $post_id : 0;
335: }
336:
337: /**
338: * The bundled card used as the out-of-the-box default listing card.
339: *
340: * @return int Post ID, or 0 when unavailable.
341: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
342: */
343: public static function get_default_card_id() {
344: return (int) apply_filters( 'epl_elementor_default_card_id', self::get_template_id( 'epl-card' ) );
345: }
346: }
347: