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

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

376 lines 11.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 = '/(http(s?):)([\/|.|\w|\s|-])*\.(?:jpg|gif|png)/';
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 = [] ) {
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, ['fetch_attachments' => true] );
38
39 $parsed_blocks = parse_blocks( $template_json['content'] );
40 if ( ! empty( $extra_content ) ) {
41 $this->prepare_form_data( $extra_content, $template_settings );
42 }
43 if ( isset($this->template_settings['__attachments']) ) {
44 $this->process_images();
45 // Make sure we do the longest urls first, in case one is a substring of another.
46 uksort( $this->wp_importer->url_remap, function ( $a, $b ) {
47 // Return the difference in length between two strings.
48 return strlen( $b ) - strlen( $a );
49 } );
50 }
51 $this->replace( $parsed_blocks );
52 $this->content = wp_slash( serialize_blocks( $parsed_blocks ) );
53
54 return $this;
55 }
56
57 public function update() {
58 $this->sse_log('update', 'Updating prepared data, just a moment...', 1, 'eventLog');
59 wp_update_post( [
60 'ID' => $this->post_id,
61 'post_content' => $this->content
62 ] );
63 }
64
65 private function prepare_form_data( $extra_content, $template_settings ) {
66 foreach ( $extra_content as $type => $content ) {
67 foreach ( $content as $block_id => $value ) {
68 foreach ( $template_settings['data']['form'][ $type ] as $setting ) {
69 if ( isset( $setting['id'] ) && $setting['id'] === $block_id ) {
70 $this->forms[ $block_id ] = [
71 'value' => $value,
72 'attr' => $setting['identifier']
73 ];
74 }
75 }
76
77 }
78 }
79 }
80
81 private function replace( &$blocks ) {
82 foreach ( $blocks as &$block ) {
83 $this->sse_log('prepare', 'Preparing output for finalize, just a moment...', 1, 'eventLog');
84 if ( $block['blockName'] === 'core/navigation' ) {
85 if ( ! empty( $block['attrs']['ref'] ) && array_key_exists( $block['attrs']['ref'], $this->map_post_ids ) ) {
86 $block['attrs']['ref'] = $this->map_post_ids[ $block['attrs']['ref'] ];
87 $this->replace_archive_id( $block['attrs']['ref'] );
88 }
89 }
90 if ( isset( $block['blockId'] ) && array_key_exists( $block['blockId'], $this->forms ) ) {
91 $block['attrs'][ $this->forms[ $block['blockId'] ]['attr'] ] = $this->forms[ $block['blockId'] ]['value'];
92 }
93
94 if ( ! empty( $block['attrs']['queryData'] ) ) {
95 $this->replace_query_data( $block );
96 }
97
98 if ( isset($this->template_settings['__attachments']) ) {
99 $block = $this->replace_attachment_url( $block );
100 }
101
102 if ( ! empty( $block['innerBlocks'] ) ) {
103 $this->replace( $block['innerBlocks'] );
104 }
105 }
106 }
107
108 private function replace_archive_id( $menu_id ) {
109 if ( ! empty( $this->imported_data['archive_settings'] ) ) {
110 $post = get_post( $menu_id );
111 $blocks = parse_blocks( $post->post_content );
112 $changed = false;
113 foreach ( $blocks as &$block ) {
114 $this->sse_log('query', 'Finalizing archive settings, just a moment...', 1, 'eventLog');
115
116 if ( isset( $block['attrs']['id'] ) && $block['attrs']['id'] === $this->imported_data['archive_settings']['archive_id'] ) {
117 $changed = true;
118 $block['attrs']['id'] = $this->imported_data['archive_settings']['page_id'];
119 $block['attrs']['url'] = get_the_permalink( $this->imported_data['archive_settings']['page_id'] );
120 }
121 }
122 if ( $changed ) {
123 wp_update_post( [
124 'ID' => $menu_id,
125 'post_content' => wp_slash( serialize_blocks( $blocks ) )
126 ] );
127 }
128 }
129 }
130
131 /**
132 * @param $block
133 *
134 * @return void
135 */
136 private function replace_query_data( &$block ) {
137 if ( ! empty( $block['attrs']['queryData']['taxonomies'] ) ) {
138 foreach ( $block['attrs']['queryData']['taxonomies'] as &$tax ) {
139 $this->sse_log('query', 'Finalizing query data, just a moment...', 1, 'eventLog');
140 $tax['value'] = json_decode( $tax['value'], true );
141 if ( ! empty( $tax['value'] ) ) {
142 foreach ( $tax['value'] as &$val ) {
143 if ( array_key_exists( $val['value'], $this->map_term_ids ) ) {
144 $val['value'] = $this->map_term_ids[ $val['value'] ];
145 }
146 }
147 }
148 $tax['value'] = json_encode( $tax['value'] );
149 }
150 }
151 $this->replace_raw_taxonomies($block);
152 if(!empty( $block['attrs']['queryData']['author'])){
153 $user = wp_get_current_user();
154 $block['attrs']['queryData']['author'] = json_encode([['label' => $user->display_name, 'value' => $user->ID]]);
155 }
156 }
157
158 /**
159 * @param $block
160 *
161 * @return void
162 */
163 private function replace_raw_taxonomies( &$block ) {
164 $types = ['category', 'tag'];
165 foreach ( $types as $type){
166 if(!empty($block['attrs']['queryData'][$type])){
167 $block['attrs']['queryData'][$type] = json_decode($block['attrs']['queryData'][$type], true);
168 foreach ($block['attrs']['queryData'][$type] as &$term){
169 $this->sse_log('prepare', 'Finalizing taxonomies, just a moment...', 1, 'eventLog');
170 if ( isset($term['value']) && array_key_exists( $term['value'], $this->map_term_ids ) ) {
171 $term['value'] = $this->map_term_ids[ $term['value'] ];
172 }
173 }
174 $block['attrs']['queryData'][$type] = json_encode($block['attrs']['queryData'][$type]);
175 }
176 }
177 }
178
179 public function replace_attachment_url($attrs) {
180 if ( !empty($attrs['blockName'] ) ) {
181 $attrs = $this->replace_attachment_ids($attrs);
182 }
183
184 if (is_string($attrs)) {
185 foreach ($this->wp_importer->url_remap as $old_url => $new_url) {
186 if (strpos($attrs, $old_url) !== false) {
187 $attrs = str_replace($old_url, $new_url, $attrs);
188 }
189 }
190 }
191 else if (is_array($attrs)) {
192 foreach ($attrs as $key => $attr) {
193 $attrs[$key] = $this->replace_attachment_url($attr);
194 }
195 }
196
197 return $attrs;
198 }
199
200 protected function replace_attachment_ids($attrs){
201 switch ($attrs['blockName']) {
202 case 'essential-blocks/slider':
203 $attrs = $this->processImages($attrs, 'images', 'imageId', 'url');
204 break;
205 case 'essential-blocks/advanced-image':
206 $attrs = $this->processSingleImage($attrs, 'image');
207 break;
208 case 'essential-blocks/parallax-slider':
209 $attrs = $this->processImages($attrs, 'sliderData', 'id', 'src');
210 break;
211 case 'essential-blocks/image-gallery':
212 $attrs = $this->processImages($attrs, 'images', 'id', 'url');
213 $attrs = $this->processImages($attrs, 'sources', 'id', 'url');
214 break;
215 case 'core/image':
216 $attrs = $this->processCoreImage($attrs, 'id');
217 break;
218 case 'core/media-text':
219 $attrs = $this->processCoreImage($attrs, 'mediaId');
220 break;
221 case 'core/cover':
222 $attrs = $this->processSingleImage($attrs, 'url');
223 break;
224 }
225 return $attrs;
226 }
227
228 private function processImages($attrs, $imageKey, $idKey, $urlKey) {
229 if (!empty($attrs['attrs'][$imageKey])) {
230 foreach ($attrs['attrs'][$imageKey] as $key => &$image) {
231 $imageUrl = $image[$urlKey];
232 if (!empty(self::$attachment_ids[$imageUrl])) {
233 $oldId = $image[$idKey];
234 $newId = (int) self::$attachment_ids[$imageUrl];
235 $image[$idKey] = $newId;
236
237 // Update innerHTML and innerContent for 'essential-blocks/slider'
238 if ($attrs['blockName'] === 'essential-blocks/slider') {
239 $attrs = $this->updateInnerHTMLAndContent($attrs, "imageId&quot;:$oldId,&quot;", "imageId&quot;:$newId,&quot;");
240 }
241 }
242 }
243 }
244 return $attrs;
245 }
246
247 private function processSingleImage($attrs, $imageKey) {
248 if (!empty(self::$attachment_ids[$attrs['attrs'][$imageKey]['url']])) {
249 $attrs['attrs'][$imageKey]['id'] = (int) self::$attachment_ids[$attrs['attrs'][$imageKey]['url']];
250 }
251 return $attrs;
252 }
253
254 private function processCoreImage($attrs, $idKey) {
255 preg_match(self::IMAGE_URL_PATTERN, $attrs['innerHTML'], $matches);
256 if (!empty($matches[0])) {
257 $url = $matches[0];
258 if (!empty(self::$attachment_ids[$url])) {
259 $oldId = $attrs['attrs'][$idKey];
260 $newId = (int) self::$attachment_ids[$url];
261 $attrs['attrs'][$idKey] = $newId;
262
263 // Replace old ID with new ID in innerHTML and innerContent
264 $attrs = $this->updateInnerHTMLAndContent($attrs, "wp-image-$oldId", "wp-image-$newId");
265 }
266 }
267 return $attrs;
268 }
269
270 private function updateInnerHTMLAndContent($attrs, $oldValue, $newValue) {
271 $attrs['innerHTML'] = str_replace($oldValue, $newValue, $attrs['innerHTML']);
272 if (is_array($attrs['innerContent'])) {
273 foreach ($attrs['innerContent'] as $i => $content) {
274 $attrs['innerContent'][$i] = str_replace($oldValue, $newValue, $content);
275 }
276 } else {
277 $attrs['innerContent'] = str_replace($oldValue, $newValue, $attrs['innerContent']);
278 }
279 return $attrs;
280 }
281
282 /**
283 * Parses the images from the post content, processes them as attachments, and updates the post with the new attachment URL.
284 * @todo: Parse using parse_blocks instead of regex
285 *
286 * @param int $post_id The ID of the post.
287 * @param string $post_content The content of the post.
288 */
289 public function parse_images($post_content) {
290 // Find all image URLs in the post content
291 preg_match_all(self::IMAGE_URL_PATTERN, $post_content, $matches);
292
293 $urls = $matches[0];
294 $organizedUrls = [];
295
296 foreach ($urls as $url) {
297 // Remove the size suffix from the URL
298 $base_url = preg_replace('/-\d+x\d+(?=\.[a-zA-Z]+$)/', '', $url);
299
300 // Check if the URL already exists in the array
301 if (!isset($organizedUrls[$base_url]) || !in_array($url, $organizedUrls[$base_url])) {
302 // Add the URL to the array under the base URL key
303 $organizedUrls[$base_url][] = $url;
304 }
305 }
306
307 return $organizedUrls;
308 }
309
310 public function process_images(){
311 // Time to run the import!
312 set_time_limit( 0 );
313
314 $organizedUrls = $this->template_settings['__attachments'];
315 // For each base image URL...
316 foreach ($organizedUrls as $base_url => $sizes) {
317 // Prepare the post data for the attachment
318 $post_data = $this->prepare_post_data($this->post_id, $base_url);
319
320 // If prepare_post_data returned null, skip this iteration
321 if ($post_data === null) {
322 continue;
323 }
324
325 // Check if the attachment already exists
326 $attachment_id = $this->wp_importer->process_attachment($post_data, $base_url, $sizes);
327 // If there was an error, handle it here
328 if (is_wp_error($attachment_id)) {
329 $this->sse_log('error', $attachment_id->get_error_message(), -1, 'eventLog');
330 } else {
331 $this->sse_log('success', "Imported attachment: $attachment_id", -1, 'eventLog');
332 self::$attachment_ids[$base_url] = $attachment_id;
333 }
334 }
335 }
336
337 private function prepare_post_data($post_id, $image_url) {
338 $filetype = wp_check_filetype(basename($image_url));
339 if (!$filetype['type']) {
340 $this->sse_log('prepare', 'Error: Unable to determine the file type.', -1, 'eventLog');
341 return null;
342 }
343
344 $post_data = array(
345 'post_title' => basename($image_url),
346 'post_content' => '',
347 'post_status' => 'inherit',
348 'post_mime_type' => $filetype['type'],
349 'guid' => $image_url,
350 'post_parent' => $post_id, // Set the parent post
351 );
352
353 if (preg_match('%wp-content/uploads/([0-9]{4}/[0-9]{2})%', $image_url, $matches)) {
354 $post_data['upload_date'] = $matches[1];
355 }
356 else{
357 $post_data['upload_date'] = date('Y/m');
358 }
359
360 return $post_data;
361 }
362
363 public function sse_log( $type, $message, $progress = 1, $action = 'updateLog', $status = null ) {
364 if ($this->shouldLog) {
365 parent::sse_log($type, $message, $progress, $action, $status);
366 }
367 else{
368 Helper::log(func_get_args());
369 }
370 }
371
372 public function get_content(){
373 return $this->content;
374 }
375
376 }