PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.5.1
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.5.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
templately / includes / Core / Importer / Utils / GutenbergHelper.php

GutenbergHelper.php in Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! 3.5.1, at includes/Core/Importer/Utils/GutenbergHelper.php

438 lines 13.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Templately\Core\Importer\Utils;
4
5 use Templately\Core\Importer\WPImport;
6 use Templately\Utils\Helper;
7
8 class GutenbergHelper extends ImportHelper {
9 const IMAGE_URL_PATTERN = '/(https?:\/\/[^\s<>"\']+\.(jpg|jpeg|gif|png|svg|webp|ico|tiff|tif)(?:\?[^\s<>"\']*)?)/i';
10
11 private $template_settings = [];
12 private $forms = [];
13 /**
14 * @var WPImport
15 */
16 private $wp_importer;
17
18 public $shouldLog = true; // This is the class property to check
19
20 protected $content;
21
22 protected $post_id;
23
24 protected static $attachment_ids = [];
25
26
27 /**
28 * @param $template_json
29 * @param $template_settings
30 * @param $extra_content
31 *
32 * @return GutenbergHelper
33 */
34 public function prepare( $template_json, $template_settings, $extra_content = [], $request_params = [] ) {
35 $this->template_settings = $template_settings;
36 $this->post_id = $this->map_post_ids[ $template_settings['post_id'] ];
37 $this->wp_importer = new WPImport( null, [
38 'session_id' => $this->session_id,
39 'fetch_attachments' => true,
40 ] );
41
42 $parsed_blocks = parse_blocks( $template_json['content'] );
43 if ( ! empty( $extra_content ) ) {
44 $this->prepare_form_data( $extra_content, $template_settings );
45 }
46 if ( isset($this->template_settings['__attachments']) ) {
47 $this->process_images();
48 // Make sure we do the longest urls first, in case one is a substring of another.
49 }
50 if(!empty($this->wp_importer->url_remap)){
51 uksort( $this->wp_importer->url_remap, function ( $a, $b ) {
52 // Return the difference in length between two strings.
53 return strlen( $b ) - strlen( $a );
54 } );
55 }
56 if(!empty($template_settings["page_settings"]["fluent_cart_store_settings"])){
57 $this->replace_fluent_cart_store_settings($template_settings["page_settings"]["fluent_cart_store_settings"]);
58 }
59 $this->replace( $parsed_blocks, $request_params );
60 $this->content = wp_slash( serialize_blocks( $parsed_blocks ) );
61
62 return $this;
63 }
64
65 public function update() {
66 $this->sse_log('update', 'Updating prepared data, just a moment...', 1, 'eventLog');
67 wp_update_post( [
68 'ID' => $this->post_id,
69 'post_content' => $this->content
70 ] );
71 }
72
73 private function prepare_form_data( $extra_content, $template_settings ) {
74 foreach ( $extra_content as $type => $content ) {
75 foreach ( $content as $block_id => $value ) {
76 foreach ( $template_settings['data']['form'][ $type ] as $setting ) {
77 if ( isset( $setting['id'] ) && $setting['id'] === $block_id ) {
78 $this->forms[ $block_id ] = [
79 'value' => $value,
80 'attr' => $setting['identifier']
81 ];
82 }
83 }
84
85 }
86 }
87 }
88
89 private function replace( &$blocks, $request_params = [] ) {
90 foreach ( $blocks as &$block ) {
91 $this->sse_log('prepare', 'Preparing output for finalize, just a moment...', 1, 'eventLog');
92 if ( $block['blockName'] === 'core/navigation' ) {
93 if ( ! empty( $block['attrs']['ref'] ) && array_key_exists( $block['attrs']['ref'], $this->map_post_ids ) ) {
94 $block['attrs']['ref'] = $this->map_post_ids[ $block['attrs']['ref'] ];
95 $this->replace_archive_id( $block['attrs']['ref'] );
96 }
97 }
98 if ( isset( $block['attrs']['blockId'] ) && array_key_exists( $block['attrs']['blockId'], $this->forms ) ) {
99 $blockId = $block['attrs']['blockId'];
100 $form = $this->forms[$blockId];
101 $attr = $form['attr'];
102 $value = (string) $form['value'];
103
104 $block['attrs'][$attr] = $value;
105 }
106
107 if ( ! empty( $block['attrs']['queryData'] ) ) {
108 $this->replace_query_data( $block );
109 }
110
111 if ( isset($this->template_settings['__attachments']) ) {
112 $block = $this->replace_attachment_url( $block );
113 }
114
115 if ( ! empty( $block['innerBlocks'] ) ) {
116 $this->replace( $block['innerBlocks'], $request_params );
117 }
118 else if(!empty($request_params['logo']['id']) && isset($request_params['logo_size']) && $request_params['logo_size'] && $block['blockName'] === "essential-blocks/advanced-image" && $block["attrs"]["imgSource"] === "site-logo"){
119 $block["attrs"]["widthRange"] = $request_params['logo_size'];
120 unset($block["attrs"]["widthUnit"]);
121 if (isset($block['attrs']['blockMeta']['desktop']) && is_string($block['attrs']['blockMeta']['desktop'])) {
122 $meta = $block['attrs']['blockMeta']['desktop'];
123 $regex = '/\.image-wrapper\s*{\s*width:\s*(\d+)px;/';
124
125 if (preg_match($regex, $meta, $matches)) {
126 $replaced = preg_replace($regex, '.image-wrapper { width:' . $request_params['logo_size'] . 'px;', $meta);
127
128 if ($replaced) {
129 $block['attrs']['blockMeta']['desktop'] = $replaced;
130 }
131 }
132 }
133
134 $this->sse_log('prepare', 'Updated Site Logo', 1, 'eventLog');
135 }
136 }
137 }
138
139 private function replace_fluent_cart_store_settings($settings) {
140 $map_post_ids = $this->map_post_ids;
141 $saved_options = $settings;
142 $mapped_keys = [
143 'checkout_page_id',
144 'custom_payment_page_id',
145 'registration_page_id',
146 'login_page_id',
147 'cart_page_id',
148 'receipt_page_id',
149 'shop_page_id',
150 'customer_profile_page_id',
151 ];
152
153 foreach ($mapped_keys as $key) {
154 $old_id = $saved_options[$key] ?? null;
155 if (!empty($old_id) && isset($map_post_ids[$old_id])) {
156 $saved_options[$key] = $map_post_ids[$old_id];
157 }
158 else if(isset($saved_options[$key])){
159 $saved_options[$key] = 0;
160 }
161 }
162
163 update_option('fluent_cart_store_settings', $saved_options);
164 }
165
166 private function replace_archive_id( $menu_id ) {
167 if ( ! empty( $this->imported_data['archive_settings'] ) ) {
168 $post = get_post( $menu_id );
169 $blocks = parse_blocks( $post->post_content );
170 $changed = false;
171 foreach ( $blocks as &$block ) {
172 $this->sse_log('query', 'Finalizing archive settings, just a moment...', 1, 'eventLog');
173
174 if (isset($block['attrs']['id'])) {
175 $blockId = $block['attrs']['id'];
176 $archiveSettings = $this->imported_data['archive_settings'];
177
178 $archiveIds = $archiveSettings[$blockId] ?? false;
179
180 if ($archiveIds) {
181 $block['attrs']['id'] = $archiveIds['page_id'];
182 $block['attrs']['url'] = get_the_permalink($archiveIds['page_id']);
183 $changed = true;
184 }
185 }
186 }
187 if ( $changed ) {
188 wp_update_post( [
189 'ID' => $menu_id,
190 'post_content' => wp_slash( serialize_blocks( $blocks ) )
191 ] );
192 }
193 }
194 }
195
196 /**
197 * @param $block
198 *
199 * @return void
200 */
201 private function replace_query_data( &$block ) {
202 if ( ! empty( $block['attrs']['queryData']['taxonomies'] ) ) {
203 foreach ( $block['attrs']['queryData']['taxonomies'] as &$tax ) {
204 $this->sse_log('query', 'Finalizing query data, just a moment...', 1, 'eventLog');
205 $tax['value'] = json_decode( $tax['value'], true );
206 if ( ! empty( $tax['value'] ) ) {
207 foreach ( $tax['value'] as &$val ) {
208 if ( array_key_exists( $val['value'], $this->map_term_ids ) ) {
209 $val['value'] = $this->map_term_ids[ $val['value'] ];
210 }
211 }
212 }
213 $tax['value'] = json_encode( $tax['value'] );
214 }
215 }
216 $this->replace_raw_taxonomies($block);
217 if(!empty( $block['attrs']['queryData']['author'])){
218 $user = wp_get_current_user();
219 $block['attrs']['queryData']['author'] = json_encode([['label' => $user->display_name, 'value' => $user->ID]]);
220 }
221 }
222
223 /**
224 * @param $block
225 *
226 * @return void
227 */
228 private function replace_raw_taxonomies( &$block ) {
229 $types = ['category', 'tag'];
230 foreach ( $types as $type){
231 if(!empty($block['attrs']['queryData'][$type])){
232 $block['attrs']['queryData'][$type] = json_decode($block['attrs']['queryData'][$type], true);
233 foreach ($block['attrs']['queryData'][$type] as &$term){
234 $this->sse_log('prepare', 'Finalizing taxonomies, just a moment...', 1, 'eventLog');
235 if ( isset($term['value']) && array_key_exists( $term['value'], $this->map_term_ids ) ) {
236 $term['value'] = $this->map_term_ids[ $term['value'] ];
237 }
238 }
239 $block['attrs']['queryData'][$type] = json_encode($block['attrs']['queryData'][$type]);
240 }
241 }
242 }
243
244 public function replace_attachment_url($attrs) {
245 if ( !empty($attrs['blockName'] ) ) {
246 $attrs = $this->replace_attachment_ids($attrs);
247 }
248
249 if (is_string($attrs)) {
250 foreach ($this->wp_importer->url_remap as $old_url => $new_url) {
251 if (strpos($attrs, $old_url) !== false) {
252 $attrs = str_replace($old_url, $new_url, $attrs);
253 }
254 }
255 }
256 else if (is_array($attrs)) {
257 foreach ($attrs as $key => $attr) {
258 $attrs[$key] = $this->replace_attachment_url($attr);
259 }
260 }
261
262 return $attrs;
263 }
264
265 protected function replace_attachment_ids($attrs){
266 switch ($attrs['blockName']) {
267 case 'essential-blocks/slider':
268 $attrs = $this->processImages($attrs, 'images', 'imageId', 'url');
269 break;
270 case 'essential-blocks/advanced-image':
271 $attrs = $this->processSingleImage($attrs, 'image');
272 break;
273 case 'essential-blocks/parallax-slider':
274 $attrs = $this->processImages($attrs, 'sliderData', 'id', 'src');
275 break;
276 case 'essential-blocks/image-gallery':
277 $attrs = $this->processImages($attrs, 'images', 'id', 'url');
278 $attrs = $this->processImages($attrs, 'sources', 'id', 'url');
279 break;
280 case 'core/image':
281 $attrs = $this->processCoreImage($attrs, 'id');
282 break;
283 case 'core/media-text':
284 $attrs = $this->processCoreImage($attrs, 'mediaId');
285 break;
286 case 'core/cover':
287 $attrs = $this->processSingleImage($attrs, 'url');
288 break;
289 }
290 return $attrs;
291 }
292
293 private function processImages($attrs, $imageKey, $idKey, $urlKey) {
294 if (!empty($attrs['attrs'][$imageKey])) {
295 foreach ($attrs['attrs'][$imageKey] as $key => &$image) {
296 $imageUrl = $image[$urlKey];
297 if (!empty(self::$attachment_ids[$imageUrl])) {
298 $oldId = $image[$idKey];
299 $newId = (int) self::$attachment_ids[$imageUrl];
300 $image[$idKey] = $newId;
301
302 // Update innerHTML and innerContent for 'essential-blocks/slider'
303 if ($attrs['blockName'] === 'essential-blocks/slider') {
304 $attrs = $this->updateInnerHTMLAndContent($attrs, "imageId&quot;:$oldId,&quot;", "imageId&quot;:$newId,&quot;");
305 }
306 }
307 }
308 }
309 return $attrs;
310 }
311
312 private function processSingleImage($attrs, $imageKey) {
313 if (!empty(self::$attachment_ids[$attrs['attrs'][$imageKey]['url']])) {
314 $attrs['attrs'][$imageKey]['id'] = (int) self::$attachment_ids[$attrs['attrs'][$imageKey]['url']];
315 }
316 return $attrs;
317 }
318
319 private function processCoreImage($attrs, $idKey) {
320 preg_match(self::IMAGE_URL_PATTERN, $attrs['innerHTML'], $matches);
321 if (!empty($matches[0])) {
322 $url = $matches[0];
323 if (!empty(self::$attachment_ids[$url])) {
324 $oldId = $attrs['attrs'][$idKey];
325 $newId = (int) self::$attachment_ids[$url];
326 $attrs['attrs'][$idKey] = $newId;
327
328 // Replace old ID with new ID in innerHTML and innerContent
329 $attrs = $this->updateInnerHTMLAndContent($attrs, "wp-image-$oldId", "wp-image-$newId");
330 }
331 }
332 return $attrs;
333 }
334
335 private function updateInnerHTMLAndContent($attrs, $oldValue, $newValue) {
336 $attrs['innerHTML'] = str_replace($oldValue, $newValue, $attrs['innerHTML']);
337 if (is_array($attrs['innerContent'])) {
338 foreach ($attrs['innerContent'] as $i => $content) {
339 $attrs['innerContent'][$i] = str_replace($oldValue, $newValue, $content);
340 }
341 } else {
342 $attrs['innerContent'] = str_replace($oldValue, $newValue, $attrs['innerContent']);
343 }
344 return $attrs;
345 }
346
347 /**
348 * Parses the images from the post content, processes them as attachments, and updates the post with the new attachment URL.
349 * @todo: Parse using parse_blocks instead of regex
350 *
351 * @param int $post_id The ID of the post.
352 * @param string $post_content The content of the post.
353 */
354 public function parse_images($post_content) {
355 // Find all image URLs in the post content
356 preg_match_all(self::IMAGE_URL_PATTERN, $post_content, $matches);
357
358 $urls = $matches[0];
359 $organizedUrls = [];
360
361 foreach ($urls as $url) {
362 // Remove the size suffix from the URL
363 $base_url = preg_replace('/-\d+x\d+(?=\.[a-zA-Z]+$)/', '', $url);
364
365 // Check if the URL already exists in the array
366 if (!isset($organizedUrls[$base_url]) || !in_array($url, $organizedUrls[$base_url])) {
367 // Add the URL to the array under the base URL key
368 $organizedUrls[$base_url][] = $url;
369 }
370 }
371
372 return $organizedUrls;
373 }
374
375 public function process_images(){
376 // Time to run the import!
377 set_time_limit( 0 );
378
379 $organizedUrls = $this->template_settings['__attachments'];
380 // For each base image URL...
381 foreach ($organizedUrls as $base_url => $sizes) {
382 // Prepare the post data for the attachment
383 $post_data = $this->prepare_post_data($this->post_id, $base_url);
384
385 // If prepare_post_data returned null, skip this iteration
386 if ($post_data === null) {
387 continue;
388 }
389
390 foreach ($sizes as $key => $size) {
391 if ($base_url == $size) {
392 unset($sizes[$key]);
393 continue;
394 }
395
396 // $size url string; get width height from the image url
397 preg_match('/-(\d+)x(\d+)\.[a-zA-Z]+$/', $size, $matches);
398 if (isset($matches[1]) && isset($matches[2])) {
399 $sizes[$key] = [
400 'file' => basename($size),
401 'width' => $matches[1],
402 'height' => $matches[2]
403 ];
404 } else {
405 unset($sizes[$key]);
406 }
407 }
408
409 // Check if the attachment already exists
410 $attachment_id = $this->wp_importer->process_attachment($post_data, $base_url, $sizes);
411 // If there was an error, handle it here
412 if (is_wp_error($attachment_id)) {
413 $this->sse_log('error', $attachment_id->get_error_message(), -1, 'eventLog');
414 } else {
415 $this->sse_log('success', "Imported attachment: $attachment_id", -1, 'eventLog');
416 self::$attachment_ids[$base_url] = $attachment_id;
417 }
418 }
419 }
420
421 private function prepare_post_data($post_id, $image_url) {
422 return Utils::prepare_post_data($image_url, $post_id, [$this, 'sse_log']);
423 }
424
425 public function sse_log( $type, $message, $progress = 1, $action = 'updateLog', $status = null ) {
426 if ($this->shouldLog) {
427 parent::sse_log($type, $message, $progress, $action, $status);
428 }
429 else{
430 Helper::log(func_get_args());
431 }
432 }
433
434 public function get_content(){
435 return $this->content;
436 }
437
438 }