PluginProbe
Post Snippets – Custom WordPress Code Snippets Customizer / 4.2.2
Post Snippets – Custom WordPress Code Snippets Customizer v4.2.2
4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.1 1.7.2 1.7.3 1.8 1.8.1 1.8.2 1.8.3 1.8.5 1.8.6 1.8.7 1.8.8 1.8.9 1.8.9.1 1.8.9.2 1.9 1.9.1 1.9.2 1.9.3 1.9.4 1.9.5 All 115 releases
post-snippets / src / PostSnippets / ImportExport.php

ImportExport.php in Post Snippets – Custom WordPress Code Snippets Customizer 4.2.2, at src/PostSnippets/ImportExport.php

601 lines 21.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace PostSnippets;
3
4 if ( ! defined( 'ABSPATH' ) ) exit;
5
6 /**
7 * Post Snippets I/O.
8 *
9 * Class to handle import and export of Snippets.
10 *
11 */
12 class ImportExport
13 {
14 protected static $FILE_ZIP;
15 const FILE_CFG = 'post-snippets-export.cfg';
16
17 private $downloadUrl;
18
19 /**
20 * Export Snippets.
21 *
22 * Check if an export file shall be created, or if a download url should be
23 * pushed to the footer. Also checks for old export files laying around and
24 * deletes them (for security).
25 *
26 * @return void
27 */
28 public function exportSnippets($snippets_ids)
29 {
30 self::set_export_name();
31
32 $url = $this->createExportFile($snippets_ids);
33 if ($url) {
34
35 $this->downloadUrl = $url;
36
37 add_action(
38 'admin_footer',
39 array(&$this, 'psnippetsFooter'),
40 10000
41 );
42
43 return true;
44 } else {
45 return false;
46 }
47
48 }
49
50 /**
51 * Export All Snippets.
52 *
53 * Check if an export file shall be created, or if a download url should be
54 * pushed to the footer. Also checks for old export files laying around and
55 * deletes them (for security).
56 *
57 * @return void
58 */
59 public function exportAllSnippets()
60 {
61 self::set_export_name();
62 if (isset($_POST['postsnippets_export'])) {
63 check_admin_referer('postsnippets_export', 'postsnippets_export_nonce');
64 $url = $this->createExportFile();
65 if ($url) {
66 $this->downloadUrl = $url;
67 add_action(
68 'admin_footer',
69 array(&$this, 'psnippetsFooter'),
70 10000
71 );
72 } else {
73 echo __('Error: ', 'post-snippets') . $url;
74 }
75 } else {
76 // Check if there is any old export files to delete
77 $dir = wp_upload_dir();
78 $upload_dir = $dir['basedir'] . '/';
79 chdir($upload_dir);
80 if (file_exists('./' . self::$FILE_ZIP)) {
81 unlink('./' . self::$FILE_ZIP);
82 }
83 }
84 }
85
86 /**
87 * Handles uploading of post snippets archive and import the snippets.
88 *
89 * @uses wp_handle_upload() in wp-admin/includes/file.php
90 * @return string HTML to handle the import
91 */
92 public function importSnippets()
93 {
94 $import =
95 '<br/><br/><strong>' .
96 __('Import', 'post-snippets') .
97 '</strong><br/>';
98 if (
99 !isset($_FILES['postsnippets_import_file'])
100 || empty($_FILES['postsnippets_import_file'])
101 ) {
102 $import .=
103 '<p>' . __('Import snippets from a post-snippets-export.zip file. Imported sinppets will get added at the bottom.', 'post-snippets') .
104 '</p>';
105 $import .=
106 '<p>' . __('Please make sure no snippets have duplicate titles.', 'post-snippets') .
107 '</p>';
108 $import .= '<form method="post" enctype="multipart/form-data">';
109 $import .= wp_nonce_field('postsnippets_import', 'postsnippets_import_nonce', true, false);
110 $import .= '<input type="file" name="postsnippets_import_file"/>';
111 $import .= '<input type="hidden" name="action" value="wp_handle_upload"/>';
112 $import .=
113 '<input type="submit" class="button" value="' .
114 __('Import Snippets', 'post-snippets') . '"/>';
115 $import .= '</form>';
116 } else {
117
118 check_admin_referer('postsnippets_import', 'postsnippets_import_nonce');
119
120 if (file_exists('./' . self::FILE_CFG)) { /**Overwriting Existing File */
121 unlink('./' . self::FILE_CFG);
122 }
123
124 $file = wp_handle_upload($_FILES['postsnippets_import_file']);
125
126 if (isset($file['file']) && !is_wp_error($file)) {
127 require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
128 $zip = new \PclZip($file['file']);
129 $dir = wp_upload_dir();
130 $upload_dir = $dir['basedir'] . '/';
131 chdir($upload_dir);
132
133 if ($zip->listContent() == 0) {
134 $import .=
135 '<p><strong>' .
136 __('Unsupported File Type:', 'post-snippets') .
137 ' ' .
138 __('Unzipping failed.', 'post-snippets') .
139 '</strong></p>';
140 return $import;
141 }
142
143 $unzipped = $zip->extract();
144
145 if (
146 $unzipped[0]['stored_filename'] == self::FILE_CFG
147 && $unzipped[0]['status'] == 'ok'
148 || $unzipped[0]['status'] == 'newer_exist'
149 ) {
150 // Delete the uploaded archive
151 unlink($file['file']);
152
153 $snippets = file_get_contents(
154 $upload_dir . self::FILE_CFG
155 );
156
157 if ($snippets) {
158
159 $snippets = apply_filters(
160 'post_snippets_import',
161 $snippets
162 );
163
164 $imported_snippets = maybe_unserialize($snippets);
165
166 if (!empty($imported_snippets)) {
167
168 $import .= $this->importAllSnippets($imported_snippets);
169 } else {
170 $import .=
171 '<p><strong>' .
172 __('Empty Snippets.', 'post-snippets') .
173 '</strong></p>';
174 }
175 }
176
177 // Delete the snippet file
178 unlink('./' . self::FILE_CFG);
179
180 } else {
181 $import .=
182 '<p><strong>' .
183 __('Snippets could not be imported:', 'post-snippets') .
184 ' ' .
185 __('Unzipping failed.', 'post-snippets') .
186 '</strong></p>';
187 }
188 } else {
189 if ($file['error'] || is_wp_error($file)) {
190 $import .=
191 '<p><strong>' .
192 __('Snippets could not be imported:', 'post-snippets') .
193 ' ' .
194 $file['error'] . '</strong></p>';
195 } else {
196 $import .=
197 '<p><strong>' .
198 __('Snippets could not be imported:', 'post-snippets') .
199 ' ' .
200 __('Upload failed.', 'post-snippets') .
201 '</strong></p>';
202 }
203 }
204 }
205 return $import;
206 }
207
208
209 function importAllSnippets($imported_snippets)
210 {
211
212 global $wpdb;
213 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
214 $group_table_name = $wpdb->prefix . \PostSnippets::GROUP_TABLE_NAME;
215 $snippet_added = false;
216
217 if (empty(array_column($imported_snippets, 'ID'))) { /**Old Exported Files, Backward Compatibility */
218
219 $current_snippets_titles = $wpdb->get_results($wpdb->prepare("SELECT snippet_title from %1s", $table_name), ARRAY_A);
220 $current_snippets_titles = array_column($current_snippets_titles, "snippet_title");
221
222 if (!empty($current_snippets_titles)) { /**If there are any Existing Snippets */
223
224 foreach ($imported_snippets as $imported_snippet) {
225
226 if (in_array($imported_snippet['title'], $current_snippets_titles)) {
227 //duplicate according to settings
228 $snippet_added = $this->duplicateSnippet($imported_snippet);
229
230 } else { /**No Duplicate */
231 DBTable::update_db_table_previous(array($imported_snippet), true);
232 $snippet_added = true;
233 }
234 }
235
236 } else { /**There aren't any Existing Snippets */
237
238 DBTable::update_db_table_previous($imported_snippets, true);
239 $snippet_added = true;
240
241 }
242
243 if ($snippet_added) {
244 return
245 '<p><strong>' .
246 __('Snippets Added Successfully.', 'post-snippets') .
247 '</strong></p>';
248 } else {
249 return
250 '<p><strong>' .
251 __('Snippets Not Added.', 'post-snippets') .
252 '</strong></p>';
253 }
254
255 }
256
257 $current_snippets_titles = $wpdb->get_results($wpdb->prepare("SELECT snippet_title from %1s", $table_name), ARRAY_A);
258 $imported_snippets_titles = array_column($imported_snippets, 'snippet_title');
259 $current_snippets_titles = array_column($current_snippets_titles, "snippet_title");
260
261 $group_details = $imported_snippets['group_details'] ?? array();
262
263 if (!empty($group_details)) {
264 unset($imported_snippets['group_details']);
265 }
266
267 if (!empty($current_snippets_titles)) { /**If there are any Existing Snippets */
268
269 foreach ($imported_snippets as $imported_snippet) {
270
271 if (in_array($imported_snippet['snippet_title'], $current_snippets_titles)) {
272 //duplicate according to settings
273 $imported_snippet = $this->updateGroupDetails($imported_snippet, $group_details);
274 $snippet_added = $this->duplicateSnippet($imported_snippet);
275 } else { /**No Duplicate */
276
277 $imported_snippet = $this->updateGroupDetails($imported_snippet, $group_details);
278 $snippet_added = Edit::addImportedSnippet($imported_snippet);
279
280 }
281 }
282 } else { /**There aren't any Existing Snippets */
283
284 foreach ($imported_snippets as $imported_snippet) {
285
286 $imported_snippet = $this->updateGroupDetails($imported_snippet, $group_details);
287 $snippet_added = Edit::addImportedSnippet($imported_snippet);
288
289 }
290 }
291
292 if ($snippet_added) {
293
294 return
295 '<p><strong>' .
296 __('Snippets Added Successfully.', 'post-snippets') .
297 '</strong></p>';
298
299 } else {
300 return
301 '<p><strong>' .
302 __('Snippets Not Added.', 'post-snippets') .
303 '</strong></p>';
304
305 }
306 }
307
308 public function duplicateSnippet($imported_snippet)
309 {
310
311 $duplicate_option = get_option(\PostSnippets::SETTINGS);
312
313 if (!isset($duplicate_option['duplicate_option'])) {
314 return true; /**If duplicate option doesn't exist.. maybe due to version difference */
315 }
316
317 if ($duplicate_option['duplicate_option'] == 'allow_duplicate') {
318
319 if (isset($imported_snippet['ID'])) { /**Revamped Version */
320 $imported_snippet['snippet_title'] = Edit::number_duplicate_snippet_title($imported_snippet['snippet_title']);
321 return Edit::addImportedSnippet($imported_snippet);
322 } else { /**Old Version, without ID */
323 $imported_snippet["title"] = Edit::number_duplicate_snippet_title($imported_snippet["title"]);
324 DBTable::update_db_table_previous(array($imported_snippet), true);
325 return true;
326 }
327 }
328
329 if ($duplicate_option['duplicate_option'] == 'replace_duplicate') {
330
331 return $this->replaceSnippet($imported_snippet);
332
333 }
334
335 if ($duplicate_option['duplicate_option'] == 'skip_duplicate') {
336 return true;
337 }
338
339 return true;
340
341 }
342
343 public function replaceSnippet($imported_snippet)
344 {
345
346 global $wpdb;
347 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
348 $table_name_group = $wpdb->prefix . \PostSnippets::GROUP_TABLE_NAME;
349
350
351 // $wild = '%';
352 $find = isset($imported_snippet['ID']) ? $imported_snippet['snippet_title'] : $imported_snippet['title'];
353 // $snippet_title_like = $wild . $wpdb->esc_like( $find ) . $wild;
354
355 $particular_snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_title = %s", $find), ARRAY_A);
356
357 foreach ($particular_snippets as $particular_snippet) { /**DB query may return multiple snippets of same case-insensitive name */
358
359 if (!empty($particular_snippet) && strcmp($particular_snippet['snippet_title'], $find) == 0) { /**Filtering case-sensitively, cause DB is insensitive */
360 $snippet_found = $particular_snippet;
361 break;
362 } else {
363 continue;
364 }
365
366 }
367
368 if (isset($imported_snippet['snippet_group'])) {
369
370 /**
371 * change group ids, if they are different
372 * from imported
373 */
374
375 $current_snippet_group_ids = $snippet_found['snippet_group'];
376
377 $snippet_group = $imported_snippet['snippet_group'];
378
379 $group_ids_to_increase_count = array_diff(maybe_unserialize($imported_snippet['snippet_group']), maybe_unserialize($current_snippet_group_ids));
380
381 $group_ids_to_decrease_count = array_diff(maybe_unserialize($current_snippet_group_ids), maybe_unserialize($imported_snippet['snippet_group']));
382
383 }
384
385 if (!empty($snippet_group) && !is_serialized($snippet_group)) {
386
387 $snippet_group = maybe_serialize($snippet_group);
388
389 }
390
391 $snippet_php = PSallSnippets::get_snippet_php($imported_snippet['snippet_php'] ?? $imported_snippet['php']);
392
393 // Sanitize snippet content before updating
394 $content_to_update = $imported_snippet['snippet_content'] ?? addslashes($imported_snippet['snippet'] ?? '');
395 $sanitized_content = Edit::sanitize_snippet_content($content_to_update, $snippet_php);
396
397 $snippet_updated = $wpdb->update(
398 $table_name,
399 array(
400 'snippet_group' => $imported_snippet['snippet_group'] ?? $snippet_found['snippet_group'],
401 // 'snippet_title' => $snippet_title,
402 'snippet_content' => $sanitized_content,
403 'snippet_date' => current_time('mysql'),
404 'snippet_vars' => $imported_snippet['snippet_vars'] ?? Edit::filter_snippet_vars($imported_snippet['vars'] ?? ''),
405 'snippet_desc' => $imported_snippet['snippet_desc'] ?? sanitize_textarea_field($imported_snippet['description'] ?? ''),
406 'snippet_status' => ($imported_snippet['snippet_status'] ?? $snippet_found['snippet_status']) == 1 ? 1 : 0,
407 'snippet_shortcode' => ($imported_snippet['snippet_shortcode'] ?? $imported_snippet['shortcode'] ?? 0) == 1 ? 1 : 0,
408 'snippet_php' => $snippet_php,
409 'snippet_wptexturize' => ($imported_snippet['snippet_wptexturize'] ?? $imported_snippet['wptexturize'] ?? 0) == 1 ? 1 : 0,
410 ),
411 array( /**Where Coulum = ? */
412 'ID' => $snippet_found['ID'],
413 ),
414 array( /**Data Format, %d or %s */
415 '%s', /*'%s',*/
416 '%s',
417 '%s',
418 '%s',
419 '%s',
420 '%d',
421 '%d',
422 '%d',
423 '%d'
424 ),
425 array( /**Where Format, %d or %s */
426 '%d'
427 )
428 );
429
430 if ($snippet_updated) {
431
432 if (isset($group_ids_to_increase_count) && !empty($group_ids_to_increase_count)) {
433
434 Edit::change_group_count($group_ids_to_increase_count, 'increment');
435 }
436
437 if (isset($group_ids_to_decrease_count) && !empty($group_ids_to_decrease_count)) {
438
439 Edit::change_group_count($group_ids_to_decrease_count, 'decrement');
440 }
441
442 return true;
443 }
444
445 }
446
447 public function updateGroupDetails($imported_snippet, $group_details)
448 {
449
450 global $wpdb;
451 $group_table_name = $wpdb->prefix . \PostSnippets::GROUP_TABLE_NAME;
452
453 $group_ids = maybe_unserialize($imported_snippet['snippet_group']);
454
455 $all_group_ids = array_column($group_details, 'ID');
456
457 foreach ($group_ids as $key => $group_id) { /**Getting groups who has same group ID as in exported snippet_groups */
458
459 $group_details[$key] = $group_details[array_search($group_id, $all_group_ids, true)];
460
461 }
462
463
464 foreach ($group_details as $group) { /**getting group IDs from group DB by slug, if exists, else creating new group */
465
466 $group_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $group_table_name WHERE group_slug = %s", $group['group_slug']));
467
468 if ($group_id == NULL) {
469
470 $group_added_status = $wpdb->insert(
471 $group_table_name,
472 array(
473 'group_name' => $group['group_name'],
474 'group_slug' => $group['group_slug'],
475 'group_desc' => $group['group_desc'],
476 'group_count' => 0
477 )
478 );
479
480 $imported_snippet = $this->changeGroupId($imported_snippet, $group['ID'], $wpdb->insert_id);
481 } else {
482
483 $imported_snippet = $this->changeGroupId($imported_snippet, $group['ID'], $group_id);
484
485 }
486 }
487
488 return $imported_snippet;
489 }
490
491 private function changeGroupId($imported_snippet, $old_id, $new_id)
492 {
493
494 $imported_snippet_groups = maybe_unserialize($imported_snippet['snippet_group']);
495
496 if (in_array($old_id, $imported_snippet_groups, true) && ($old_id != $new_id)) {
497
498 $imported_snippet_groups[array_search($old_id, $imported_snippet_groups, true)] = strval($new_id);
499
500 $imported_snippet['snippet_group'] = maybe_serialize($imported_snippet_groups);
501
502 }
503
504 return $imported_snippet;
505 }
506
507 /**
508 * Create a zipped filed containing all Post Snippets, for export.
509 *
510 * @return string URL to the exported snippets
511 */
512 private function createExportFile($snippets_ids = '')
513 {
514 $dir = wp_upload_dir();
515 $upload_dir = $dir['basedir'] . '/';
516 $upload_url = $dir['baseurl'] . '/';
517
518 global $wpdb;
519
520 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
521
522 if (empty($snippets_ids)) {
523
524 $snippets = $wpdb->get_results($wpdb->prepare("SELECT * from %1s", $table_name), ARRAY_A);
525
526 } else {
527
528 $snippets = $wpdb->get_results($wpdb->prepare("SELECT * from $table_name WHERE ID IN %1s", $snippets_ids), ARRAY_A);
529 }
530
531 $snippets = $this->addGroupDetails($snippets);
532
533 $snippets = maybe_serialize($snippets);
534
535 $snippets = apply_filters('post_snippets_export', $snippets);
536
537
538 // Open a file stream and write the serialized options to it.
539 if (!$handle = fopen($upload_dir . './' . self::FILE_CFG, 'w')) {
540 die();
541 }
542 if (!fwrite($handle, $snippets)) {
543 die();
544 }
545 fclose($handle);
546
547 // Create a zip archive
548 require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
549 chdir($upload_dir);
550 $zip = new \PclZip('./' . self::$FILE_ZIP);
551 $zipped = $zip->create('./' . self::FILE_CFG);
552
553 // Delete the snippet file
554 unlink('./' . self::FILE_CFG);
555
556 if (!$zipped) {
557 return false;
558 }
559
560 return $upload_url . './' . self::$FILE_ZIP;
561 }
562
563 private function addGroupDetails($snippets)
564 {
565
566 global $wpdb;
567
568 $table_name = $wpdb->prefix . \PostSnippets::GROUP_TABLE_NAME;
569
570 $group_details = $wpdb->get_results($wpdb->prepare("SELECT * from $table_name WHERE group_count > %d", 0), ARRAY_A);
571
572 $snippets['group_details'] = $group_details;
573
574 return $snippets;
575 }
576
577 /**
578 * Set export file name
579 */
580 public static function set_export_name()
581 {
582 $date_part = date('Y-m-d');
583 self::$FILE_ZIP = "post-snippets-export-{$date_part}.zip";
584 }
585
586 /**
587 * Generates the javascript to trigger the download of the file.
588 *
589 * @return void
590 */
591 public function psnippetsFooter()
592 {
593 $export = '<script type="text/javascript">
594 jQuery(document).ready(function ($) {
595 document.location = \'' . $this->downloadUrl . '\';
596 });
597 </script>';
598 echo $export;
599 }
600 }
601