-
Notifications
You must be signed in to change notification settings - Fork 2
/
ProcessMigrator.module
2986 lines (2497 loc) · 148 KB
/
ProcessMigrator.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ProcessWire Migrator
* by Adrian Jones
*
* Automatically migrate content from one PW installation to another. Also allows 3rd party modules to convert content from other sources.
*
* ProcessWire 2.x
* Copyright (C) 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
* http://www.ryancramer.com
*
*/
ini_set('max_execution_time', 0); // no time limit
ini_set('memory_limit', '1024M');
class ProcessMigrator extends Process implements Module, ConfigurableModule {
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Migrator',
'version' => '0.7.8',
'summary' => 'Automatically migrate content from one PW installation to another. Also allows 3rd party modules to convert content from other sources.',
'href' => 'https://processwire.com/talk/topic/4420-migrator/',
'singular' => true,
'autoload' => false,
'icon' => 'exchange',
'nav' => array(
array(
'url' => 'export/',
'label' => 'Export',
'icon' => 'arrow-right',
),
array(
'url' => 'import/',
'label' => 'Import',
'icon' => 'arrow-left'
),
array(
'url' => 'restore/',
'label' => 'Restore',
'icon' => 'reply'
)
)
);
}
/**
* Name used for the page created in the admin
*
*/
const adminPageName = 'migrator';
protected $pageFiles = array();
protected $repeaterSubFields = array();
protected $templateFiles = array();
protected $migratedTemplateFileNames = array();
protected $selectedFields = array();
protected $selectedPages = array();
protected $zipFilename = '';
//protected $jsonFilename = '';
//protected $migratorFilesDir = '';
protected $newPage = '';
protected $newField = '';
protected $base_url = '';
protected $thumb_suffix = '';
/**
* Instance of Template, used for imported pages
*
*/
protected $template = null;
/**
* Instance of Page, representing the parent Page for imported pages
*
*/
protected $parent = null;
/**
* Default configuration for module
*
*/
static public function getDefaultData() {
return array(
"ignoredSubFolders" => ""
);
}
/**
* Populate the default config data
*
*/
public function __construct() {
foreach(self::getDefaultData() as $key => $value) {
$this->$key = $value;
}
}
/**
* Initialize the module
*
*/
public function init() {
parent::init();
ini_set('auto_detect_line_endings', true);
wire("config")->scripts->add("/wire/modules/Inputfield/InputfieldDatetime/jquery-ui-timepicker-addon.js");
}
/**
* Executed when root url for module is accessed
*
*/
public function ___execute() {
$form = $this->buildForm1();
if($this->input->post->submit) {
if($this->processForm1($form) || $this->processExportForm2($form) || $this->processImportForm2($form)) $this->session->redirect('./'.$this->session->type.'/');
}
return $form->render();
}
/**
* Executed when ./export/ url for module is accessed
*
*/
public function ___executeExport() {
$form = $this->buildExportForm2();
if($this->input->post->submit) {
return $this->processExportForm2($form);
} else {
//$form = $this->buildExportForm2();
return $form->render();
}
}
/**
* Executed when ./import/ url for module is accessed
*
*/
public function ___executeImport() {
$form = $this->buildImportForm2();
if($this->input->post->submit) {
return $this->processImportForm2($form);
} else {
return $form->render();
}
}
/**
* Executed when ./restore/ url for module is accessed
*
*/
public function ___executeRestore() {
$form = $this->buildRestoreForm2();
if($this->input->post->submit) {
return $this->processRestoreForm2($form);
} else {
return $form->render();
}
}
/**
* Build the "Step 1" form
*
*/
protected function buildForm1() {
$form = $this->modules->get("InputfieldForm");
$form->method = 'post';
$form->description = "Step 1: Export, Import, or Restore";
$f = $this->modules->get("InputfieldSelect");
$f->name = 'type';
$f->label = 'Export, Import, or Restore';
$f->required = true;
$f->addOption('');
$f->addOption('export', 'Export');
$f->addOption('import', 'Import');
if(class_exists('WireDatabaseBackup')){ //not present in older version of PW - prior to Aug 19, 2014 (approx 2.4.13)
$f->addOption('restore', 'Restore');
}
if($this->session->type) $f->attr('value', $this->session->type);
$form->add($f);
$this->addSubmit($form, 'Continue to Step 2');
return $form;
}
/**
* Process the "Step 1" form and populate session variables with the results
*
*/
protected function processForm1(InputfieldForm $form) {
$form->processInput($this->input->post);
if(count($form->getErrors())) return false;
//$this->session->type = (int) $form->get('type')->value;
$type = $form->get('type')->value;
if(!$type) {
$this->error("Missing required Export/Import/Restore action type");
return false;
}
$this->session->type = $type;
return true;
}
/**
* Build the "Export Step 2" form
*
*/
protected function buildExportForm2() {
$form = $this->modules->get("InputfieldForm");
$form->method = 'post';
$form->description = "Step 2: Export Page Tree";
$f = $this->modules->get("InputfieldPageListSelect");
$f->name = 'treeParent';
$f->label = 'Parent Page';
$f->required = true;
$f->description = "The parent of the page tree you want to export.";
if($this->session->treeParent) $f->attr('value', $this->session->treeParent);
$form->add($f);
$f = $this->modules->get("InputfieldSelect");
$f->name = 'export_components';
$f->label = 'Components to export';
$f->required = true;
$f->addOption('everything', 'Everything, including all data pages');
$f->addOption('fields_templates_and_structural_pages', 'Fields, Templates and Structural Pages');
$f->addOption('fields_and_templates_only', 'Fields and Templates Only');
if($this->session->export_components) $f->attr('value', $this->session->export_components);
$form->add($f);
$f = $this->modules->get("InputfieldDatetime");
$f->label = "Changes since";
$f->datepicker = 3;
$f->attr("name+id", "changes_since");
$f->dateInputFormat = "Y-m-d";
$f->timeInputFormat = "H:i:s";
if($this->session->changes_since){
$f->attr('value', $this->session->changes_since);
$f->attr('data-ts', $this->session->changes_since);
}
$f->description = "You can use this to export all pages that have changed since this date/time.";
$f->collapsed = Inputfield::collapsedBlank;
$form->add($f);
$f = $this->modules->get("InputfieldSelect");
$f->name = 'save_or_copy';
$f->label = 'Output Format';
$f->description = "SAVE zip file to your computer OR display code so you can COPY and then paste into new site.\nNB Copy will not work for migrating full page content if there are included files/images. It also won't migrate required template files.";
$f->required = true;
$f->addOption('save', 'Save');
$f->addOption('copy', 'Copy');
if($this->session->save_or_copy) $f->attr('value', $this->session->save_or_copy);
$form->add($f);
$f = $this->modules->get("InputfieldAsmSelect");
$f->name = 'helper_files';
$f->label = 'Helper Files';
$f->description = "Determines which additional helper files (inc, css, js etc) will be included in the export. These will be in addition to the required template php files needed for the templates, which will automatically be included.";
$f->showIf = "save_or_copy=save";
/*
foreach($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->config->paths->templates, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item){
if ($item->isDir()) {
//$f->addOption($iterator->getSubPathName(), $iterator->getSubPathName());
}
else {
$exclude = false;
foreach(explode("\n", $this->data['ignoredSubFolders']) as $ignoredSubFolder) {
if(pathinfo($iterator->getSubPathName(), PATHINFO_DIRNAME) == $ignoredSubFolder) $exclude = true;
}
if(!$exclude) $f->addOption($iterator->getSubPathName(), $iterator->getSubPathName());
}
}
*/
// fix by @jlahijani: prevent export from completely erroring if on windows and have directories that exceed the path limit (like 'node_modules'), which ignoredSubfolders won't have an affect on
try {
foreach($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->config->paths->templates, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item){
if ($item->isDir()) {
//$f->addOption($iterator->getSubPathName(), $iterator->getSubPathName());
}
else {
$exclude = false;
foreach(explode("\n", $this->data['ignoredSubFolders']) as $ignoredSubFolder) {
if(dirname(pathinfo($iterator->getSubPathName(), PATHINFO_DIRNAME)) == $ignoredSubFolder) $exclude = true;
// @jlahijani: dirty way to detect ignored folders if on windows and hit directory path bug
//if( strpos($iterator->getSubPathName(), $ignoredSubFolder ) !== false ) $exclude = true;
}
if(!$exclude) $f->addOption($iterator->getSubPathName(), $iterator->getSubPathName());
}
}
} catch (Exception $e) {
//consider putting friendly message here about hitting the windows path limit, but that it won't entirely affect their import.
//$this->message("");
}
$form->add($f);
$this->addSubmit($form, 'Export');
return $form;
}
/**
* Process the "Step 2" form and populate session variables with the results
*
*/
protected function processExportForm2(InputfieldForm $form) {
$form->processInput($this->input->post);
$this->session->treeParent = (int) $form->get('treeParent')->value;
$this->session->export_components = $form->get('export_components')->value;
$this->session->changes_since = $form->get('changes_since')->value;
$this->session->save_or_copy = $form->get('save_or_copy')->value;
$this->session->helper_files = $form->get('helper_files')->value;
if(count($form->getErrors())){
if(!$form->get('treeParent')->value) $this->error("You did not select a parent page. This must be selected to define the content to export.");
if(!$form->get('export_components')->value) $this->error("You did not select the export components.");
if(!$form->get('save_or_copy')->value) $this->error("You did not choose an output format.");
//$this->session->redirect('./'.$this->session->type);
return $form->render();
}
//find all the relevant pages under the selected parent and then sort them by child level (count path segments) to make sure parents are added to the JSON before their children
if($this->session->changes_since != ''){
$items = $this->pages->get($this->session->treeParent)->find("modified>{$this->session->changes_since}, id!=2, id!=7, has_parent!=2, has_parent!=7, template!=admin, sort=id, include=all"); // exclude admin and trash in case the user chooses the 'Home' as the parent
}
else{
$items = $this->pages->get($this->session->treeParent)->find("id!=2, id!=7, has_parent!=2, has_parent!=7, template!=admin, sort=id, include=all"); // exclude admin and trash in case the user chooses the 'Home' as the parent
}
// create empty page array
$res = new PageArray();
foreach($items as $item) {
// temporarily add pathsegments property to items
$item->pathsegments = count(explode('/',$item->path));
$res->add($item);
}
//sort based on their level in the page hierarchy which ensures parents get created before their children
$items = $res->filter("sort=pathsegments");
$parent_item = $this->pages->get($this->session->treeParent);
$items->prepend($parent_item);
if($this->session->save_or_copy == 'copy'){
return '<p><textarea rows="10" style="width:95%">' . $this->pagesToJSON($items, $this->session->export_components) . '</textarea></p><p>Copy this text and import it into your new site using the paste option.</p><p><a href="../export/">Export more pages</a></p>';
}
else{
$this->session->jsonFilename = $this->page->filesManager()->path() . 'data.json';
//header('Content-disposition: attachment; filename='.$this->pages->get($this->session->treeParent)->name.'.json');
//header('Content-type: application/json');
//echo ($this->pagesToJSON($items, $this->session->export_components));
//exit;
//write json file to assets folder and add it to the zip download
file_put_contents($this->session->jsonFilename, $this->pagesToJSON($items, $this->session->export_components));
$allfiles = array($this->session->jsonFilename);
$this->create_zip($allfiles, $this->page->filesManager()->path().'files.zip', 'json');
unlink($this->session->jsonFilename);
//download the zip to the users
$zipFilename = $this->page->filesManager()->path().'files.zip';
if (file_exists($zipFilename)) {
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.basename($zipFilename));
header('Content-length: ' . filesize($zipFilename));
header('Pragma: no-cache');
header('Expires: 0');
readfile($zipFilename);
unlink($zipFilename);
exit;
}
}
}
/**
* Build the "Import Step 2" form to import the json file
*
*/
protected function buildImportForm2() {
$form = $this->modules->get("InputfieldForm");
$form->method = 'post';
$form->description = "Step 2: Import";
if(class_exists('WireDatabaseBackup')){ //not present in older version of PW - prior to Aug 19, 2014 (approx 2.4.13)
$f = $this->modules->get("InputfieldCheckbox");
$f->name = 'create_backup';
$f->label = 'Backup existing database and templates directory';
$f->description = "Determines whether to backup the existing database and the templates and assets/files directories before importing the new content. Highly Recommended!";
if($this->session->create_backup) $f->attr('value', $this->session->create_backup);
$f->attr('checked', $this->session->create_backup == '1' ? 'checked' : '' );
$form->add($f);
}
$f = $this->modules->get("InputfieldPageListSelect");
$f->name = 'import_to_parent';
$f->label = 'Parent Page';
$f->description = "The parent that you want the imported pages added to.\r\nIMPORTANT NOTE:\r\nThis should be one level up from the parent that you exported, the only exception being if you exported \"Home\", in which case you should still choose \"Home\". \r\nThis is not required if you choose 'Fields and Templates Only' from the options below.";
if($this->session->import_to_parent) $f->attr('value', $this->session->import_to_parent);
$form->add($f);
$f = $this->modules->get("InputfieldSelect");
$f->name = 'import_components';
$f->label = 'Components to Import';
$f->required = true;
$f->addOption('everything', 'Everything, including all data pages');
//$f->addOption('fields_templates_and_structural_pages', 'Fields, Templates and Structural Pages');
$f->addOption('fields_and_templates_only', 'Fields and Templates Only');
if($this->session->import_components) $f->attr('value', $this->session->import_components);
$form->add($f);
$f = $this->modules->get("InputfieldSelect");
$f->name = 'import_type';
$f->label = 'Import Type';
$f->required = true;
$f->addOption('append', 'Append');
$f->addOption('overwrite', 'Overwrite');
$f->addOption('replace', 'Replace');
$f->description = "APPEND will not change settings of existing fields, nor the content of existing pages. It will append new fields to templates and new pages (and date) to the selected Parent Page.\nOVERWRITE will change field settings and edit the content of existing pages so they match the imported data.\nREPLACE will match the destination to the source exactly, by modifying page data, changing field type and field settings, and deleting unused fields from templates.";
if($this->session->import_type) $f->attr('value', $this->session->import_type);
$form->add($f);
$f = $this->modules->get("InputfieldCheckbox");
$f->name = 'user_details';
$f->label = 'Import User Details';
$f->description = "Determines whether to migrate the original createdUser and modifiedUser for each page.";
if($this->session->user_details) $f->attr('value', $this->session->user_details);
$f->attr('checked', $this->session->user_details == '1' ? 'checked' : '' );
$f->collapsed = Inputfield::collapsedBlank;
$form->add($f);
$f = $this->modules->get("InputfieldCheckbox");
$f->name = 'page_dates';
$f->label = 'Import Created / Modified Dates';
$f->description = "Determines whether to migrate the original created and modified dates for each page.";
if($this->session->page_dates) $f->attr('value', $this->session->page_dates);
$f->attr('checked', $this->session->page_dates == '1' ? 'checked' : '' );
$f->collapsed = Inputfield::collapsedBlank;
$form->add($f);
$f = $this->modules->get("InputfieldCheckbox");
$f->name = 'download_modules';
$f->label = 'Automatically Download and Install Missing Fieldtypes';
$f->description = "Determines whether to automatically download and install missing fieldtypes.";
$f->notes = "If you do not trust the source of the import data, then it is recommended to NOT check this and manually install any missing fieldtypes when warned.";
if($this->session->download_modules) $f->attr('value', $this->session->download_modules);
$f->attr('checked', $this->session->download_modules == '1' ? 'checked' : '' );
$form->add($f);
$fieldset = $this->modules->get("InputfieldFieldset");
$fieldset->attr('id', 'json_source_options');
$fieldset->label = "Data Source";
$fieldset->description = "Choose one of the following options as the source of the data.\r\nIf you are importing \"Everything, including all data pages\" and you have files/images in the pages, then you must choose the zip upload.\r\nNB: The structure of this JSON is critical, so it is important that it was created using the export feature of this module.";
$form->add($fieldset);
$f = $this->modules->get("InputfieldFile");
$f->name = 'zip_file';
$f->label = 'Zip File Upload';
$f->extensions = 'zip';
$f->maxFiles = 1;
$f->descriptionRows = 0;
$f->overwrite = true;
$f->collapsed = Inputfield::collapsedBlank;
$fieldset->add($f);
//look for plugin migrator modules and add an importer for each one
$migratorClasses = array();
foreach($this->wire('modules') as $module) {
$className = $module->className();
//Look for Migrator in the class name. Might need to make this more specific
if (strpos($className,'Migrator') === false || $className == 'Migrator') continue;
$module = $this->wire('modules')->get($className);
$info = $this->wire('modules')->getModuleInfo($module);
if(!in_array('ProcessMigrator', $info['requires'])) continue;
$f = $this->modules->get("InputfieldFile");
$f->name = 'thirdparty_file_'.$className;
$f->label = $info['title'];
$f->extensions = $info['filetype'];
$f->maxFiles = 1;
$f->descriptionRows = 0;
$f->overwrite = true;
$f->collapsed = Inputfield::collapsedBlank;
$fieldset->add($f);
$migratorClasses[] = $className;
}
// Little workaround because multidimensional field names aren't allowed
if(isset($migratorClasses)){
$f = $this->modules->get("InputfieldHidden");
$f->name = 'migrator_classes';
$f->value = json_encode($migratorClasses);
$fieldset->add($f);
}
$f = $this->modules->get("InputfieldTextarea");
$f->name = 'json_data';
$f->label = 'Paste in JSON Data';
$f->collapsed = Inputfield::collapsedBlank;
$fieldset->add($f);
$f = $this->modules->get("InputfieldSelect");
$f->name = 'json_package';
$f->label = 'Shared JSON packages';
//$packages = json_decode(file_get_contents('https://raw.github.com/adrianbj/ProcessWirePageLists/master/packages.json'));
$options = array('http' => array('user_agent' => 'adrianbj'));
$context = stream_context_create($options);
$packages = json_decode(file_get_contents('https://api.github.com/repos/adrianbj/ProcessWirePageLists/contents/', false, $context));
if(!is_array($packages)) {
$this->error("Github rate limit has been exceeded. Please try again shortly.");
$f->description = __("Github rate limit has been exceeded. Please try again shortly.");
}
else{
$f->addOption('');
foreach($packages as $package){
if(pathinfo($package->html_url, PATHINFO_EXTENSION) != "json") continue; //exclude readme, license etc. Only looking for JSON files
$package_name = pathinfo($package->html_url, PATHINFO_FILENAME);
$package_raw_url = str_replace('//','//raw.', str_replace('blob/','',$package->html_url));
$f->addOption($package_raw_url, $package_name);
}
if($this->session->json_package) $f->attr('value', $this->session->json_package);
$f->description = __("Select from one of the shared JSON packages.\r\nMore details about these packages are available at the ProcessWirePageLists Github page: [https://github.com/adrianbj/ProcessWirePageLists](https://github.com/adrianbj/ProcessWirePageLists)");
}
$f->collapsed = Inputfield::collapsedBlank;
$fieldset->add($f);
$f = $this->modules->get("InputfieldURL");
$f->name = 'json_url';
$f->label = 'URL to JSON file';
$f->description = "Enter a URL directly to a .json file, eg: [https://raw.github.com/adrianbj/ProcessWirePageLists/master/countries.json](https://raw.github.com/adrianbj/ProcessWirePageLists/master/countries.json)";
$f->collapsed = Inputfield::collapsedBlank;
$fieldset->add($f);
$f = $this->modules->get("InputfieldCheckbox");
$f->name = 'edit_imported_content';
$f->label = 'Edit Imported Content';
$f->description = "If checked you will get another step where you can choose exactly which pages and fields you want to import.";
$f->attr('checked', $this->session->edit_imported_content == '1' ? 'checked' : '' );
//$f->collapsed = Inputfield::collapsedBlank;
$f->collapsed = $f->attr('checked') ? Inputfield::collapsedNo : Inputfield::collapsedYes;
$form->add($f);
$this->addSubmit($form, 'Upload and Create Content');
return $form;
}
/**
* Build the "Restore Step 2" form to restore database backup
*
*/
protected function buildRestoreForm2() {
$form = $this->modules->get("InputfieldForm");
$form->method = 'post';
$f = $this->modules->get("InputfieldSelect");
$f->name = 'restore_directory';
$f->label = 'Backup to Restore';
$f->required = true;
if(file_exists($this->config->paths->assets.'migratorbackups/') && !$this->is_dir_empty($this->config->paths->assets.'migratorbackups/')){
$form->description = "Step 2: Restore";
foreach($iterator = new RecursiveDirectoryIterator($this->config->paths->assets.'migratorbackups/', RecursiveDirectoryIterator::SKIP_DOTS) as $item){
if ($item->isDir()) {
if(strpos($iterator->getSubPathName(),'_') !== false){
//convert dir name to friendly date / time format for restore select dropdown
$optionLabel = strstr($iterator->getSubPathName(), '_', true) . " " . str_replace("-", ":", str_replace("_", "", strstr($iterator->getSubPathName(), '_')));
}
else{
$optionLabel = $iterator->getSubPathName(); // just for anyone who installed the module before the date format changed
}
$f->addOption($iterator->getSubPathName(), $optionLabel);
}
}
if($this->session->restore_directory) $f->attr('value', $this->session->restore_directory);
$form->add($f);
$this->addSubmit($form, 'Restore');
}
else{
$form->description = "Sorry, there are no backups to restore.";
}
return $form;
}
/**
* Build the "Import Step 3" form to determine what pages/fields get imported
*
*/
protected function buildImportForm3($data) {
$form = $this->modules->get("InputfieldForm");
$form->method = 'post';
$form->description = "Step 3: Edit Content to be Imported";
$f = $this->modules->get("InputfieldAsmSelect");
$f->name = 'import_fields';
$f->label = 'Excluded Fields';
$f->required = true;
foreach($data->fields as $np){
$f->addOption($np->name, $np->name);
//$f->attr('value', $np->name);
}
$f->description = "By default, all fields are imported. Select any fields that you DON'T want to import.";
$f->setAsmSelectOption('sortable', false);
$form->add($f);
if(isset($data->pages) && $this->session->import_components != 'fields_and_templates_only'){
$f = $this->modules->get("InputfieldAsmSelect");
$f->name = 'import_pages';
$f->label = 'Excluded Pages';
$f->required = true;
foreach($data->pages as $np){
$f->addOption($np->name, $np->name);
//$f->attr('value', $np->name);
}
$f->description = "By default, all pages are imported. Select any pages that you DON'T want to import.";
$f->setAsmSelectOption('sortable', false);
$form->add($f);
}
//these hidden fields are a bit of a hack to prevent field required notices when processing this form because we are using the same code to process Input Form2 and Form3 and session variables are being lost somewhere
$f = $this->modules->get("InputfieldHidden");
$f->name = 'create_backup';
if($this->session->create_backup) $f->attr('value', $this->session->create_backup);
$form->add($f);
$f = $this->modules->get("InputfieldHidden");
$f->name = 'import_to_parent';
if($this->session->import_to_parent) $f->attr('value', $this->session->import_to_parent);
$form->add($f);
$f = $this->modules->get("InputfieldHidden");
$f->name = 'import_type';
if($this->session->import_type) $f->attr('value', $this->session->import_type);
$form->add($f);
$f = $this->modules->get("InputfieldHidden");
$f->name = 'import_components';
if($this->session->import_components) $f->attr('value', $this->session->import_components);
$form->add($f);
$f = $this->modules->get("InputfieldHidden");
$f->name = 'download_modules';
if($this->session->download_modules) $f->attr('value', $this->session->download_modules);
$form->add($f);
$f = $this->modules->get("InputfieldHidden");
$f->name = 'jsonFilename';
if($this->session->jsonFilename) $f->attr('value', $this->session->jsonFilename);
$form->add($f);
$this->addSubmit($form, 'Create Content');
return $form;
}
/**
* Process the "Import Step 2" form and upload the zip/json file
*
*/
protected function processImportForm2(InputfieldForm $form) {
$this->recursiveDelete($this->page->filesManager()->path(), false); //cleanup anything left in the Migrator assets/files directory from previous failed import
$form->processInput($this->input->post);
//$errors = $form->getErrors(true); used to delete automatic field errors since we want to provide custom ones
if(count($form->getErrors())) return false;
if($this->input->post){
//because these two are coming from InputForm3?, they have to use $this->input->post and not $form->get()->value
$this->session->import_fields = isset($this->input->post->import_fields) ? $this->input->post->import_fields : '';
$this->session->import_pages = isset($this->input->post->import_pages) ? $this->input->post->import_pages : '';
/*
$this->session->create_backup = $form->get('create_backup')->value;
$this->session->import_to_parent = (int) $form->get('import_to_parent')->value;
$this->session->import_to_parent = (int) $this->input->post->import_to_parent;
$this->session->import_components = $form->get('import_components')->value;
$this->session->import_components = $this->input->post->import_components;
$this->session->user_details = $form->get('user_details')->value;
$this->session->page_dates = $form->get('page_dates')->value;
$this->session->download_modules = $form->get('download_modules')->value;
$this->session->import_type = $form->get('import_type')->value;
if(isset($form->get('jsonFilename')->value)) $this->session->jsonFilename = $form->get('jsonFilename')->value;
$this->session->edit_imported_content = isset($form->get('import_fields')->value) ? $this->session->edit_imported_content : $form->get('edit_imported_content')->value;
*/
$this->session->create_backup = $this->input->post->create_backup;
$this->session->import_to_parent = (int) $this->input->post->import_to_parent;
$this->session->import_to_parent = (int) $this->input->post->import_to_parent;
$this->session->import_components = $this->input->post->import_components;
$this->session->import_components = $this->input->post->import_components;
$this->session->user_details = $this->input->post->user_details;
$this->session->page_dates = $this->input->post->page_dates;
$this->session->download_modules = $this->input->post->download_modules;
$this->session->import_type = $this->input->post->import_type;
if(isset($this->input->post->jsonFilename)) $this->session->jsonFilename = $this->input->post->jsonFilename;
$this->session->edit_imported_content = isset($this->input->post->import_fields) ? $this->session->edit_imported_content : $this->input->post->edit_imported_content;
}
if($this->session->create_backup == 1){
$backupDir = $this->config->paths->assets.'migratorbackups/'.date('Y-m-d_H-i-s');
if (!file_exists($this->config->paths->assets.'migratorbackups/')) mkdir($this->config->paths->assets.'migratorbackups/');
if (!file_exists($backupDir)) mkdir($backupDir);
$backup = new WireDatabaseBackup($backupDir.'/');
$backup->setDatabase($this->database);
$backup->setDatabaseConfig($this->config);
$file = $backup->backup(array('filename' => 'migratorbackup.sql'));
//copy templates and files directory to backup location
wireCopy($this->config->paths->templates, $backupDir . '/templates/', true);
wireCopy($this->config->paths->files, $backupDir . '/files/', true);
// remove uploaded file from the backup directory by emptying the files page folder connected with Migrator
// don't want this restored or we get an error when importing after restore because file already exists
$migratorClassFilesDir = str_replace($this->config->paths->assets, '', $this->page->filesManager()->path());
$this->recursiveDelete($backupDir . '/' . $migratorClassFilesDir, false);
}
if(!$this->session->import_to_parent && $this->session->import_components != 'fields_and_templates_only') {
if($this->session->migratorFilesDir && file_exists($this->session->migratorFilesDir)) $this->recursiveDelete($this->session->migratorFilesDir);
$this->error("Missing required parent page. This must be selected if you want to import the pages in addition to field and template creation.");
//$this->session->redirect('./'.$this->session->type);
return $form->render();
}
//for submission of form either without Edit Imported Content, or the first submission to get the fields/pages from the JSON file
if(!isset($form->get('import_fields')->value) || $form->get('import_fields')->value==''){
/*$this->session->zipFile = $form->get('zip_file')->value;
if($form->get('json_data')->value != '') $this->session->jsonData = $form->get('json_data')->value;
$this->session->jsonURL = $form->get('json_url')->value;*/
/*$zipFile = $form->get('zip_file')->value != '' ? $form->get('zip_file')->value : '';
$this->session->jsonPackage = $form->get('json_package')->value != '' ? $form->get('json_package')->value : $this->session->jsonPackage;
$this->session->jsonData = $form->get('json_data')->value != '' ? $form->get('json_data')->value : $this->session->jsonData;
$this->session->jsonURL = $form->get('json_url')->value != '' ? $form->get('json_url')->value : $this->session->jsonURL;*/
if($form->get('json_package')->value != ''){
$this->session->jsonPackage = $form->get('json_package')->value;
$this->session->remove('jsonData');
$this->session->remove('jsonURL');
$this->session->remove('zipFilename');
}
if($form->get('json_data')->value != ''){
$this->session->remove('jsonPackage');
$this->session->jsonData = $form->get('json_data')->value;
$this->session->remove('jsonURL');
$this->session->remove('zipFilename');
}
if($form->get('json_url')->value != ''){
$this->session->remove('jsonPackage');
$this->session->remove('jsonData');
$this->session->jsonURL = $form->get('json_url')->value;
$this->session->remove('zipFilename');
}
if($form->get('zip_file')->value != ''){
$this->session->remove('jsonPackage');
$this->session->remove('jsonData');
$this->session->remove('jsonURL');
$zipFile = $form->get('zip_file')->value;
//if(is_array($zipFile) && count($zipFile)>0){
$this->session->zipFile = $zipFile->first();
$this->session->zipFile->rename("data.zip");
$this->session->zipFilename = $this->session->zipFile->filename;
//}
}
$migratorClasses = json_decode($form->get('migrator_classes')->value);
if(is_array($migratorClasses)){
foreach($migratorClasses as $migratorClass) {
if($form->get('thirdparty_file_'.$migratorClass)->value == '') continue;
$this->session->remove('jsonPackage');
$this->session->remove('jsonData');
$this->session->remove('jsonURL');
$this->session->remove('thirdpartyFilename');
$thirdpartyFile = $form->get('thirdparty_file_'.$migratorClass)->value;
rename($this->page->filesManager()->path() . $thirdpartyFile, $this->page->filesManager()->path() . 'thirdpartydata.txt');
$this->session->thirdpartyFilename = $this->page->filesManager()->path() . 'thirdpartydata.txt';
$this->session->thirdpartyModule = $migratorClass;
}
}
/*if(is_array($zipFile) && count($zipFile)>0) {
$this->session->zipFile = $zipFile->first();
$this->session->zipFile->rename("data.zip");
$this->session->zipFilename = $this->session->zipFile->filename;*/
$this->session->migratorFilesDir = $this->page->filesManager()->path() . 'migratorfiles';
$this->session->jsonFilename = $this->session->migratorFilesDir . '/data.json';
if($this->session->zipFilename){
// extract uploaded zip to destination PW installation
$zip = new ZipArchive;
if($zip->open($this->session->zipFilename) === TRUE) {
$zip->extractTo($this->session->migratorFilesDir);
$zip->close();
unlink($this->session->zipFilename);
// set paths for moving files into the destination PW site's templates folder
$srcDir = $this->session->migratorFilesDir . '/templates/';
$destDir = $this->config->paths->templates.'/';
// check write permissions on templates directory and fail with friendly error
if(file_exists($srcDir) && !is_writable($destDir)){
if($this->session->migratorFilesDir && file_exists($this->session->migratorFilesDir)) $this->recursiveDelete($this->session->migratorFilesDir);
$this->error("There are template PHP files in your import, but the templates directory is not writeable. Please change permissions and try again.");
//$this->session->redirect('./'.$this->session->type);
$form->get('zip_file')->value = '';
return $form->render();
}
//move template and other helper files into the templates directory
if (file_exists($srcDir) && is_dir($srcDir) && $handle = opendir($srcDir)) {
foreach($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($srcDir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item){
$this->migratedTemplateFileNames[] = str_replace($this->session->migratorFilesDir, '', $item);
if ($item->isDir()) {
if(!file_exists($destDir . $iterator->getSubPathName())){
mkdir($destDir . str_replace("//", "/", $iterator->getSubPathName()));
}
}
else {
copy($item, $destDir . str_replace("//", "/", $iterator->getSubPathName()));
}
}
}
}
}
elseif(file_exists($this->session->migratorFilesDir)){
//no need to do anything since the directory of files already exists
//this would be the case when "Edit Imported Content" was selected.
}
else{
if($this->session->jsonData) {
$json = $this->session->jsonData;
}
elseif($this->session->jsonPackage) {
$json = file_get_contents($this->session->jsonPackage);
}
elseif($this->session->jsonURL) {
$json = file_get_contents($this->session->jsonURL);
}
elseif($this->session->thirdpartyFilename){
// loading the third party data
if (!file_exists($this->session->migratorFilesDir)) mkdir($this->session->migratorFilesDir);
// Load Thirdparty Migrator
$migrator = $this->modules->get($this->session->thirdpartyModule);
//convertToJson function must be defined in the 3rd party module
$json = $migrator->convertToJson($this->page->filesManager()->path() . '/thirdpartydata.txt');
$this->session->jsonData = $json;
//just for testing/debugging json
//file_put_contents($this->page->filesManager()->path() . '/thirdpartydata.json', $json);
// remove original third party data file
unlink($this->page->filesManager()->path() . '/thirdpartydata.txt');
}
else{
$this->error("Missing required ZIP or JSON Source");
if($this->session->migratorFilesDir && file_exists($this->session->migratorFilesDir)) $this->recursiveDelete($this->session->migratorFilesDir);
return $form->render();
}
if (!file_exists($this->session->migratorFilesDir)) mkdir($this->session->migratorFilesDir);
file_put_contents($this->session->jsonFilename, $json);
//exit;
}
//populate $fp with data from json file written to the server from pasted, or externally linked JSON file
$fp = file_get_contents($this->session->jsonFilename);
//if no data source provided, return an error. This check probably isn't necessary because of the ones above.
if(empty($fp)){
$this->error("Missing required ZIP or JSON Source");
if($this->session->migratorFilesDir && file_exists($this->session->migratorFilesDir)) $this->recursiveDelete($this->session->migratorFilesDir);
//$this->session->redirect('./'.$this->session->type);
return $form->render();
}
//populate $data with json string of all the content to be created
$data = json_decode($fp);
}
//if selected, redirect to form to allow user to determine which pages/fields get imported
if($this->input->post->edit_imported_content=='1'){
$form = $this->buildImportForm3($data);
return $form->render();
}
//now that we have been through both ImportForm 2 and 3, it's ok to delete the json.data file from the migratorfiles temp directory.
//unlink($this->session->jsonFilename);
//check fieldtypes of the fields to be installed against the available ones in the destination install before attempting to save a field with a type that isn't available.
//attempt to install it if it is available (core and those site modules that are downloaded but not installed)
//TODO: should maybe switch to $this->modules->getInstall() - https://processwire.com/talk/topic/6449-install-module-from-api-when-module-is-not-listed/?p=63127
//Maybe also use "isInstalled" to check first, although everything does seem to be working as is: https://processwire.com/talk/topic/6450-how-do-we-check-if-a-module-is-activated/?p=63126
$missing_fieldtypes = array();
foreach($data->fields as $np){
//automatically install language support if needed
if(strpos($np->type, 'Language') !== false){
$this->modules->get("LanguageSupport");
if(strpos($np->type, 'Fieldtype') !== false) $this->modules->get("LanguageSupportFields");
if(count($this->languages) < 2) $missing_fieldtypes[] = 'Missing additional language pack(s)';
}
if(!in_array($np->type, $this->fieldtypes->getArray()) && !$this->modules->get($np->type)){
if(!$this->downloadConfirm($np->type)) { // attempt to download and install. If not possible, then add to missing list error
$missing_fieldtypes[] = $np->type;
}
}
}