-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessDataMigrator.module.php
More file actions
1620 lines (1364 loc) · 65.2 KB
/
Copy pathProcessDataMigrator.module.php
File metadata and controls
1620 lines (1364 loc) · 65.2 KB
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
namespace ProcessWire;
require_once(__DIR__ . '/classes/parsers/AbstractParser.php');
require_once(__DIR__ . '/classes/parsers/SqlParser.php');
require_once(__DIR__ . '/classes/parsers/CsvParser.php');
require_once(__DIR__ . '/classes/parsers/JsonParser.php');
require_once(__DIR__ . '/classes/parsers/XmlParser.php');
require_once(__DIR__ . '/classes/DataAnalyzer.php');
require_once(__DIR__ . '/classes/TypeDetector.php');
require_once(__DIR__ . '/classes/MappingEngine.php');
require_once(__DIR__ . '/classes/TemplateCreator.php');
require_once(__DIR__ . '/classes/ImportProcessor.php');
require_once(__DIR__ . '/classes/ImportRollback.php');
require_once(__DIR__ . '/classes/Logger.php');
/**
* ProcessWire Data Migrator
*
* Migrate external data (SQL, CSV, JSON, XML) into ProcessWire
*
* @author frameless Media
* @version 1.1.2
*/
class ProcessDataMigrator extends Process implements Module, ConfigurableModule {
/**
* Module information
*/
public static function getModuleInfo() {
return [
'title' => 'Data Migrator',
'summary' => 'Migrate external data (SQL, CSV, JSON, XML) into ProcessWire',
'version' => '1.1.2',
'author' => 'ProcessWire',
'icon' => 'upload',
'permission' => 'data-migrate',
'permissions' => [
'data-migrate' => 'Migrate external data into ProcessWire'
],
'page' => [
'name' => 'data-migrator',
'parent' => 'setup',
'title' => 'Data Migrator'
],
'requires' => [
'PHP>=7.4',
'ProcessWire>=3.0.0'
],
];
}
/**
* Uploaded files directory
*/
protected $uploadsPath;
/**
* Session key for storing analysis data
*/
const SESSION_KEY = 'DataMigrator';
/**
* Maximum file upload size in bytes (50 MB)
* SECURITY: Prevents resource exhaustion attacks via large file uploads
*/
const MAX_FILE_SIZE = 52428800;
/**
* Initialize the module
*/
public function init() {
parent::init();
// Set uploads directory
$this->uploadsPath = $this->config->paths->cache . 'DataMigrator/';
if (!is_dir($this->uploadsPath)) {
wireMkdir($this->uploadsPath, true);
}
// Load CSS
$cssUrl = $this->config->urls->siteModules . 'ProcessDataMigrator/assets/css/data-migrator.css';
$this->config->styles->add($cssUrl);
}
/**
* Main execute method
*/
public function ___execute() {
// Check for actions first (GET or POST)
$action = $this->input->get('action') ?: $this->input->post('action');
if ($action) {
if ($action === 'clear') {
return $this->executeClear();
}
if ($action === 'dry_run' || $action === 'import') {
$sessionData = $this->session->get(self::SESSION_KEY);
// Store selected tables if submitted via POST
if ($this->input->post('selected_tables')) {
$selectedTables = $this->input->post->array('selected_tables');
$sessionData['selected_tables'] = $selectedTables;
}
// Store selected fields if submitted via POST (independent of selected_tables!)
// CRITICAL: Use $_POST directly - WireInput filters nested arrays!
$selectedFields = isset($_POST['fields']) ? $_POST['fields'] : null;
if ($selectedFields && is_array($selectedFields)) {
$sessionData['selected_fields'] = $selectedFields;
}
// Store fieldtype overrides if submitted via POST
// CRITICAL: Use $_POST directly - WireInput filters nested arrays!
$fieldtypeOverrides = isset($_POST['fieldtypes']) ? $_POST['fieldtypes'] : null;
if ($fieldtypeOverrides && is_array($fieldtypeOverrides)) {
$sessionData['fieldtype_overrides'] = $fieldtypeOverrides;
}
// Store FK table mappings
$fkTables = isset($_POST['fk_table']) ? $_POST['fk_table'] : null;
if ($fkTables && is_array($fkTables)) {
$fkMappings = [];
foreach ($fkTables as $tableName => $columns) {
foreach ($columns as $columnName => $refTable) {
if (!empty($refTable)) {
$fkMappings[$tableName][$columnName] = $refTable;
}
}
}
if (!empty($fkMappings)) {
$sessionData['fk_mappings'] = $fkMappings;
}
}
// Store title field overrides
$titleFields = isset($_POST['title_field']) ? $_POST['title_field'] : null;
if ($titleFields && is_array($titleFields)) {
$sessionData['title_field_overrides'] = [];
foreach ($titleFields as $tableName => $titleField) {
if (!empty($titleField)) {
$sessionData['title_field_overrides'][$tableName] = $titleField;
}
}
}
$this->session->set(self::SESSION_KEY, $sessionData);
// Route to dry run or actual import
if ($action === 'dry_run') {
return $this->executeDryRun();
} else {
return $this->executeImport();
}
}
if ($action === 'confirm_import') {
// Execute import with existing session data (after dry run confirmation)
return $this->executeImport();
}
if ($action === 'rollback') {
return $this->executeRollback();
}
}
// Check if we have session data (analysis results)
$sessionData = $this->session->get(self::SESSION_KEY);
if ($sessionData && isset($sessionData['step'])) {
// Continue from saved step
switch ($sessionData['step']) {
case 'analyze':
return $this->executeAnalyze();
case 'import':
return $this->executeImportResult();
default:
return $this->executeUpload();
}
}
return $this->executeUpload();
}
/**
* Step 1: Upload file
*/
protected function executeUpload() {
$this->headline('Data Migration - Upload');
// Build form first
$form = $this->buildUploadForm();
// Handle file upload via $_FILES
if ($this->input->post('submit_upload') && isset($_FILES['sql_file'])) {
// Process form to get other field values
$form->processInput($this->input->post);
$file = $_FILES['sql_file'];
// Validate upload with specific error messages
if ($file['error'] !== UPLOAD_ERR_OK) {
$uploadErrors = [
UPLOAD_ERR_INI_SIZE => sprintf(
$this->_('File exceeds PHP upload_max_filesize limit (%s). Please increase this value in php.ini or contact your administrator.'),
ini_get('upload_max_filesize')
),
UPLOAD_ERR_FORM_SIZE => $this->_('File exceeds maximum allowed form size'),
UPLOAD_ERR_PARTIAL => $this->_('File was only partially uploaded. Please try again.'),
UPLOAD_ERR_NO_FILE => $this->_('No file was selected for upload'),
UPLOAD_ERR_NO_TMP_DIR => $this->_('Server configuration error: Missing temporary folder'),
UPLOAD_ERR_CANT_WRITE => $this->_('Server error: Failed to write file to disk'),
UPLOAD_ERR_EXTENSION => $this->_('A PHP extension stopped the file upload'),
];
$errorMessage = $uploadErrors[$file['error']] ?? $this->_('File upload failed (unknown error)');
$this->error($errorMessage);
} else if ($file['size'] === 0) {
$this->error($this->_('File is empty'));
} else if ($file['size'] > self::MAX_FILE_SIZE) {
// SECURITY: Prevent resource exhaustion attacks via large file uploads
$maxMb = round(self::MAX_FILE_SIZE / 1048576);
$this->error(sprintf($this->_('File size exceeds maximum allowed size of %d MB'), $maxMb));
} else if (!preg_match('/\.(sql|csv|json|xml)$/i', $file['name'])) {
$this->error($this->_('Only .sql, .csv, .json, and .xml files are allowed'));
} else {
// Get form field values
$sampleSize = (int) $form->get('sample_size')->value;
$maxRows = (int) $form->get('max_rows')->value;
// Move to temp location - preserve original extension
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$tempFile = $this->uploadsPath . uniqid('import_') . '.' . $extension;
if (move_uploaded_file($file['tmp_name'], $tempFile)) {
// Process the file
$result = $this->processUpload($tempFile, $sampleSize, $maxRows);
if ($result['success']) {
// Store analysis in session
$this->session->set(self::SESSION_KEY, [
'step' => 'analyze',
'file' => $result['file'],
'temp_file' => $tempFile,
'analysis' => $result['analysis'],
'tables' => $result['tables'],
'max_rows' => $maxRows // Store for import limiting
]);
// Redirect to analysis
$this->session->redirect($this->page->url);
} else {
$this->error($result['error']);
// Clean up temp file
if (file_exists($tempFile)) {
unlink($tempFile);
}
}
} else {
$this->error($this->_('Failed to save uploaded file'));
}
}
}
return $form->render();
}
/**
* Step 2: Analyze and show results
*/
protected function executeAnalyze() {
$this->headline('Data Migration - Analyze');
$sessionData = $this->session->get(self::SESSION_KEY);
$analysis = $sessionData['analysis'] ?? [];
if (empty($analysis)) {
$this->session->redirect($this->page->url);
return;
}
// Pass session data to preserve user selections after errors/back from dry run
$out = $this->buildAnalysisView($analysis, $sessionData);
return $out;
}
/**
* Build upload form
*/
protected function buildUploadForm() {
$form = $this->modules->get('InputfieldForm');
$form->attr('method', 'post');
$form->attr('action', $this->page->url);
$form->attr('enctype', 'multipart/form-data');
// File upload - using Markup instead of InputfieldFile
$f = $this->modules->get('InputfieldMarkup');
$f->label = $this->_('Upload Data File');
$f->description = $this->_('Upload a data file to analyze and migrate');
$fileInput = '<div class="InputfieldContent">';
$fileInput .= '<input type="file" name="sql_file" accept=".sql,.csv,.json,.xml" required>';
$fileInput .= '<p class="description">' . $this->_('Supported formats: SQL, CSV, JSON, XML') . '</p>';
$fileInput .= '</div>';
$f->value = $fileInput;
$form->add($f);
// Options fieldset
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->label = $this->_('Migration Options');
$fieldset->collapsed = Inputfield::collapsedYes;
// Sample size
$f = $this->modules->get('InputfieldInteger');
$f->name = 'sample_size';
$f->label = $this->_('Sample Size');
$f->description = $this->_('Number of rows to analyze per table');
$f->value = 100;
$f->min = 10;
$f->max = 1000;
$fieldset->add($f);
// Max rows
$f = $this->modules->get('InputfieldInteger');
$f->name = 'max_rows';
$f->label = $this->_('Maximum Rows');
$f->description = $this->_('Maximum number of rows to migrate per table (0 = all)');
$f->value = 0;
$f->min = 0;
$fieldset->add($f);
$form->add($fieldset);
// Submit
$f = $this->modules->get('InputfieldSubmit');
$f->name = 'submit_upload';
$f->value = $this->_('Analyze File');
$f->icon = 'search';
$form->add($f);
return $form;
}
/**
* Process uploaded file
*/
protected function processUpload($filePath, $sampleSize = 100, $maxRows = 0) {
// Detect and initialize appropriate parser
$parser = $this->detectParser($filePath);
if (!$parser) {
return [
'success' => false,
'error' => 'File format not supported. Supported formats: SQL, CSV, JSON, XML'
];
}
// Parse file
$options = [
'sample_size' => $sampleSize,
'max_rows' => $maxRows,
];
try {
$tables = $parser->parse($filePath, $options);
if (empty($tables)) {
return [
'success' => false,
'error' => 'No data found in file'
];
}
// Analyze each table
$analyzer = new DataAnalyzer();
$analysis = [];
foreach ($tables as $tableName => $tableData) {
$analysis[$tableName] = $analyzer->analyze($tableData, $options);
}
return [
'success' => true,
'file' => basename($filePath),
'tables' => $tables,
'analysis' => $analysis,
'metadata' => $parser->getMetadata()
];
} catch (\Exception $e) {
return [
'success' => false,
'error' => 'Error parsing file: ' . $e->getMessage()
];
}
}
/**
* Detect and return appropriate parser for file
*
* @param string $filePath Path to file
* @return AbstractParser|null Parser instance or null if no suitable parser found
*/
protected function detectParser($filePath) {
// List of available parsers in priority order
$parsers = [
new CsvParser(),
new JsonParser(),
new XmlParser(),
new SqlParser(),
];
// Try each parser
foreach ($parsers as $parser) {
if ($parser->canParse($filePath)) {
$parserName = get_class($parser);
$parserName = str_replace('ProcessWire\\', '', $parserName);
$this->message($this->_("Using parser: {$parserName}"));
return $parser;
}
}
return null;
}
/**
* Build analysis view
*/
protected function buildAnalysisView($analysis, $sessionData = []) {
$allTableNames = array_keys($analysis);
$out = '<form method="post" action="' . $this->page->url . '">';
$out .= '<div class="data-migrator-analysis">';
// Summary
$totalRows = array_sum(array_column($analysis, 'row_count'));
$totalColumns = array_sum(array_map(function($table) {
return count($table['columns']);
}, $analysis));
$out .= '<div class="uk-alert uk-alert-success">';
$out .= '<h3>' . $this->_('Analysis Complete') . '</h3>';
$out .= '<p>';
$out .= sprintf(
$this->_('%d tables found - Select tables to migrate below'),
count($analysis)
);
$out .= '<br>';
$out .= sprintf(
$this->_('%d total rows and %d columns'),
$totalRows,
$totalColumns
);
$out .= '</p>';
$out .= '</div>';
// Tables
foreach ($analysis as $tableName => $tableAnalysis) {
$out .= $this->buildTableAnalysis($tableName, $tableAnalysis, $allTableNames, $sessionData);
}
// Add action buttons inside the form
$out .= $this->buildAnalysisActions();
$out .= '</div>';
$out .= '</form>';
return $out;
}
/**
* Get available fieldtypes for selection
*/
protected function getAvailableFieldtypes() {
return [
'FieldtypeText' => 'Text',
'FieldtypeTextarea' => 'Textarea',
'FieldtypeInteger' => 'Integer',
'FieldtypeFloat' => 'Float',
'FieldtypeCheckbox' => 'Checkbox',
'FieldtypeEmail' => 'Email',
'FieldtypeURL' => 'URL',
'FieldtypeDatetime' => 'Datetime',
'FieldtypeOptions' => 'Options/Select',
'FieldtypePage' => 'Page Reference *',
'FieldtypeImage' => 'Image **',
'FieldtypeFile' => 'File **',
'FieldtypePassword' => 'Password',
];
}
/**
* Build fieldtype selector dropdown
*/
protected function buildFieldtypeSelector($tableName, $columnName, $suggested, $sessionData = []) {
$fieldtypes = $this->getAvailableFieldtypes();
// Check if there's a fieldtype override from session data
$selectedFieldtype = $sessionData['fieldtype_overrides'][$tableName][$columnName] ?? $suggested;
// CRITICAL: Don't escape the square brackets in the name attribute!
// entities() would convert [ to [ which breaks POST array structure
$safeName = 'fieldtypes[' . $this->sanitizer->name($tableName) . '][' . $this->sanitizer->name($columnName) . ']';
$out = '<select name="' . $safeName . '" class="uk-select" style="font-size: 12px; padding: 2px 4px;">';
foreach ($fieldtypes as $type => $label) {
$selected = ($type === $selectedFieldtype) ? ' selected' : '';
$out .= '<option value="' . $this->sanitizer->entities($type) . '"' . $selected . '>' . $this->sanitizer->entities($label) . '</option>';
}
$out .= '</select>';
return $out;
}
/**
* Build single table analysis view
*/
protected function buildTableAnalysis($tableName, $analysis, $allTableNames = [], $sessionData = []) {
$out = '<div class="table-analysis uk-margin" style="border: 2px solid #ddd; padding: 15px; border-radius: 4px;">';
// Checkbox for table selection - restore from session if available
$isTableSelected = true; // Default: checked
if (isset($sessionData['selected_tables'])) {
// Session data exists, use it
$isTableSelected = in_array($tableName, $sessionData['selected_tables']);
}
$out .= '<div style="margin-bottom: 10px;">';
$out .= '<label style="font-size: 16px; font-weight: bold;">';
$out .= '<input type="checkbox" name="selected_tables[]" value="' . $this->sanitizer->entities($tableName) . '"' . ($isTableSelected ? ' checked' : '') . '> ';
$out .= $this->sanitizer->entities($tableName);
$out .= '</label>';
$out .= '</div>';
$out .= '<dl class="uk-description-list">';
$out .= '<dt>' . $this->_('Rows') . ':</dt>';
$out .= '<dd>' . number_format($analysis['row_count']) . '</dd>';
$out .= '<dt>' . $this->_('Columns') . ':</dt>';
$out .= '<dd>' . count($analysis['columns']) . '</dd>';
if ($analysis['suggested_template']) {
$out .= '<dt>' . $this->_('Suggested Template') . ':</dt>';
$out .= '<dd><code>' . $this->sanitizer->entities($analysis['suggested_template']) . '</code></dd>';
}
// Title field selector - allow manual selection
$out .= '<dt>' . $this->_('Title Field') . ':</dt>';
$out .= '<dd>';
// Get current selection from session or use suggested
$currentTitleField = $sessionData['title_field_overrides'][$tableName]
?? $analysis['suggested_title_field']
?? null;
// Build dropdown - show non-ID columns first, then ID columns as fallback
$out .= '<select name="title_field[' . $this->sanitizer->entities($tableName) . ']" class="uk-select" style="width: auto; min-width: 200px;">';
if (!$currentTitleField) {
$out .= '<option value="">-- ' . $this->_('Please select') . ' --</option>';
}
// Separate columns into non-ID and ID fields
$nonIdColumns = [];
$idColumns = [];
foreach ($analysis['columns'] as $column) {
if ($column['is_likely_id']) {
$idColumns[] = $column;
} else {
$nonIdColumns[] = $column;
}
}
// First: show non-ID columns (preferred)
foreach ($nonIdColumns as $column) {
$selected = ($column['name'] === $currentTitleField) ? ' selected' : '';
$label = $this->sanitizer->entities($column['name']);
// Add type hint
$typeHint = $column['base_type'] ?? 'unknown';
$label .= ' (' . $typeHint . ')';
// Mark suggested field
if ($column['name'] === $analysis['suggested_title_field']) {
$label .= ' *';
}
$out .= '<option value="' . $this->sanitizer->entities($column['name']) . '"' . $selected . '>' . $label . '</option>';
}
// Then: show ID columns as fallback (for junction tables etc.)
if (!empty($idColumns)) {
if (!empty($nonIdColumns)) {
$out .= '<option disabled>───────────────</option>';
}
foreach ($idColumns as $column) {
$selected = ($column['name'] === $currentTitleField) ? ' selected' : '';
$label = $this->sanitizer->entities($column['name']);
$typeHint = $column['base_type'] ?? 'unknown';
$label .= ' (' . $typeHint . ', ID)';
$out .= '<option value="' . $this->sanitizer->entities($column['name']) . '"' . $selected . '>' . $label . '</option>';
}
}
$out .= '</select>';
if (!$currentTitleField) {
$out .= ' <span style="color: #c00; font-weight: bold;">' . $this->_('Required!') . '</span>';
}
$out .= '</dd>';
$out .= '</dl>';
// Columns table
$out .= '<table class="uk-table uk-table-striped uk-table-small">';
$out .= '<thead>';
$out .= '<tr>';
$out .= '<th style="width: 30px;">' . $this->_('Migrate') . '</th>';
$out .= '<th>' . $this->_('Column') . '</th>';
$out .= '<th>' . $this->_('Detected Type') . '</th>';
$out .= '<th style="min-width: 250px;">' . $this->_('Suggested Fieldtype') . '</th>';
$out .= '<th>' . $this->_('Confidence') . '</th>';
$out .= '<th>' . $this->_('Sample Values') . '</th>';
$out .= '</tr>';
$out .= '</thead>';
$out .= '<tbody>';
foreach ($analysis['columns'] as $column) {
$columnName = $column['name'];
$isIdField = $column['is_likely_id'];
$isTitleField = ($columnName === $analysis['suggested_title_field']);
// Show FK dropdown for all integer fields (except main ID field)
// User decides which fields are actually foreign keys
$isPotentialFk = (
in_array($column['detected_type'], ['integer', 'int']) &&
!$isIdField // Not the main ID field
);
// Checkbox: restore from session if available, otherwise default (checked except for ID fields)
$isFieldSelected = !$isIdField; // Default: checked if not ID field
if (isset($sessionData['selected_fields'][$tableName])) {
// Session data exists, use it
$isFieldSelected = in_array($columnName, $sessionData['selected_fields'][$tableName]);
}
$checked = $isFieldSelected ? ' checked' : '';
// Title field is required, so make it disabled but checked
$disabled = $isTitleField ? ' disabled checked' : '';
$out .= '<tr>';
$out .= '<td>';
$out .= '<input type="checkbox" name="fields[' . $tableName . '][]" value="' . $columnName . '"' . $checked . $disabled . '>';
if ($disabled) {
$out .= '<input type="hidden" name="fields[' . $tableName . '][]" value="' . $columnName . '">';
}
$out .= '</td>';
$out .= '<td><strong>' . $this->sanitizer->entities($columnName) . '</strong>';
if ($column['is_likely_id']) {
$out .= ' <span class="uk-badge">ID</span>';
}
if ($column['name'] === $analysis['suggested_title_field']) {
$out .= ' <span class="uk-badge uk-badge-success">Title</span>';
}
$out .= '</td>';
$out .= '<td>' . $this->sanitizer->entities($column['detected_type']) . '</td>';
// Fieldtype + FK combined in one cell
$out .= '<td style="white-space: nowrap;">';
$out .= '<div style="display: flex; align-items: center; gap: 8px;">';
$out .= $this->buildFieldtypeSelector($tableName, $columnName, $column['suggested_fieldtype'], $sessionData);
// Add FK dropdown inline for potential FK fields (integer fields, not ID)
if ($isPotentialFk) {
// Check if there's an FK mapping from session data
$selectedFkTable = $sessionData['fk_mappings'][$tableName][$columnName] ?? '';
$out .= '<span style="color: #666; font-size: 11px;">FK:</span>';
$out .= '<select name="fk_table[' . $this->sanitizer->name($tableName) . '][' . $this->sanitizer->name($columnName) . ']" ';
$out .= 'class="uk-select" style="font-size: 12px; padding: 2px 6px; width: auto; min-width: 100px;">';
$out .= '<option value="">--</option>';
foreach ($allTableNames as $tbl) {
$selected = ($tbl === $selectedFkTable) ? ' selected' : '';
$out .= '<option value="' . $this->sanitizer->entities($tbl) . '"' . $selected . '>' . $this->sanitizer->entities($tbl) . '</option>';
}
$out .= '</select>';
}
$out .= '</div>';
$out .= '</td>';
// Confidence with color
$confidence = $column['detection_confidence'];
$color = $confidence >= 80 ? 'success' : ($confidence >= 60 ? 'warning' : 'danger');
$out .= '<td><span class="uk-text-' . $color . '">' . $confidence . '%</span></td>';
// Sample values
$samples = array_slice($column['sample_values'], 0, 3);
$samplesHtml = array_map(function($v) {
$v = $this->sanitizer->entities((string) $v);
return strlen($v) > 30 ? substr($v, 0, 30) . '...' : $v;
}, $samples);
$out .= '<td><small>' . implode(', ', $samplesHtml) . '</small></td>';
$out .= '</tr>';
}
$out .= '</tbody>';
$out .= '</table>';
$out .= '</div>';
return $out;
}
/**
* Build analysis action buttons
*/
protected function buildAnalysisActions() {
$out = '<div class="uk-margin">';
// Dry Run button (recommended)
$out .= '<button type="submit" name="action" value="dry_run" class="ui-button ui-priority-primary">';
$out .= '<i class="fa fa-eye"></i> ' . $this->_('Preview Migration (Dry Run)');
$out .= '</button>';
$out .= ' ';
// Direct import button (skip preview)
$out .= '<button type="submit" name="action" value="import" class="ui-button ui-priority-secondary">';
$out .= '<i class="fa fa-upload"></i> ' . $this->_('Migrate Now (Skip Preview)');
$out .= '</button>';
$out .= ' ';
// Clear session button
$out .= '<a href="' . $this->page->url . '?action=clear" class="ui-button ui-priority-secondary">';
$out .= '<i class="fa fa-arrow-left"></i> ' . $this->_('Start Over');
$out .= '</a>';
$out .= '</div>';
return $out;
}
/**
* Build dry run confirmation screen
*/
protected function buildDryRunConfirmation($dryRunResult) {
$out = '<div class="uk-container">';
// Success alert
$out .= '<div class="uk-alert uk-alert-success" style="margin: 20px 0;">';
$out .= '<h3 style="margin-top: 0;"><i class="fa fa-check-circle"></i> ' . $this->_('Dry Run Complete - Preview Results') . '</h3>';
$out .= '<p>' . $this->_('The following changes will be made when you execute the migration:') . '</p>';
$out .= '</div>';
// Summary boxes
$out .= '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0;">';
// Templates count
$templateCount = count($dryRunResult['templates']);
$out .= '<div style="background: #f8f9fa; border-left: 4px solid #3B82F6; padding: 15px;">';
$out .= '<div style="font-size: 24px; font-weight: bold; color: #3B82F6;">' . $templateCount . '</div>';
$out .= '<div style="color: #666;">' . $this->_('Templates') . '</div>';
$out .= '</div>';
// Fields count
$fieldsCount = count($dryRunResult['fields']);
$out .= '<div style="background: #f8f9fa; border-left: 4px solid #10B981; padding: 15px;">';
$out .= '<div style="font-size: 24px; font-weight: bold; color: #10B981;">' . $fieldsCount . '</div>';
$out .= '<div style="color: #666;">' . $this->_('Fields') . '</div>';
$out .= '</div>';
// Pages count
$pagesCount = $dryRunResult['pages_count'];
$out .= '<div style="background: #f8f9fa; border-left: 4px solid #F59E0B; padding: 15px;">';
$out .= '<div style="font-size: 24px; font-weight: bold; color: #F59E0B;">' . number_format($pagesCount) . '</div>';
$out .= '<div style="color: #666;">' . $this->_('Pages') . '</div>';
$out .= '</div>';
// FK relationships count
$fkCount = count($dryRunResult['fk_relationships']);
$out .= '<div style="background: #f8f9fa; border-left: 4px solid #8B5CF6; padding: 15px;">';
$out .= '<div style="font-size: 24px; font-weight: bold; color: #8B5CF6;">' . $fkCount . '</div>';
$out .= '<div style="color: #666;">' . $this->_('FK Relationships') . '</div>';
$out .= '</div>';
$out .= '</div>';
// Details sections
$out .= '<div style="margin: 30px 0;">';
// Templates list
if (!empty($dryRunResult['templates'])) {
$out .= '<h4>' . $this->_('Templates to be created:') . '</h4>';
$out .= '<ul>';
foreach ($dryRunResult['templates'] as $template) {
$out .= '<li><code>' . $this->sanitizer->entities($template) . '</code></li>';
}
$out .= '</ul>';
}
// Pages breakdown per table
if (!empty($dryRunResult['tables_breakdown'])) {
$out .= '<h4>' . $this->_('Pages per table:') . '</h4>';
$out .= '<ul>';
foreach ($dryRunResult['tables_breakdown'] as $table => $count) {
$out .= '<li><strong>' . $this->sanitizer->entities($table) . '</strong>: ' . number_format($count) . ' ' . $this->_('pages') . '</li>';
}
$out .= '</ul>';
}
// FK relationships
if (!empty($dryRunResult['fk_relationships'])) {
$out .= '<h4>' . $this->_('Foreign Key Relationships:') . '</h4>';
$out .= '<ul>';
foreach ($dryRunResult['fk_relationships'] as $relationship) {
$out .= '<li>' . $this->sanitizer->entities($relationship) . '</li>';
}
$out .= '</ul>';
}
$out .= '</div>';
// Action buttons
$out .= '<form method="post" action="' . $this->page->url . '" style="margin: 30px 0;">';
$out .= '<input type="hidden" name="action" value="confirm_import">';
$out .= '<button type="submit" class="ui-button ui-priority-primary" style="font-size: 16px; padding: 10px 20px;">';
$out .= '<i class="fa fa-check"></i> ' . $this->_('Execute Migration Now');
$out .= '</button>';
$out .= ' ';
$out .= '<a href="' . $this->page->url . '" class="ui-button ui-priority-secondary">';
$out .= '<i class="fa fa-arrow-left"></i> ' . $this->_('Back to Edit Configuration');
$out .= '</a>';
$out .= '</form>';
$out .= '</div>';
return $out;
}
/**
* Detect circular dependencies in dependency graph
* Returns array of nodes in cycle, or null if no cycle found
*/
protected function detectCycle($dependencies) {
$visited = [];
$recursionStack = [];
foreach (array_keys($dependencies) as $node) {
if (!isset($visited[$node])) {
$cycle = $this->detectCycleDFS($node, $dependencies, $visited, $recursionStack, []);
if ($cycle !== null) {
return $cycle;
}
}
}
return null;
}
/**
* DFS helper for cycle detection
*/
protected function detectCycleDFS($node, $dependencies, &$visited, &$recursionStack, $path) {
$visited[$node] = true;
$recursionStack[$node] = true;
$path[] = $node;
if (isset($dependencies[$node])) {
foreach ($dependencies[$node] as $neighbor) {
if (!isset($visited[$neighbor])) {
$cycle = $this->detectCycleDFS($neighbor, $dependencies, $visited, $recursionStack, $path);
if ($cycle !== null) {
return $cycle;
}
} elseif (isset($recursionStack[$neighbor])) {
// Found a cycle - extract it from path
$cycleStart = array_search($neighbor, $path);
return array_slice($path, $cycleStart);
}
}
}
unset($recursionStack[$node]);
return null;
}
/**
* Sort tables by FK dependencies using topological sort
* Throws exception if circular dependencies are detected
*/
protected function sortTablesByDependencies($tables, $fkMappings) {
if (empty($fkMappings)) {
return $tables;
}
$dependencies = [];
$sorted = [];
$visited = [];
// Build dependency graph
foreach ($tables as $table) {
$dependencies[$table] = [];
if (isset($fkMappings[$table])) {
foreach ($fkMappings[$table] as $column => $refTable) {
if (in_array($refTable, $tables) && $refTable !== $table) {
$dependencies[$table][] = $refTable;
}
}
}
}
// CYCLE DETECTION: Check for circular dependencies before sorting
$cycle = $this->detectCycle($dependencies);
if ($cycle !== null) {
$cycleStr = implode(' → ', $cycle) . ' → ' . $cycle[0];
throw new \Exception(sprintf(
$this->_('Circular Foreign Key dependency detected: %s. Please remove one of the FK mappings to break the cycle.'),
$cycleStr
));
}
// Topological sort using DFS
$visit = function($table) use (&$visit, &$visited, &$sorted, $dependencies) {
if (isset($visited[$table])) {
return;
}
$visited[$table] = true;
foreach ($dependencies[$table] as $dep) {
$visit($dep);
}
// Append (not prepend) to get correct dependency order
$sorted[] = $table;
};
foreach ($tables as $table) {
$visit($table);
}
return $sorted;
}
/**
* Execute dry run (preview without actual import)
*/
protected function executeDryRun() {
$this->headline('Data Migration - Dry Run Preview');
// Get session data
$sessionData = $this->session->get(self::SESSION_KEY);
if (!$sessionData || !isset($sessionData['analysis'])) {
$this->error($this->_('No analysis data found. Please start over.'));
$this->session->redirect($this->page->url);
}
// Get all tables data
$allAnalysis = $sessionData['analysis'] ?? [];
$allTables = $sessionData['tables'] ?? [];
if (empty($allAnalysis) || empty($allTables)) {
$this->error($this->_('No table data found in session. Please start over.'));
$this->session->redirect($this->page->url);
}
// Get selected tables
$selectedTables = $sessionData['selected_tables'] ?? array_keys($allAnalysis);
if (empty($selectedTables)) {
$this->error($this->_('No tables selected for migration.'));
$this->session->redirect($this->page->url);
}
// Get FK mappings
$fkMappings = $sessionData['fk_mappings'] ?? [];
// Sort tables by dependencies
if (!empty($fkMappings)) {
try {
$sortedTables = $this->sortTablesByDependencies($selectedTables, $fkMappings);
$selectedTables = $sortedTables;
} catch (\Exception $e) {
// Circular FK dependency detected - show error and return to analysis view
$this->error($e->getMessage());
$this->error($this->_('Please uncheck one of the FK dropdowns in the cycle to break the circular dependency, then try again.'));
return $this->executeAnalyze();
}
}