PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.0.1
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.0.1
3.7.5 3.7.4 3.7.3 3.7.2 1-final 3.7.1 3.7.0 3.6.8 3.6.7 3.6.6 3.6.5 3.6.4 3.6.3 3.6.2 3.6.1 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.10 All 111 releases
← All changes | includes/Core/Importer/FullSiteImport.php +252 -851 3.1.103.0.1 View file →
@@ -1,12 +1,10 @@
1 1 <?php
2 2
3 3 namespace Templately\Core\Importer;
4 4
5 -use Elementor\Plugin;
6 -use Error;
5 +use EbStyleHandler;
7 6 use Exception;
8 -use Templately\Core\Importer\Utils\Utils;
9 7 use Templately\Utils\Base;
10 8 use Templately\Utils\Helper;
11 9 use Templately\Utils\Installer;
12 10 use Templately\Utils\Options;
@@ -20,9 +18,8 @@
20 18
21 19 private $version = '1.0.0';
22 20
23 21 public $session_id;
24 - public $download_key;
25 22 public $dir_path;
26 23 protected $filePath;
27 24 protected $tmp_dir = null;
28 25 protected $dev_mode = false;
@@ -29,251 +26,58 @@
29 26 protected $api_key = '';
30 27 public $request_params = [];
31 28 protected $documents_data = [];
32 29 protected $dependency_data = [];
33 - private $is_import_status_handled = false;
34 30
35 31 public function __construct() {
36 - $this->dev_mode = defined('TEMPLATELY_DEV') && TEMPLATELY_DEV;
37 - $this->api_key = Options::get_instance()->get('api_key');
32 + $this->dev_mode = defined( 'TEMPLATELY_DEV' ) && TEMPLATELY_DEV;
33 + $this->api_key = Options::get_instance()->get( 'api_key' );
38 34
39 - $this->add_ajax_action('import_settings', $this);
40 - $this->add_ajax_action('import_status', $this);
41 - $this->add_ajax_action('import', $this);
42 - $this->add_ajax_action('import_revert', $this);
43 - $this->add_ajax_action('import_info', $this);
44 - $this->add_ajax_action('import_close_feedback_modal', $this);
45 - $this->add_ajax_action('feedback_form', $this);
35 + add_action( 'wp_ajax_templately_import_settings', [ $this, 'import_settings' ] );
36 + add_action( 'wp_ajax_templately_pack_import', [ $this, 'import' ] );
46 37
47 - add_action('admin_init', [$this, 'admin_init']);
48 - // add_action('admin_notices', [$this, 'add_revert_button']);
49 -
50 - if(isset($_GET['action']) && ($_GET['action'] == 'templately_pack_import' || $_GET['action'] == 'templately_pack_import_status')) {
51 - add_filter('wp_redirect', '__return_false', 999);
52 - }
53 -
54 - if ($this->dev_mode) {
55 - add_filter('http_request_host_is_external', '__return_true');
56 - add_filter('http_request_args', function ($args) {
38 + if ( $this->dev_mode ) {
39 + add_filter( 'http_request_host_is_external', '__return_true' );
40 + add_filter( 'http_request_args', function ( $args ) {
57 41 $args['sslverify'] = false;
58 42
59 43 return $args;
60 - });
44 + } );
61 45 }
46 + add_action( 'eb_frontend_assets', [ $this, 'enqueue_template_assets' ], 10, 2 );
47 + add_filter( 'the_content', [$this, 'filter_content'], 10 ,1);
62 48 }
63 49
64 - public function add_ajax_action($action, $object) {
65 - add_action("wp_ajax_templately_pack_$action", function() use ($action, $object) {
66 - // Check nonce
67 - $nonce = null;
68 - if(isset($_POST['nonce'])){
69 - $nonce = $_POST['nonce'];
70 - }
71 - if(isset($_GET['nonce'])){
72 - $nonce = $_GET['nonce'];
73 - }
74 - if (!$nonce || !wp_verify_nonce($nonce, 'templately_nonce')) {
75 - wp_send_json_error(['message' => __('Invalid nonce', 'templately')]);
76 - wp_die();
77 - }
78 -
79 - // Check user capability
80 - if (!current_user_can('install_plugins') || !current_user_can('install_themes')) {
81 - wp_send_json_error(['message' => __('Insufficient permissions', 'templately')]);
82 - wp_die();
83 - }
84 -
85 - // Call the actual handler method
86 - call_user_func([$object, $action]);
87 - });
88 - }
89 -
90 - public function admin_init() {
91 - if (get_option('templately_flush_rewrite_rules', false)) {
92 - flush_rewrite_rules();
93 - delete_option('templately_flush_rewrite_rules');
94 - }
95 - }
96 -
97 50 public function import_settings() {
98 - $data = wp_unslash($_POST);
99 -
100 - update_option(self::SESSION_OPTION_KEY, $data);
101 -
102 - delete_option('templately_fsi_imported_list');
103 - delete_option('templately_fsi_log');
104 -
105 - wp_send_json_success([
106 - 'is_lightspeed' => !Helper::should_flush(),
107 - ]);
108 - }
109 -
110 - public function import_close_feedback_modal() {
111 - $return = null;
112 - if(isset($_GET['closeAction']) && $_GET['closeAction']){
113 - $review_email = isset($_POST['review-email']) ? sanitize_email($_POST['review-email']) : '';
114 - $pack_id = get_user_meta(get_current_user_id(), 'templately_fsi_pack_id', true);
115 -
116 - // Prepare the body of the request
117 - $body = json_encode([
118 - 'action' => $_GET['closeAction'],
119 - 'email' => $review_email,
120 - 'pack_id' => (int) $pack_id,
121 - ]);
122 -
123 - // Send the request to the API
124 - $response = wp_remote_post($this->get_api_url('v2', 'feedback/close'), [
125 - 'timeout' => 30,
126 - 'headers' => [
127 - 'Content-Type' => 'application/json',
128 - 'Authorization' => 'Bearer ' . $this->api_key,
129 - 'x-templately-ip' => Helper::get_ip(),
130 - 'x-templately-url' => home_url('/'),
131 - 'x-templately-version' => TEMPLATELY_VERSION,
132 - ],
133 - 'body' => $body,
134 - ]);
135 - $body = wp_remote_retrieve_body($response);
136 - $return = json_decode($body, true);
51 + if( ! current_user_can( 'edit_posts' ) ) {
52 + wp_send_json_error( __( 'Unauthorized action.', 'templately' ) );
137 53 }
138 - update_user_meta(get_current_user_id(), 'templately_fsi_complete', 'done');
139 - wp_send_json_success($return);
140 - }
141 - public function feedback_form() {
142 - // Get data from $_POST
143 - $review_description = isset($_POST['review-description']) ? sanitize_textarea_field($_POST['review-description']) : '';
144 - $review_email = isset($_POST['review-email']) ? sanitize_email($_POST['review-email']) : '';
145 - $rating = isset($_POST['rating']) ? sanitize_text_field($_POST['rating']) : '';
146 - $pack_id = get_user_meta(get_current_user_id(), 'templately_fsi_pack_id', true);
147 54
148 - // Prepare the body of the request
149 - $body = json_encode([
150 - 'description' => $review_description,
151 - 'email' => $review_email,
152 - 'rating' => (int) $rating,
153 - 'pack_id' => (int) $pack_id,
154 - ]);
55 + $data = wp_unslash( $_POST );
155 56
156 - // Send the request to the API
157 - $response = wp_remote_post($this->get_api_url('v2', 'feedback/store'), [
158 - 'timeout' => 30,
159 - 'headers' => [
160 - 'Content-Type' => 'application/json',
161 - 'Authorization' => 'Bearer ' . $this->api_key,
162 - 'x-templately-ip' => Helper::get_ip(),
163 - 'x-templately-url' => home_url('/'),
164 - 'x-templately-version' => TEMPLATELY_VERSION,
165 - ],
166 - 'body' => $body,
167 - ]);
168 -
169 - if (is_wp_error($response)) {
170 - wp_send_json_error($response->get_error_message());
57 + // Upload the logo and add its URL to the data
58 + $logo_url = $this->upload_logo();
59 + if ($logo_url !== null) {
60 + $data['logo'] = $logo_url;
171 61 }
172 62
173 - $body = wp_remote_retrieve_body($response);
174 - $data = json_decode($body, true);
175 -
176 - if (wp_remote_retrieve_response_code($response) != 200 && wp_remote_retrieve_response_code($response) != 201) {
177 - if (isset($data['status'], $data['message']) && $data['status'] === 'error') {
178 - wp_send_json_error($data['message']);
179 - }
180 -
181 - wp_send_json_error('API request failed with response code ' . wp_remote_retrieve_response_code($response));
182 - }
183 -
184 - if (!isset($data['status']) || $data['status'] !== 'success') {
185 - wp_send_json_error('API response indicates failure.');
186 - }
187 -
188 - if (!isset($data['message'])) {
189 - wp_send_json_error('API response missing data.');
190 - }
191 -
192 - $result = $data['message'];
193 -
194 - wp_send_json_success($result);
63 + wp_send_json_success( update_option( self::SESSION_OPTION_KEY, $data ) );
195 64 }
196 65
197 - private function update_session_data($data): bool {
198 - $old_data = $this->get_session_data();
66 + private function update_session_data( $data ): bool {
67 + $old_data = get_option( self::SESSION_OPTION_KEY, [] );
199 68
200 - return update_option(self::SESSION_OPTION_KEY, wp_parse_args($data, $old_data));
69 + return update_option( self::SESSION_OPTION_KEY, wp_parse_args( $data, $old_data ) );
201 70 }
202 71
203 - protected function CallingFunctionName($id = null) {
204 - $return = 'unknown';
205 - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
206 -
207 - // Check if the trace has at least three elements
208 - if (isset($trace[2])) {
209 - $final_call = $trace[2];
210 -
211 - // Check if 'class' and 'function' indexes exist
212 - if (isset($final_call['class']) && isset($final_call['function'])) {
213 - $return = "{$final_call['class']}::{$final_call['function']}";
214 - }
215 - else if(isset($final_call['function'])){
216 - $return = $final_call['function'];
217 - }
218 - if(!empty($id)){
219 - $return .= "::$id";
220 - }
221 - }
222 -
223 - // Return a default value if 'class' or 'function' index does not exist, or if the trace doesn't have at least three elements
224 - return $return;
225 - }
226 -
227 -
228 - public function get_progress($defaults = [], $unique_id = null) {
229 - $calling_class = $this->CallingFunctionName($unique_id);
230 - if(isset($this->request_params['progress'][$calling_class])){
231 - return $this->request_params['progress'][$calling_class];
232 - }
233 - return $defaults;
234 - }
235 -
236 -
237 - public function update_progress( $progress, $imported_data = null, $unique_id = null ): bool {
238 - $calling_class = $this->CallingFunctionName($unique_id);
239 - $old_data = $this->get_session_data();
240 -
241 - $new_data = [];
242 -
243 - if($progress !== null){
244 - $new_data['progress'] = [$calling_class => $progress];
245 - }
246 - if($imported_data !== null){
247 - $new_data['imported_data'] = $imported_data;
248 - }
249 -
250 - $this->request_params = $this->recursive_wp_parse_args( $new_data, $old_data );
251 - return update_option( self::SESSION_OPTION_KEY, $this->request_params );
252 - }
253 -
254 - public function recursive_wp_parse_args( $args, $defaults ) {
255 - $args = (array) $args;
256 - $defaults = (array) $defaults;
257 - $r = $defaults;
258 - foreach ( $args as $key => $value ) {
259 - if ( is_array( $value ) && isset( $r[ $key ] ) ) {
260 - $r[ $key ] = $this->recursive_wp_parse_args( $value, $r[ $key ] );
261 - } else {
262 - $r[ $key ] = $value;
263 - }
264 - }
265 - return $r;
266 - }
267 -
268 72 public function get_session_data(): array {
269 - $data = get_option(self::SESSION_OPTION_KEY, []);
73 + $data = get_option( self::SESSION_OPTION_KEY, [] );
270 74
271 75 $options = [];
272 76
273 77 if ( is_array( $data ) && ! empty( $data ) ) {
274 78 foreach ( $data as $key => $value ) {
275 - $json = is_string($value) ? json_decode( $value, true ) : null;
79 + $json = json_decode( $value, true );
276 80 $options[ $key ] = $json !== null ? $json : $value;
277 81 }
278 82 }
279 83
@@ -279,137 +83,55 @@
279 83
280 84 return $options;
281 85 }
282 86
283 - public function initialize_props() {
284 - $data = $this->get_session_data();
285 - if (isset($data['session_id'])) {
286 - $this->session_id = $data['session_id'];
287 - }
288 - if (isset($data['dir_path'])) {
289 - $this->dir_path = $data['dir_path'];
290 - }
291 - if (isset($data['download_key'])) {
292 - $this->download_key = $data['download_key'];
293 - }
294 - if (isset($data['dependency_data'])) {
295 - $this->dependency_data = $data['dependency_data'];
296 - }
87 + private function clear_session_data(): bool {
88 + return delete_site_option( self::SESSION_OPTION_KEY );
297 89 }
298 90
299 - private function clear_session_data(): bool {
300 - return delete_site_option(self::SESSION_OPTION_KEY);
301 - }
91 + public function import() {
92 + if ( ! $this->dev_mode && ! wp_doing_ajax() ) {
93 + exit;
94 + }
302 95
303 - private function finishRequestHeaders() {
304 96 header( "Cache-Control: no-store, no-cache" );
305 - // header( 'Content-Type: text/event-stream, charset=UTF-8' );
306 - // header( "Connection: Keep-Alive" );
97 + header( 'Content-Type: text/event-stream, charset=UTF-8' );
98 + header( "Connection: Keep-Alive" );
307 99
308 - // Ignore user aborts and allow the script to run forever
309 - // (Use with caution, consider progress updates or timeouts)
310 - ignore_user_abort(true);
311 -
312 - // Time to run the import! Set no limit
313 - set_time_limit(0);
314 -
315 -
316 - if ( !empty($GLOBALS['is_nginx']) ) {
100 + if ( $GLOBALS['is_nginx'] ) {
317 101 header( 'X-Accel-Buffering: no' );
318 102 header( 'Content-Encoding: none' );
319 103 }
320 104
321 - // Send output as soon as possible during long-running process
322 - if (function_exists('fastcgi_finish_request')) {
323 - fastcgi_finish_request();
324 - } elseif (function_exists('litespeed_finish_request')) {
325 - litespeed_finish_request();
326 - } else {
327 - wp_ob_end_flush_all();
328 - }
329 - }
105 + register_shutdown_function( [ $this, 'register_shutdown' ] );
330 106
331 - public function import() {
332 - if ( ! $this->dev_mode && ! wp_doing_ajax() ) {
333 - exit;
334 - }
107 + // Time to run the import!
108 + set_time_limit( 0 );
335 109
336 - // delete_option( 'templately_fsi_log' );
110 + flush();
111 + wp_ob_end_flush_all();
337 112
338 - $this->sse_message( [
339 - 'type' => 'start',
340 - 'action' => 'eventLog',
341 - 'results' => __METHOD__ . '::' . __LINE__,
342 - ] );
343 -
344 - register_shutdown_function( [ $this, 'register_shutdown' ] );
345 -
346 - $this->finishRequestHeaders();
347 -
348 113 try {
349 114 // TODO: Need to check if user is connected or not
350 115
351 116 $this->request_params = $this->get_session_data();
352 - $this->initialize_props();
353 - $this->add_revert_hooks();
354 - $progress = $this->request_params['progress'] ?? [];
355 117
356 - $_id = isset($this->request_params['id']) ? (int) $this->request_params['id'] : null;
118 + $_id = isset( $this->request_params['id'] ) ? (int) $this->request_params['id'] : null;
357 119
358 - if ($_id === null) {
359 - $this->throw(__('Invalid Pack ID.', 'templately'));
120 + if ( $_id === null ) {
121 + $this->throw( __( 'Invalid Pack ID.', 'templately' ) );
360 122 }
361 123
362 - if(empty($progress['download_zip'])){
363 - //clear previous revert backup
364 - $options = Utils::get_backup_options();
365 - foreach ($options as $key => $value) {
366 - delete_option("__templately_$key");
367 - }
124 + /**
125 + * Check Writing Permission
126 + */
127 + $this->check_writing_permission();
368 128
369 - /**
370 - * Check Writing Permission
371 - */
372 - $this->check_writing_permission();
129 + /**
130 + * Download the zip
131 + */
132 + $this->download_zip( $_id );
373 133
374 - /**
375 - * Download the zip
376 - */
377 - $this->download_zip( $_id );
378 -
379 - $progress['download_zip'] = true;
380 - $this->update_session_data( [
381 - 'progress' => $progress,
382 - ] );
383 - $this->sse_message( [
384 - 'type' => 'continue',
385 - 'action' => 'continue',
386 - 'info' => 'download_zip',
387 - 'results' => __METHOD__ . '::' . __LINE__,
388 - ] );
389 - exit;
390 - }
391 -
392 -
393 - if(empty($progress['download_dependencies'])){
394 - /**
395 - * Checking & Installing Plugin Dependencies
396 - */
397 - $this->install_dependencies();
398 -
399 - $progress['download_dependencies'] = true;
400 - $this->update_session_data( [
401 - 'progress' => $progress,
402 - ] );
403 - $this->sse_message( [
404 - 'type' => 'continue',
405 - 'action' => 'continue',
406 - 'results' => 'download_dependencies',
407 - ] );
408 - exit;
409 - }
410 -
411 -
412 134 /**
413 135 * Reading Manifest File
414 136 */
415 137 $this->read_manifest();
@@ -424,52 +146,43 @@
424 146 $this->throw( __( 'Please update the templately plugin.', 'templately' ) );
425 147 }
426 148
427 149 /**
150 + * Checking & Installing Plugin Dependencies
151 + */
152 + $this->install_dependencies();
153 +
154 + /**
428 155 * Should Revert Old Data
429 156 */
430 - // $this->revert();
157 + $this->revert();
431 158
432 159 /**
433 160 * Platform Based Templates Import
434 161 */
435 162 $this->start_content_import();
436 -
437 163 } catch ( Exception $e ) {
438 - $this->handle_import_status('failed', $e->getMessage());
439 - $this->sse_message([
164 + $this->sse_message( [
440 165 'action' => 'error',
441 166 'status' => 'error',
442 167 'type' => "error",
443 168 'title' => __("Oops!", "templately"),
444 169 'message' => $e->getMessage()
445 - ]);
170 + ] );
446 171 }
447 172
448 - // if($_GET['part'] === 'import'){
449 - // TODO: cleanup
450 - // $this->clear_session_data();
451 - // }
173 + // TODO: cleanup
174 + $this->clear_session_data();
452 175 }
453 176
454 - public function import_status(){
455 - $log = get_option( 'templately_fsi_log' );
456 -
457 - if(!empty($log) && is_array($log) && isset($_GET['lastLogIndex'])){
458 - $lastLogIndex = (int) $_GET['lastLogIndex'];
459 - $log = array_slice($log, $lastLogIndex);
460 - }
461 - wp_send_json( ['count' => $log ? count($log) : 0, 'log' => $log] );
462 - }
463 -
464 177 /**
465 178 * @throws Exception
466 179 */
467 - private function throw($message, $code = 0) {
468 - if ($this->dev_mode) {
469 - error_log(print_r($message, 1));
180 + private function throw( $message, $code = 0 ) {
181 + if ( $this->dev_mode ) {
182 + error_log( print_r( $message, 1 ) );
470 183 }
471 - throw new Exception($message);
184 + throw new Exception( $message );
472 185 }
473 186
474 187 /**
475 188 * @throws Exception
@@ -476,65 +189,43 @@
476 189 */
477 190 private function check_writing_permission() {
478 191 $upload_dir = wp_upload_dir();
479 192
480 - if (!is_writable($upload_dir['basedir'])) {
481 - $this->throw(__('Upload directory is not writable.', 'templately'));
193 + if ( ! is_writable( $upload_dir['basedir'] ) ) {
194 + $this->throw( __( 'Upload directory is not writable.', 'templately' ) );
482 195 }
483 196
484 - $this->tmp_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
197 + $this->tmp_dir = trailingslashit( $upload_dir['basedir'] ) . 'templately' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
485 198
486 - if (!is_dir($this->tmp_dir)) {
487 - wp_mkdir_p($this->tmp_dir);
199 + if ( ! is_dir( $this->tmp_dir ) ) {
200 + wp_mkdir_p( $this->tmp_dir );
488 201 }
489 202
490 - $this->sse_log('writing_permission_check', __('Permission Passed', 'templately'), 100);
203 + $this->sse_log( 'writing_permission_check', __( 'Permission Passed', 'templately' ), 100 );
491 204 }
492 205
493 - private function get_api_url($version, $end_point): string {
494 - return $this->dev_mode ? "https://app.templately.dev/api/$version/" . $end_point : "https://app.templately.com/api/$version/" . $end_point;
206 + private function get_api_url( $id ): string {
207 + return $this->dev_mode ? 'https://app.templately.dev/api/v1/import/pack/' . $id : 'https://app.templately.com/api/v1/import/pack/' . $id;
495 208 }
496 209
497 - private function info_get_api_url($id): string {
498 - return $this->dev_mode ? 'https://app.templately.dev/api/v1/import/info/pack/' . $id : 'https://app.templately.com/api/v1/import/info/pack/' . $id;
499 - }
500 -
501 210 /**
502 211 * @throws Exception
503 212 */
504 213 private function download_zip( $id ) {
505 - $this->sse_log( 'download', __( 'Downloading Template Pack', 'templately' ), 1 );
506 - $response = wp_remote_get( $this->get_api_url( "v2", "import/pack/$id" ), [
507 - 'timeout' => 30,
214 + // $this->sse_log( 'download', __( 'Downloading Template Pack', 'templately' ), 1 );
215 + $response = wp_remote_get( $this->get_api_url( $id ), [
508 216 'headers' => [
509 - 'Content-Type' => 'application/json',
510 - 'Authorization' => 'Bearer ' . $this->api_key,
511 - 'x-templately-ip' => Helper::get_ip(),
512 - 'x-templately-url' => home_url('/'),
513 - 'x-templately-version' => TEMPLATELY_VERSION,
217 + 'Authorization' => 'Bearer ' . $this->api_key,
218 + 'x-templately-ip' => Helper::get_ip(),
219 + 'x-templately-url' => home_url( '/' )
514 220 ]
515 - ]);
221 + ] );
516 222
517 - $response_code = wp_remote_retrieve_response_code($response);
518 - $content_type = wp_remote_retrieve_header($response, 'content-type');
519 - $this->download_key = wp_remote_retrieve_header($response, 'download-key');
520 -
521 - if (is_wp_error($response)) {
522 - $this->throw(__('Template pack download failed', 'templately') . $response->get_error_message());
523 - } else if ($response_code != 200) {
524 - if (strpos($content_type, 'application/json') !== false) {
525 - // Retrieve Data from Response Body.
526 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
527 -
528 - // If the response body is JSON and it contains an error, throw an exception with the error message
529 - if (isset($response_body['status']) && $response_body['status'] === 'error') {
530 - $this->throw($response_body['message']);
531 - }
532 - }
533 - $this->throw(__('Template pack download failed with response code: ', 'templately') . $response_code);
223 + if ( is_wp_error( $response ) ) {
224 + $this->throw( __( 'Template pack download failed', 'templately' ) . $response->get_error_message() );
534 225 }
535 226
536 - $this->sse_log('download', __('Template is getting ready', 'templately'), 57);
227 + $this->sse_log( 'download', __( 'Template is getting ready', 'templately' ), 57 );
537 228
538 229 $session_id = uniqid();
539 230 $this->dir_path = $this->tmp_dir . $session_id . DIRECTORY_SEPARATOR;
540 231 $this->filePath = $this->tmp_dir . "{$session_id}.zip";
@@ -539,20 +230,16 @@
539 230 $this->dir_path = $this->tmp_dir . $session_id . DIRECTORY_SEPARATOR;
540 231 $this->filePath = $this->tmp_dir . "{$session_id}.zip";
541 232 $this->session_id = $session_id;
542 233
543 - $this->update_session_data([
544 - 'session_id' => $this->session_id,
545 - 'dir_path' => $this->dir_path,
546 - 'download_key' => $this->download_key,
547 - ]);
234 + $this->update_session_data( [ 'session_id' => $this->session_id ] );
548 235
549 - if (file_put_contents($this->filePath, $response['body'])) { // phpcs:ignore
550 - $this->sse_log('download', __('Template is getting ready', 'templately'), 100);
236 + if ( file_put_contents( $this->filePath, $response['body'] ) ) { // phpcs:ignore
237 + $this->sse_log( 'download', __( 'Template is getting ready', 'templately' ), 100 );
551 238
552 239 $this->unzip();
553 240 } else {
554 - $this->throw(__('Downloading Failed. Please try again', 'templately'));
241 + $this->throw( __( 'Downloading Failed. Please try again', 'templately' ) );
555 242 }
556 243 }
557 244
558 245 /**
@@ -558,74 +245,34 @@
558 245 /**
559 246 * @throws Exception
560 247 */
561 248 protected function unzip() {
562 - if (!WP_Filesystem()) {
563 - $this->throw(__('WP_Filesystem cannot be initialized', 'templately'));
249 + if ( ! WP_Filesystem() ) {
250 + $this->throw( __( 'WP_Filesystem cannot be initialized', 'templately' ) );
564 251 }
565 252
566 - $unzip = unzip_file($this->filePath, $this->dir_path);
567 - if (is_wp_error($unzip)) {
568 - $unzip = $this->unzip_file($this->filePath, $this->dir_path);
569 - }
253 + $unzip = unzip_file( $this->filePath, $this->dir_path );
570 254
571 - if (is_wp_error($unzip)) {
572 - $error = $unzip->get_error_message();
573 - if (empty($error)) {
574 - // Generic error message
575 - Helper::log($unzip);
576 - $error_message = sprintf(__("It seems we're experiencing technical difficulties. Please try again or contact <a href='%s' target='_blank'>support</a>.", "templately"), 'https://wpdeveloper.com/support');
577 - $this->throw($error_message);
578 - } else {
579 - $this->throw($unzip->get_error_message());
580 - }
255 + if ( is_wp_error( $unzip ) ) {
256 + $this->throw( sprintf( __( 'Unzipping failed: %s', 'templately' ), $unzip->get_error_message() ) );
581 257 }
582 258
583 - if ($unzip) {
584 - unlink($this->filePath);
259 + if ( $unzip ) {
260 + unlink( $this->filePath );
585 261 }
586 262 }
587 263
588 264 /**
589 - * Unzip a specified ZIP file to a location on the Filesystem.
590 - *
591 - * @param string $file Full path and filename of ZIP archive.
592 - * @param string $to Full path on the filesystem to extract archive to.
593 - * @return true|WP_Error True on success, WP_Error on failure.
594 - */
595 - function unzip_file($file, $to) {
596 - try {
597 - $zip = new \ZipArchive;
598 -
599 - $res = $zip->open($file);
600 - if ($res === TRUE) {
601 - $zip->extractTo($to);
602 - $zip->close();
603 -
604 - return true;
605 - }
606 - } catch (\Throwable $th) {
607 - return new \WP_Error('exception_caught', $th->getMessage());
608 - }
609 -
610 - if (isset($zip)) {
611 - return new \WP_Error('zip_error_' . $zip->status, $zip->getStatusString());
612 - } else {
613 - return new \WP_Error('unknown_error', '');
614 - }
615 - }
616 -
617 - /**
618 265 * @throws Exception
619 266 */
620 267 private function read_manifest() {
621 - $manifest_content = file_get_contents($this->dir_path . DIRECTORY_SEPARATOR . 'manifest.json');
622 - if (empty($manifest_content)) {
623 - $this->throw(__('Cannot be imported, as the manifest file is corrupted', 'templately'));
268 + $manifest_content = file_get_contents( $this->dir_path . DIRECTORY_SEPARATOR . 'manifest.json' );
269 + if ( empty( $manifest_content ) ) {
270 + $this->throw( __( 'Cannot be imported, as the manifest file is corrupted', 'templately' ) );
624 271 }
625 272
626 - $this->manifest = json_decode($manifest_content, true);
627 - $this->removeLog('temp');
273 + $this->manifest = json_decode( $manifest_content, true );
274 + $this->removeLog( 'temp' );
628 275
629 276 // TODO: Read & Broadcast the LOG for waiting list
630 277 // $this->sse_log( 'plugin', 'Installing required plugins', '--', 'updateLog', 'processing' );
631 278 // // $this->sse_log( 'extra-content', 'Import Extra Contents (i.e: Forms)', '--', 'updateLog', 'processing' );
@@ -635,38 +282,31 @@
635 282 // $this->sse_log( 'finalize', 'Finalizing Your Imports', '--', 'updateLog', 'processing' );
636 283 }
637 284
638 285 private function skipped_plugin(): bool {
639 - return empty($this->request_params['plugins']) || !is_array($this->request_params['plugins']);
286 + return empty( $this->request_params['plugins'] ) || ! is_array( $this->request_params['plugins'] );
640 287 }
641 288
642 289 private function install_dependencies() {
643 - $progress = $this->request_params['progress'] ?? [];
644 -
645 - if ( empty($progress['theme_dependency']) && ! empty( $this->request_params['theme'] ) && is_array( $this->request_params['theme'] ) ) {
290 + if ( ! empty( $this->request_params['theme'] ) && is_array( $this->request_params['theme'] ) ) {
646 291 // activate theme
647 292 $theme = $this->request_params['theme'];
648 293
649 - // $this->before_install_hook();
294 + $this->before_install_hook();
650 295
651 296 if (isset($theme['stylesheet'])) {
652 297 // do_action('before_theme_activation', $theme); // Trigger action before theme activation
653 - $this->sse_log('theme', 'Installing and activating theme: ' . $theme['name'], 0);
654 - if (!get_option("__templately_stylesheet")) {
655 - $stylesheet = get_option('stylesheet');
656 - add_option("__templately_stylesheet", $stylesheet, '', 'no');
657 - }
298 + $this->sse_log( 'theme', 'Installing and activating theme: ' . $theme['name'], 0 );
299 + $plugin_status = Installer::get_instance()->install_and_activate_theme( $theme['stylesheet'] );
658 300
659 - $plugin_status = Installer::get_instance()->install_and_activate_theme($theme['stylesheet']);
660 -
661 301 if (!$plugin_status['success']) {
662 - $this->sse_message([
302 + $this->sse_message( [
663 303 'action' => 'updateLog',
664 304 'status' => 'error',
665 305 'message' => "Failed to activate theme: " . $theme['name'],
666 306 'type' => "theme",
667 307 'progress' => 0
668 - ]);
308 + ] );
669 309 $this->dependency_data['theme'] = [
670 310 'success' => false,
671 311 'name' => $theme['name'],
672 312 'slug' => $theme['stylesheet'],
@@ -671,21 +311,18 @@
671 311 'name' => $theme['name'],
672 312 'slug' => $theme['stylesheet'],
673 313 'message' => $plugin_status['message'] ?? ''
674 314 ];
675 - $this->update_session_data( [
676 - 'dependency_data' => $this->dependency_data,
677 - ] );
678 315 } else {
679 316 // do_action('after_theme_activation', $theme); // Trigger action after theme activation
680 317
681 - $this->sse_message([
318 + $this->sse_message( [
682 319 'action' => 'updateLog',
683 320 'status' => 'complete',
684 321 'message' => "Activated theme: " . $theme['name'],
685 322 'type' => "theme",
686 323 'progress' => 100
687 - ]);
324 + ] );
688 325 $this->dependency_data['theme'] = [
689 326 'success' => true,
690 327 'name' => $theme['name'],
691 328 'slug' => $theme['stylesheet'],
@@ -690,67 +327,40 @@
690 327 'name' => $theme['name'],
691 328 'slug' => $theme['stylesheet'],
692 329 'message' => $plugin_status['message'] ?? ''
693 330 ];
694 - $this->update_session_data( [
695 - 'dependency_data' => $this->dependency_data,
696 - ] );
697 -
698 - $progress['theme_dependency'] = true;
699 - $this->update_session_data( [
700 - 'progress' => $progress,
701 - ] );
702 331 }
703 -
704 - // If it's not the last item, send the SSE message and exit
705 - $this->sse_message( [
706 - 'type' => 'continue',
707 - 'action' => 'continue',
708 - 'results' => __METHOD__ . '::' . __LINE__,
709 - ] );
710 - exit;
711 332 }
712 333
713 - // $this->after_install_hook();
334 + $this->after_install_hook();
714 335 }
715 - else if(empty($progress['theme_dependency'])) {
336 + else {
716 337 $this->removeLog( 'theme' );
717 338 }
718 339 if ( ! empty( $this->request_params['plugins'] ) && is_array( $this->request_params['plugins'] ) ) {
719 340 // $this->sse_log( 'plugin', 'Installing Plugins', 1 );
720 - $total_plugin = count($this->request_params['plugins']);
341 + $total_plugin = count( $this->request_params['plugins'] );
721 342
722 - // $total_plugin_installed = $total_plugin;
723 - $_installed_plugins = $this->dependency_data['_installed_plugins'] ?? 0;
724 - $progress['plugin_dependency'] = $progress['plugin_dependency'] ?? [];
343 + $total_plugin_installed = $total_plugin;
344 + $_installed_plugins = 0;
725 345
726 - // $this->before_install_hook();
346 + $this->before_install_hook();
727 347
728 348 foreach ( $this->request_params['plugins'] as $dependency ) {
729 - if(in_array($dependency['plugin_original_slug'], $progress['plugin_dependency'])){
730 - continue;
731 - }
732 - $_dependency = $dependency;
733 349 $this->sse_log( 'plugin', 'Installing required plugins: ' . $dependency['name'], floor( ( 100 * $_installed_plugins / $total_plugin ) ) );
734 350
735 351 $dependency['slug'] = $dependency['plugin_original_slug'];
736 - $plugin_status = Installer::get_instance()->install($dependency);
352 + $plugin_status = Installer::get_instance()->install( $dependency );
737 353
738 - if (!$plugin_status['success']) {
739 - $this->sse_message([
354 + if ( ! $plugin_status['success'] ) {
355 + $this->sse_message( [
740 356 'position' => 'plugin',
741 357 'action' => 'updateLog',
742 358 'status' => 'error',
743 - 'message' => 'Installation Failed: ' . $dependency['name'] . ' (' . ($plugin_status['message'] ?? '') . ')',
359 + 'message' => 'Installation Failed: ' . $dependency['name'] . ' (' . ( $plugin_status['message'] ?? '' ) . ')',
744 360 'type' => "plugin_{$dependency['plugin_original_slug']}",
745 361 'progress' => 0
746 - ]);
747 -
748 - if (isset($dependency['mustHave']) && $dependency['mustHave']) {
749 - $this->removeLog('plugin');
750 - $this->throw('Installation Failed: ' . $dependency['name'] . ' (' . ($plugin_status['message'] ?? '') . ')');
751 - }
752 -
362 + ] );
753 363 $this->dependency_data['plugins']['failed'][] = [
754 364 'name' => $dependency['name'],
755 365 'slug' => $dependency['slug'],
756 366 'link' => $dependency['link'],
@@ -757,60 +367,35 @@
757 367 'message' => $plugin_status['message'] ?? ''
758 368 ];
759 369 } else {
760 370 $_installed_plugins++;
761 - // $total_plugin_installed--;
762 -
763 - $this->dependency_data['_installed_plugins'] = $_installed_plugins;
371 + $total_plugin_installed--;
764 372 }
765 -
766 - $this->update_session_data( [
767 - 'dependency_data' => $this->dependency_data,
768 - ] );
769 -
770 - $progress['plugin_dependency'][] = $dependency['slug'];
771 - $this->update_session_data( [
772 - 'progress' => $progress,
773 - ] );
774 -
775 - // If it's not the last item, send the SSE message and exit
776 - if( end($this->request_params['plugins']) !== $_dependency ) {
777 - $this->sse_message( [
778 - 'type' => 'continue',
779 - 'action' => 'continue',
780 - 'results' => __METHOD__ . '::' . __LINE__,
781 - ] );
782 - exit;
783 - }
784 373 }
785 374
786 - // $this->after_install_hook();
375 + $this->after_install_hook();
787 376
788 - $this->sse_message([
377 + $this->sse_message( [
789 378 'action' => 'updateLog',
790 379 'status' => 'complete',
791 380 'message' => "Installed required plugins ($_installed_plugins/$total_plugin)",
792 381 'type' => "plugin",
793 382 'progress' => 100
794 - ]);
383 + ] );
795 384 $this->dependency_data['plugins']['total'] = $total_plugin;
796 385 $this->dependency_data['plugins']['succeed'] = $_installed_plugins;
797 386 } else {
798 - $this->removeLog('plugin');
387 + $this->removeLog( 'plugin' );
799 388 }
800 389
801 -
802 - $this->update_session_data([
803 - 'dependency_data' => json_encode($this->dependency_data),
804 - ]);
805 390 // $this->sse_log( 'plugin', 'Skipped Installing Plugins', '--', 'updateLog', 'skipped' );
806 391 }
807 392
808 393 private function before_install_hook() {
809 - // remove_all_actions( 'wp_loaded' );
810 - // remove_all_actions( 'after_setup_theme' );
811 - // remove_all_actions( 'plugins_loaded' );
812 - // remove_all_actions( 'init' );
394 + remove_all_actions( 'wp_loaded' );
395 + remove_all_actions( 'after_setup_theme' );
396 + remove_all_actions( 'plugins_loaded' );
397 + remove_all_actions( 'init' );
813 398
814 399 // making sure so that no redirection happens during plugin installation and hooks triggered bellow.
815 400 add_filter('wp_redirect', '__return_false', 999);
816 401 }
@@ -815,12 +400,12 @@
815 400 add_filter('wp_redirect', '__return_false', 999);
816 401 }
817 402
818 403 private function after_install_hook() {
819 - // do_action( 'wp_loaded' );
820 - // do_action( 'after_setup_theme' );
821 - // do_action( 'plugins_loaded' );
822 - // do_action( 'init' );
404 + do_action( 'wp_loaded' );
405 + do_action( 'after_setup_theme' );
406 + do_action( 'plugins_loaded' );
407 + do_action( 'init' );
823 408 }
824 409
825 410 /**
826 411 * @throws Exception
@@ -828,55 +413,41 @@
828 413 private function start_content_import() {
829 414 add_filter('upload_mimes', array($this, 'allow_svg_upload'));
830 415 add_filter('elementor/files/allow_unfiltered_upload', '__return_true');
831 416
832 - $import = new Import($this);
417 + $import = new Import( $this );
833 418 $imported_data = $import->run();
834 419
835 - $import_status = $this->handle_import_status('success');
836 -
837 - update_option('templately_flush_rewrite_rules', true, false);
838 -
839 - $this->sse_message([
420 + $this->sse_message( [
840 421 'type' => 'complete',
841 422 'action' => 'complete',
842 - 'results' => $this->normalize_imported_data($imported_data)
843 - ]);
844 -
845 - update_user_meta(get_current_user_id(), 'templately_fsi_pack_id', $this->request_params["id"]);
846 - if(!empty($import_status['hasFeedback'])){
847 - update_user_meta(get_current_user_id(), 'templately_fsi_complete', 'done');
848 - }
849 - else{
850 - update_user_meta(get_current_user_id(), 'templately_fsi_complete', true);
851 - }
423 + 'results' => $this->normalize_imported_data( $imported_data )
424 + ] );
852 425 }
853 426
854 - private function normalize_imported_data($data) {
855 - $templates = !empty($data['templates']['succeed']) ? count($data['templates']['succeed']) : 0;
856 - $template_types = !empty($data['templates']['template_types']) ? $data['templates']['template_types'] : [];
427 + private function normalize_imported_data( $data ) {
428 + $templates = ! empty( $data['templates']['succeed'] ) ? count( $data['templates']['succeed'] ) : 0;
429 + $template_types = ! empty( $data['templates']['template_types'] ) ? $data['templates']['template_types'] : [];
857 430
858 431 $post_types = [];
859 432 $content_templates = [];
860 - if (!empty($data['content']) && is_array($data['content'])) {
861 - foreach ($data['content'] as $type => $type_data) {
862 - $content_templates[$type] = !empty($type_data['succeed']) ? count($type_data['succeed']) : 0;
433 + if ( ! empty( $data['content'] ) && is_array( $data['content'] ) ) {
434 + foreach ( $data['content'] as $type => $type_data ) {
435 + $content_templates[ $type ] = ! empty( $type_data['succeed'] ) ? count( $type_data['succeed'] ) : 0;
863 436 $post_types[] = $this->get_post_type_label_by_slug($type);
864 437 }
865 438 }
866 439
867 440 $contents = [];
868 - if (!empty($data['wp-content']) && is_array($data['wp-content'])) {
869 - foreach ($data['wp-content'] as $type => $type_data) {
870 - $contents[$type] = !empty($type_data['succeed']) ? count($type_data['succeed']) : 0;
871 - if (!in_array($type, ['wp_navigation', 'nav_menu_item'])) {
441 + if ( ! empty( $data['wp-content'] ) && is_array( $data['wp-content'] ) ) {
442 + foreach ( $data['wp-content'] as $type => $type_data ) {
443 + $contents[ $type ] = ! empty( $type_data['succeed'] ) ? count( $type_data['succeed'] ) : 0;
444 + if(!in_array($type, ['wp_navigation', 'nav_menu_item'])){
872 445 $post_types[] = $this->get_post_type_label_by_slug($type);
873 446 }
874 447 }
875 448 }
876 449
877 - Helper::log($data);
878 -
879 450 return [
880 451 'templates' => $templates,
881 452 'contents' => $content_templates,
882 453 'wp-content' => $contents,
@@ -896,17 +467,105 @@
896 467 // // TODO: Implement the Revert Process.
897 468 // }
898 469 }
899 470
900 - public function redirect_for_archives($link, $post_id) {
901 - $archive_settings = get_option('templately_post_archive');
902 - if (!empty($archive_settings) && intval($archive_settings['post_id']) === intval($post_id)) {
903 - $link = str_replace($post_id, $archive_settings['archive_id'], $link);
471 + public function redirect_for_archives( $link, $post_id ) {
472 + $archive_settings = get_option( 'templately_post_archive' );
473 + if ( ! empty( $archive_settings ) && intval( $archive_settings['post_id'] ) === intval( $post_id ) ) {
474 + $link = str_replace( $post_id, $archive_settings['archive_id'], $link );
904 475 }
905 476
906 477 return $link;
907 478 }
908 479
480 + public function enqueue_template_assets( $path, $url ) {
481 + $using_templately_builder = get_query_var( 'using_templately_template' );
482 + if ( $using_templately_builder && function_exists( 'templately' ) ) {
483 + $template_locations = [ 'header', 'footer', 'archive', 'single' ];
484 + foreach ( $template_locations as $location ) {
485 + $template = templately()->theme_builder::$conditions_manager->get_templates_by_location( $location );
486 + if ( empty( $template ) ) {
487 + return;
488 + }
489 + $template = array_pop( $template );
490 + if ( $template->platform == 'gutenberg' ) {
491 + $template = is_array( $template ) ? array_pop( $template ) : $template;
492 + if ( ! file_exists( $path . 'eb-style-' . $template->get_main_id() . '.min.css' ) ) {
493 + $st = EbStyleHandler::init();
494 + $post = get_post( $template->get_main_id() );
495 + $st->eb_write_css_from_content( $post, $post->ID, parse_blocks( $post->post_content ) );
496 + }
497 + wp_enqueue_style( 'templately-' . $location . '-' . $template->get_main_id(), $url . 'eb-style-' . $template->get_main_id() . '.min.css', [], substr( md5( microtime( true ) ), 0, 10 ) );
498 + }
499 + }
500 + }
501 + }
502 +
503 + public function upload_logo() {
504 + // Check if the upload file exists
505 + if (isset($_FILES['logo'])) {
506 + // Require the needed files if not already loaded
507 + if (!function_exists('wp_handle_upload')) {
508 + require_once(ABSPATH . 'wp-admin/includes/file.php');
509 + }
510 +
511 + // Manually upload the file
512 + $uploadedfile = $_FILES['logo'];
513 + $upload_overrides = array('test_form' => false);
514 + $movefile = wp_handle_upload($uploadedfile, $upload_overrides);
515 +
516 + if ($movefile && !isset($movefile['error'])) {
517 + // The file was uploaded successfully, now we need to resize it
518 + if (!function_exists('wp_get_image_editor')) {
519 + require_once(ABSPATH . 'wp-admin/includes/image.php');
520 + }
521 +
522 + $filetype = wp_check_filetype($movefile['file']);
523 +
524 + if ($filetype['ext'] == 'jpg' || $filetype['ext'] == 'jpeg' || $filetype['ext'] == 'png') {
525 + $image = wp_get_image_editor($movefile['file']);
526 + if (!is_wp_error($image)) {
527 + $size = $image->get_size();
528 + if ($size['width'] > 200 || $size['height'] > 80) {
529 + $image->resize(200, 80, false);
530 + $image->save($movefile['file']);
531 + }
532 + }
533 + }
534 +
535 + // Prepare an array of post data for the attachment
536 + $attachment = array(
537 + 'guid' => $movefile['url'],
538 + 'post_mime_type' => $movefile['type'],
539 + 'post_title' => preg_replace('/\.[^.]+$/', '', basename($movefile['file'])),
540 + 'post_content' => '',
541 + 'post_status' => 'inherit'
542 + );
543 +
544 + // Insert the attachment
545 + $attach_id = wp_insert_attachment($attachment, $movefile['file']);
546 +
547 + // Generate the metadata for the attachment and update the database record
548 + $attach_data = wp_generate_attachment_metadata($attach_id, $movefile['file']);
549 + wp_update_attachment_metadata($attach_id, $attach_data);
550 +
551 + // Return the URL of the uploaded file
552 + return json_encode( [
553 + 'id' => $attach_id,
554 + 'url' => $movefile['url']
555 + ]);
556 + } else {
557 + /**
558 + * Error generated by _wp_handle_upload()
559 + * @see _wp_handle_upload() in wp-admin/includes/file.php
560 + */
561 + // return $movefile['error'];
562 + }
563 + }
564 +
565 + return null;
566 + }
567 +
909 568 public function allow_svg_upload($mimes) {
910 569 // Allow SVG
911 570 $mimes['svg'] = 'image/svg+xml';
912 571 return $mimes;
@@ -911,13 +570,12 @@
911 570 $mimes['svg'] = 'image/svg+xml';
912 571 return $mimes;
913 572 }
914 573
915 - public function register_shutdown() {
916 - $status = connection_status();
574 + public function register_shutdown(){
917 575 $last_error = error_get_last();
918 - if ($status != CONNECTION_NORMAL && $last_error && $last_error['type'] === E_ERROR) {
919 - if ((defined('WP_DEBUG') && WP_DEBUG || defined('TEMPLATELY_EVENT_LOG') && TEMPLATELY_EVENT_LOG) && !empty($last_error['message'])) {
576 + if ($last_error && $last_error['type'] === E_ERROR) {
577 + if (defined('WP_DEBUG') && WP_DEBUG && !empty($last_error['message'])) {
920 578 $full_message = $last_error['message'];
921 579
922 580 // Split the message at the first newline to remove the stack trace
923 581 $message_parts = preg_split('/\n/', $full_message);
@@ -928,12 +586,10 @@
928 586 // Generic error message
929 587 $error_message = sprintf(__("It seems we're experiencing technical difficulties. Please try again or contact <a href='%s' target='_blank'>support</a>.", "templately"), 'https://wpdeveloper.com/support');
930 588 }
931 589
932 -
933 - $this->handle_import_status('failed', $error_message);
934 590 // Handle the error, e.g. log it or display a message to the user
935 - $this->sse_message([
591 + $this->sse_message( [
936 592 'action' => 'error',
937 593 'status' => 'error',
938 594 'type' => "error",
939 595 'title' => __("Oops!", "templately"),
@@ -939,65 +595,16 @@
939 595 'title' => __("Oops!", "templately"),
940 596 'message' => $error_message,
941 597 // 'position' => 'plugin',
942 598 // 'progress' => '--',
943 - ]);
599 + ] );
944 600 }
945 601
946 - $this->debug_log("Shutdown:.....");
947 - $this->debug_log("connection_status: " . $this->getConnectionStatusText());
948 - $this->debug_log($last_error);
602 + Helper::log( "Shutdown:....." );
603 + Helper::log( "connection_status: " . $this->getConnectionStatusText() );
604 + Helper::log( $last_error );
949 605 }
950 606
951 - public function handle_import_status($status, $description = '') {
952 - if ($this->is_import_status_handled) {
953 - Helper::log("Import status already handled: $status");
954 - return null;
955 - }
956 - $this->is_import_status_handled = $status;
957 -
958 - $download_key = $this->download_key;
959 -
960 - $headers = [
961 - 'Content-Type' => 'application/json',
962 - 'Authorization' => 'Bearer ' . $this->api_key,
963 - 'download_key' => $download_key,
964 - 'download-key' => $download_key,
965 - 'x-templately-ip' => Helper::get_ip(),
966 - 'x-templately-url' => home_url('/'),
967 - ];
968 -
969 - $args = [
970 - 'headers' => $headers,
971 - ];
972 -
973 -
974 - if ($status === 'success') {
975 - $url = $this->get_api_url("v1", 'import/success');
976 - $args['body'] = json_encode(['type' => 'pack']);
977 - $response = wp_remote_post($url, $args);
978 - } elseif ($status === 'failed') {
979 - $url = $this->get_api_url("v1", 'import/failed');
980 - $args['body'] = json_encode(['type' => 'pack', 'description' => $description ?: "Something Went wrong....."]);
981 - $response = wp_remote_post($url, $args);
982 - }
983 -
984 - Helper::log($response);
985 -
986 - if (is_wp_error($response)) {
987 - // Handle error
988 - Helper::log($response->get_error_message());
989 - } else {
990 - // Handle success
991 - $body = wp_remote_retrieve_body($response);
992 - $data = json_decode($body, true);
993 - // Do something with $body
994 - return $data;
995 - }
996 -
997 - return null;
998 - }
999 -
1000 607 protected function getConnectionStatusText() {
1001 608 $status = connection_status();
1002 609 switch ($status) {
1003 610 case CONNECTION_NORMAL:
@@ -1012,228 +619,22 @@
1012 619 }
1013 620
1014 621 protected function get_post_type_label_by_slug($slug) {
1015 622 $post_type_obj = get_post_type_object($slug);
1016 - if ($post_type_obj) {
623 + if($post_type_obj) {
1017 624 return $post_type_obj->label;
1018 625 }
1019 626 return null;
1020 627 }
1021 628
1022 - public function import_info() {
1023 -
1024 - $platform = isset($_GET['platform']) ? $_GET['platform'] : 'elementor';
1025 - $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
1026 -
1027 - $response = wp_remote_get($this->info_get_api_url($id), [
1028 - 'timeout' => 30,
1029 - 'headers' => [
1030 - 'Authorization' => 'Bearer ' . $this->api_key,
1031 - 'x-templately-ip' => Helper::get_ip(),
1032 - 'x-templately-url' => home_url('/'),
1033 - 'x-templately-version' => TEMPLATELY_VERSION,
1034 - ]
1035 - ]);
1036 -
1037 - if (is_wp_error($response)) {
1038 - wp_send_json_error($response->get_error_message());
1039 - return;
1040 - }
1041 - // If the response code is not 200, return the error message
1042 - if (wp_remote_retrieve_response_code($response) != 200) {
1043 - wp_send_json_error(json_decode(wp_remote_retrieve_body($response)));
1044 - return;
1045 - }
1046 - // If the response body is JSON and it contains an error, return the error message
1047 - // Retrieve Data from Response Body.
1048 - $body = wp_remote_retrieve_body($response);
1049 - $data = json_decode($body, true);
1050 -
1051 - if (isset($data['error'])) {
1052 - wp_send_json_error($data['error']);
1053 - return;
1054 - }
1055 -
1056 - if (isset($data['data']['manifest'])) {
1057 - $data['data']['manifest'] = json_decode($data['data']['manifest'], true);
1058 - }
1059 - if (isset($data['data']['settings'])) {
1060 - $data['data']['settings'] = json_decode($data['data']['settings'], true);
1061 - }
1062 -
1063 - // Return the response body
1064 - wp_send_json($data);
1065 - }
1066 -
1067 - public function update_imported_list($type, $id) {
1068 - $imported_list = get_option('templately_fsi_imported_list', []);
1069 - $imported_list[$type][] = $id;
1070 - update_option('templately_fsi_imported_list', $imported_list);
1071 - }
1072 -
1073 - /**
1074 - *
1075 - *
1076 - * @return void
1077 - */
1078 - protected function add_revert_hooks() {
1079 - add_action('wp_insert_post', function ($post_id) {
1080 - $this->update_imported_list('posts', $post_id);
1081 - });
1082 - add_action('add_attachment', function ($post_id) {
1083 - $this->update_imported_list('attachment', $post_id);
1084 - });
1085 - add_action('created_term', function ($term_id, $tt_id, $taxonomy, $args) {
1086 - $this->update_imported_list('term', [$term_id, $taxonomy]);
1087 - }, 10, 4);
1088 - add_action('registered_taxonomy', function ($taxonomy, $object_type, $taxonomy_object) {
1089 - $this->update_imported_list('taxonomy', $taxonomy);
1090 - }, 10, 3);
1091 - add_action('fluentform/form_imported', function ($formId){
1092 - $this->update_imported_list('fluentform', $formId);
1093 - }, 10, 1);
1094 - }
1095 -
1096 - public static function has_revert(){
1097 - $options = Utils::get_backup_options();
1098 - $imported_list = get_option('templately_fsi_imported_list', []);
1099 - if(!empty($options) || !empty($imported_list)){
1100 - return true;
1101 - }
1102 - return false;
1103 - }
1104 -
1105 - public function import_revert() {
1106 -
1107 - // // Get the nonce value from the request (usually from $_POST or $_GET)
1108 - // $received_nonce = isset($_REQUEST['_wpnonce']) ? $_REQUEST['_wpnonce'] : '';
1109 -
1110 - // // Verify the nonce using wp_verify_nonce()
1111 - // $verified = wp_verify_nonce($received_nonce, 'templately_pack_import_revert_nonce');
1112 -
1113 - // if (!$verified) {
1114 - // wp_send_json_error("Nonce not verified.");
1115 - // }
1116 -
1117 - $option_active = null;
1118 - $options_deleted = false;
1119 - $imported_list_deleted = false;
1120 - $options = Utils::get_backup_options();
1121 - $status_args = [ 'post_type' => 'templately_library' ];
1122 - $all_post_url = admin_url(add_query_arg( $status_args, 'edit.php' ));
1123 - // wp_send_json_success([$options]);
1124 -
1125 - if(class_exists('Elementor\Plugin')){
1126 - $kits_manager = Plugin::$instance->kits_manager;
1127 - $option_active = $kits_manager::OPTION_ACTIVE;
1128 - $kit = $kits_manager->get_active_kit();
1129 -
1130 - if ( ! $kit->get_id() ) {
1131 - $kit = $kits_manager->create_default();
1132 - update_option( $kits_manager::OPTION_ACTIVE, $kit );
1133 - }
1134 - }
1135 -
1136 -
1137 - if (!empty($options) && is_array($options)) {
1138 - foreach ($options as $key => $value) {
1139 - if ('stylesheet' === $key) {
1140 - if (get_option('stylesheet') !== $value) {
1141 - switch_theme($value);
1142 - }
1143 - } else if($option_active === $key && class_exists('Elementor\Plugin')) {
1144 - $kits_manager->revert( (int) $kits_manager->get_active_id(), (int) $value, 0 );
1145 - $kit = $kits_manager->get_active_kit();
1146 - $settings = $kit->get_data('settings');
1147 - if ( isset( $settings['site_logo'] ) ) {
1148 - set_theme_mod( 'custom_logo', $settings['site_logo']['id'] );
1149 - }
1150 - } else {
1151 - update_option($key, $value);
629 + public function filter_content( $content ) {
630 + if(is_singular()){
631 + global $post;
632 + if(!empty($post) && $post->post_type === 'templately_library'){
633 + if(in_array(get_post_meta($post->ID, '_templately_template_type', true), ['header', 'footer'])){
634 + return '';
1152 635 }
1153 - delete_option("__templately_$key");
1154 - $options_deleted = true;
1155 636 }
1156 637 }
1157 -
1158 - $imported_list = get_option('templately_fsi_imported_list', []);
1159 - if (!empty($imported_list) && is_array($imported_list)) {
1160 - $_GET['force_delete_kit'] = 1; // Fallback GET Ready!
1161 - foreach ($imported_list as $type => $list) {
1162 - if (empty($list) || !is_array($list)) {
1163 - continue;
1164 - }
1165 - // Loop through each item ID and delete it
1166 - foreach ($list as $key => $item_id) {
1167 - switch ($type) {
1168 - case 'posts':
1169 - // making sure default kit don't get deleted.
1170 - if($option_active && isset($options[$option_active]) && $options[$option_active] == $item_id){
1171 - break;
1172 - }
1173 - wp_delete_post($item_id, true); // Set true for permanent deletion
1174 - break;
1175 - case 'attachment':
1176 - wp_delete_attachment($item_id, true); // Set true for permanent deletion
1177 - break;
1178 - case 'term':
1179 - list($term_id, $taxonomy) = $item_id;
1180 - wp_delete_term($term_id, $taxonomy); // Use corresponding taxonomy
1181 - break;
1182 - case 'taxonomy':
1183 - // Taxonomies cannot be directly deleted. Consider de-registering it.
1184 - break;
1185 - case 'fluentform':
1186 - if(class_exists('\FluentForm\App\Models\Form')){
1187 - \FluentForm\App\Models\Form::remove($item_id);
1188 - }
1189 - break;
1190 - }
1191 - }
1192 - }
1193 -
1194 - $imported_list_deleted = true;
1195 - delete_option('templately_fsi_imported_list');
1196 - }
1197 -
1198 -
1199 - if($options_deleted || $imported_list_deleted){
1200 - sleep(5);
1201 - wp_send_json_success([ 'options' => $options_deleted, 'imported_list' => $imported_list_deleted, 'site_url' => home_url(), 'redirect' => $all_post_url ]);
1202 - }
1203 -
1204 - wp_send_json_error([ 'options' => $options_deleted, 'imported_list' => $imported_list_deleted, 'site_url' => home_url() ]);
638 + return $content;
1205 639 }
1206 -
1207 - /**
1208 - * Adds "Import" button on module list page
1209 - */
1210 - public function add_revert_button() {
1211 - $screen = get_current_screen();
1212 - // Not our post type, exit earlier
1213 - // You can remove this if condition if you don't have any specific post type to restrict to.
1214 - if ('templately_library' != $screen->post_type) {
1215 - return;
1216 - }
1217 -
1218 - // Generate a nonce with a unique action name for security
1219 - $revert_nonce = wp_create_nonce('templately_pack_import_revert_nonce');
1220 -
1221 - // Build the URL with the nonce
1222 - $revert_url = add_query_arg('action', 'templately_pack_import_revert', admin_url('admin-ajax.php'));
1223 - $revert_url = add_query_arg('_wpnonce', $revert_nonce, $revert_url);
1224 - ?>
1225 -
1226 - <div class="templately-fsi-revert-wrapper clearfix" style="clear: both; background: #fff; padding: 20px; display: none;">
1227 - <div class="templately-fsi-revert-notice__content">
1228 - <h3>Revert to previous website</h3>
1229 -
1230 - <p>This usually takes a few moments. Please don’t close the window until the process in finished.</p>
1231 -
1232 - <div class="templately-fsi-revert-notice__actions">
1233 - <a href="<?php echo $revert_url;?>" class="button"><span>Revert Now</span></a>
1234 - </div>
1235 - </div>
1236 - </div>
1237 - <?php
1238 - }
1239 -}
640 +}