-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdater
1143 lines (982 loc) · 37.3 KB
/
updater
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
final class Updater
{
const VERSION = '0.1.5';
const LAYOUT_SIZE = 70;
const BOX_STYLES = [
// 0 1 2 3 4 5 6 7
'thin' => ["┌", "┐", "└", "┘", "─", "│", "├", "┤"],
'doubled' => ["╔", "╗", "╚", "╝", "═", "║", "╠", "╣"],
];
const LOCAL_VERSION_LIST = __DIR__.'/tmp/versionList.php';
const LOCAL_VERSION_FILE = __DIR__.'/galastri/VERSION';
const REMOTE_VERSION_LIST = 'https://raw.githubusercontent.com/andregalastri/galastri-framework-updates/main/versionList.php';
const LOCAL_TMP_PATH = __DIR__.'/tmp';
const LOCAL_PACKAGE_PATH = __DIR__.'/tmp/packages';
const LOCAL_BACKUP_PATH = __DIR__.'/tmp/backup';
const LOCAL_WORKING_FOLDER = __DIR__.'/tmp/working';
const REMOTE_PACKAGE_URL = 'https://github.com/andregalastri/galastri-framework-updates/raw/main/updates';
private static bool $restoreBackupStatus;
/**
* This is a singleton class, the __construct() method is private to avoid users to instanciate
* it.
*
* @return void
*/
private function __construct()
{
}
/**
* prepare
*
* @return void
*/
private static function prepare()
{
self::isWritable(__DIR__);
self::isWritable(__DIR__.'/galastri');
if (!file_exists(self::LOCAL_VERSION_FILE)) {
self::drawMessageBox(Language::text('NO_VERSION_FILE', 0), Language::text('NO_VERSION_FILE', 1));
self::pressEnterToContinue();
exit;
}
if (!file_exists(self::LOCAL_TMP_PATH)) {
mkdir(self::LOCAL_TMP_PATH);
}
self::isWritable(self::LOCAL_TMP_PATH);
if (!file_exists(self::LOCAL_BACKUP_PATH)) {
mkdir(self::LOCAL_BACKUP_PATH);
}
self::isWritable(self::LOCAL_BACKUP_PATH);
if (!file_exists(self::LOCAL_PACKAGE_PATH)) {
mkdir(self::LOCAL_PACKAGE_PATH);
}
self::isWritable(self::LOCAL_PACKAGE_PATH);
self::$restoreBackupStatus = false;
}
/**
* isWritable
*
* @param mixed $fileOrDirectory
* @return void
*/
private static function isWritable($fileOrDirectory): void
{
if (!is_writable($fileOrDirectory)) {
self::drawMessageBox(Language::text('NO_WRITTING_PERMISION', 0), '', $fileOrDirectory, '', Language::text('NO_WRITTING_PERMISION', 1));
self::pressEnterToContinue();
exit;
}
}
/**
* execute
*
* @return void
*/
public static function execute(): void
{
self::prepare();
do {
self::drawMainWindow();
$option = readline(Language::text('CHOOSE_A_OPTION', 0));
echo "\n\n\n";
switch($option) {
case 0:
self::drawMessageBox(Language::text('EXIT', 0), Language::text('EXIT', 1));
self::wait(1, false);
exit();
case 1:
self::checkUpdates();
break;
case 2:
self::checkBackups();
break;
default:
self::drawMessageBox(Language::text('MAIN_INVALID_OPTION', 0).$option.Language::text('MAIN_INVALID_OPTION', 1));
self::pressEnterToContinue();
}
} while($option != 0);
}
/**
* checkBackups
*
* @return void
*/
private static function checkBackups(): void
{
$backupList = [];
foreach(array_reverse(glob(self::LOCAL_BACKUP_PATH.'/*', GLOB_ONLYDIR)) as $key => $backupPath) {
$backupName = str_replace(self::LOCAL_BACKUP_PATH.'/', '', $backupPath);
$backupData = explode('_', $backupName);
$date = (\Datetime::createFromFormat('YmdHis', $backupData[0]))->format('Y-m-d, H:i:s');
$backupLabel = ($key+1).'. '.self::stringpad($date, 15, ' ').' | v'.$backupData[1];
$backupList[] = [
'path' => $backupPath,
'label' => $backupLabel,
];
}
if (count($backupList) <= 0) {
self::drawMessageBox(Language::text('NO_BACKUP_FOUND', 0), ':(');
} else {
do {
self::drawBackupWindow($backupList);
echo Language::text('CHOOSE_BACKUP_RESTORATION', 0);
$key = readline(Language::text('CHOOSE_BACKUP_RESTORATION', 1));
if ($key == 0) {
self::drawMessageBox(Language::text('CANCEL_BACKUP_RESTORATION', 0), Language::text('CANCEL_BACKUP_RESTORATION', 1));
} else {
if (array_key_exists($key-1, $backupList)) {
self::drawMessageBox(Language::text('CONFIRM_BACKUP_RESTORAION', 0), '', $backupList[$key-1]['label']);
$confirm = readline(Language::text('CONFIRM_BACKUP_RESTORAION', 1));
switch($confirm){
case 'y':
case 'Y':
case 's':
case 'S':
self::executeRestore($backupList, $key-1);
break;
default:
self::drawMessageBox(Language::text('CANCEL_BACKUP_RESTORATION', 0), Language::text('CANCEL_BACKUP_RESTORATION', 1));
}
self::$restoreBackupStatus = true;
} else {
self::drawMessageBox(Language::text('INVALID_BACKUP_OPTION', 0));
self::pressEnterToContinue();
}
}
} while($key != 0 and self::$restoreBackupStatus != true);
}
self::pressEnterToContinue();
}
/**
* checkUpdates
*
* @return void
*/
private static function checkUpdates(): void
{
$currentVersion = trim(file_get_contents(self::LOCAL_VERSION_FILE));
self::drawMessageBox(Language::text('CHECKING_UPDATES', 0));
file_put_contents(self::LOCAL_VERSION_LIST, file_get_contents(self::REMOTE_VERSION_LIST));
$versionList = require(self::LOCAL_VERSION_LIST);
$versionPosition = array_search($currentVersion, $versionList);
if ($versionPosition === false) {
self::drawMessageBox(
Language::text('INVALID_VERSION', 0).$currentVersion.Language::text('INVALID_VERSION', 1),
':(',
'',
Language::text('INVALID_VERSION', 2)
);
} else {
if ($versionPosition == array_key_last($versionList)) {
self::drawMessageBox(
Language::text('UP_TO_DATE_VERSION', 0),
'',
Language::text('UP_TO_DATE_VERSION', 1).$currentVersion.Language::text('UP_TO_DATE_VERSION', 2),
':D'
);
} else {
self::wait(2, false);
$packageQty = 0;
foreach ($versionList as $i => $version) {
if ($i <= $versionPosition) continue;
$packageQty++;
$lastVersion = $version;
}
self::drawUpdateWindow($currentVersion, $packageQty, $lastVersion);
$option = readline(Language::text('CONFIRM_UPDATE', 0));
switch($option){
case 'y':
case 'Y':
case 's':
case 'S':
self::executeUpdate($versionList, $versionPosition, $packageQty);
break;
default:
self::drawMessageBox(Language::text('CANCEL_UPDATE', 0), Language::text('CANCEL_UPDATE', 1));
}
}
}
self::pressEnterToContinue();
}
/**
* executeRestore
*
* @param mixed $backupPath
* @return void
*/
private static function executeRestore(array $backupList, int $restorePoint)
{
self::drawMessageBox(Language::text('RESTORING_BACKUP', 0));
self::wait(5, true, false);
echo "\n";
self::draw('doubled', 'top');
foreach($backupList as $backupPoint => $backupData) {
if ($backupPoint <= $restorePoint) {
$backupFolder = $backupData['path'];
self::text('doubled', Language::text('RESTORING_BACKUP_PROCESS', 0).$backupData['label']);
$currentVersion = trim(file_get_contents(self::LOCAL_VERSION_FILE));
$workingFiles = require($backupFolder.'/changes/deleted-files.php');
foreach($workingFiles as $file) {
self::copyFile($backupFolder.'/'.$file, __DIR__.'/'.$file);
}
$workingFiles = require($backupFolder.'/changes/new-files.php');
foreach($workingFiles as $file) {
unlink(__DIR__.'/'.$file);
}
$workingFiles = require($backupFolder.'/changes/modified-files.php');
foreach($workingFiles as $file) {
self::copyFile($backupFolder.'/'.$file, __DIR__.'/'.$file);
}
self::deleteAll($backupFolder);
}
}
self::draw('doubled', 'bottom');
self::wait(2, false, false);
echo "\n";
self::drawMessageBox(Language::text('BACKUP_RESTORED', 0));
}
/**
* executeUpdate
*
* @param mixed $versionList
* @param mixed $versionPosition
* @param mixed $packageQty
* @return void
*/
private static function executeUpdate(array $versionList, int $versionPosition, int $packageQty): void
{
self::drawMessageBox(Language::text('STARTING_UPDATE', 0));
self::wait(5, true, false);
echo "\n";
$packageNumber = 1;
$lastVersion = '';
self::draw('doubled', 'top');
foreach ($versionList as $i => $version) {
$currentVersion = trim(file_get_contents(self::LOCAL_VERSION_FILE));
if ($i <= $versionPosition) continue;
if ($packageNumber > 1) {
self::draw('doubled', 'line');
}
if (!file_exists(self::LOCAL_WORKING_FOLDER)) {
mkdir(self::LOCAL_WORKING_FOLDER);
}
$packageTarFile = $version.'.tar';
$packageTarPath = self::LOCAL_WORKING_FOLDER.'/'.$packageTarFile;
self::text('doubled', Language::text('UPDATE_PROCESS', 0).$version.'" ('.$packageNumber.'/'.$packageQty.')');
file_put_contents($packageTarPath, file_get_contents(self::REMOTE_PACKAGE_URL.'/'.$packageTarFile));
self::text('doubled', Language::text('UPDATE_PROCESS', 1));
(new \PharData($packageTarPath))->extractTo(self::LOCAL_WORKING_FOLDER);
unlink($packageTarPath);
$packageFolder = self::LOCAL_PACKAGE_PATH.'/'.$version;
if (file_exists($packageFolder)) {
self::deleteAll($packageFolder);
}
self::copyDirectory(self::LOCAL_WORKING_FOLDER.'/'.$version, self::LOCAL_PACKAGE_PATH.'/'.$version);
self::deleteAll(self::LOCAL_WORKING_FOLDER);
$backupFolder = self::LOCAL_BACKUP_PATH.'/'.date('YmdHis_').$currentVersion;
if (!file_exists($backupFolder)) {
mkdir($backupFolder);
}
self::copyFile($packageFolder.'/deleted-files.php', $backupFolder.'/changes/deleted-files.php');
self::copyFile($packageFolder.'/new-files.php', $backupFolder.'/changes/new-files.php');
self::copyFile($packageFolder.'/modified-files.php', $backupFolder.'/changes/modified-files.php');
self::text('doubled', Language::text('UPDATE_PROCESS', 2));
$workingFiles = require($packageFolder.'/deleted-files.php');
foreach($workingFiles as $file) {
self::copyFile(__DIR__.'/'.$file, $backupFolder.'/'.$file);
unlink(__DIR__.'/'.$file);
}
$workingFiles = require($packageFolder.'/new-files.php');
foreach($workingFiles as $file) {
self::copyFile($packageFolder.'/'.$file, __DIR__.'/'.$file);
}
$workingFiles = require($packageFolder.'/modified-files.php');
foreach($workingFiles as $file) {
self::copyFile(__DIR__.'/'.$file, $backupFolder.'/'.$file);
self::copyFile($packageFolder.'/'.$file, __DIR__.'/'.$file);
}
$newUpdater = $packageFolder.'/updater';
if (file_exists($newUpdater)) {
self::draw('doubled', 'bottom');
self::drawMessageBox(Language::text('UPDATE_DONE', 1).$version);
self::drawMessageBox(
Language::text('UPDATER_UPDATED', 0),
Language::text('UPDATER_UPDATED', 1),
'',
Language::text('UPDATER_UPDATED', 2)
);
self::pressEnterToContinue();
exit;
} else {
$packageNumber++;
$lastVersion = $version;
}
self::wait(2, false, false);
}
self::draw('doubled', 'bottom');
self::drawMessageBox(Language::text('UPDATE_DONE', 0), Language::text('UPDATE_DONE', 1).$lastVersion);
}
/**
* pressEnterToContinue
*
* @return void
*/
private static function pressEnterToContinue(): void
{
readline(Language::text('PRESS_ENTER_TO_CONTINUE', 0));
echo "\n\n\n";
}
/**
* wait
*
* @param mixed $seconds
* @param mixed $writeDots
* @param mixed $longJump
* @return void
*/
private static function wait(int $seconds, bool $writeDots = true, bool $longJump = true): void
{
for ($i = 0; $i < $seconds; $i++) {
echo $writeDots ? '.' : '';
sleep(1);
}
echo $longJump ? "\n\n\n" : '';
}
/**
* drawMessageBox
*
* @param mixed $messages
* @return void
*/
private static function drawMessageBox(string ...$messages): void
{
self::draw('doubled', 'top');
foreach($messages as $message) {
self::text('doubled', $message, 'center');
}
self::draw('doubled', 'bottom');
}
/**
* drawMainWindow
*
* @return void
*/
private static function drawMainWindow(): void
{
self::draw('doubled', 'top');
self::text('doubled', 'GALASTRI FRAMEWORK UPDATER', 'center');
self::text('doubled', 'v'.self::VERSION, 'center');
self::draw('doubled', 'bottom');
self::text('thin', Language::text('WELCOME_WINDOW', 0), 'center');
self::draw('thin', 'line');
self::text('thin', Language::text('WELCOME_WINDOW', 1));
self::draw('thin', 'empty');
self::text('thin', Language::text('WELCOME_WINDOW', 2));
self::text('thin', Language::text('WELCOME_WINDOW', 3));
self::draw('thin', 'empty');
self::text('thin', Language::text('WELCOME_WINDOW', 4));
self::draw('thin', 'bottom');
}
/**
* drawUpdateWindow
*
* @param mixed $currentVersion
* @param mixed $packageQty
* @param mixed $lastVersion
* @return void
*/
private static function drawUpdateWindow(string $currentVersion, int $packageQty, string $lastVersion): void
{
$headerText = $packageQty > 1 ? Language::text('UPDATE_WINDOW_HEADER', 0).$packageQty.Language::text('UPDATE_WINDOW_HEADER', 1) : Language::text('UPDATE_WINDOW_HEADER', 2);
self::draw('doubled', 'top');
self::text('doubled', $headerText, 'center');
self::draw('doubled', 'bottom');
self::text('thin', Language::text('UPDATE_WINDOW_VERSIONS', 0).$currentVersion);
self::text('thin', Language::text('UPDATE_WINDOW_VERSIONS', 1).$lastVersion);
self::draw('thin', 'line');
self::text('thin', Language::text('UPDATE_WINDOW_ABOUT', 0));
self::draw('thin', 'empty');
self::text('thin', Language::text('UPDATE_WINDOW_ABOUT', 1));
self::draw('thin', 'empty');
self::text('thin', Language::text('UPDATE_WINDOW_ABOUT', 2));
self::draw('thin', 'empty');
self::text('thin', Language::text('UPDATE_WINDOW_ABOUT', 3));
self::draw('thin', 'line');
self::text('thin', Language::text('UPDATE_WINDOW_ABOUT', 4), 'center');
self::text('thin', Language::text('UPDATE_WINDOW_ABOUT', 5), 'center');
self::draw('thin', 'bottom');
}
/**
* drawBackupWindow
*
* @param mixed $backupList
* @return void
*/
private static function drawBackupWindow(array $backupList): void
{
$backupQty = count($backupList);
$headerText = $backupQty > 1 ? Language::text('BACKUP_WINDOW_HEADER', 0).$backupQty.Language::text('BACKUP_WINDOW_HEADER', 1) : Language::text('BACKUP_WINDOW_HEADER', 2);
self::draw('doubled', 'top');
self::text('doubled', $headerText, 'center');
self::draw('doubled', 'bottom');
foreach($backupList as $backupData) {
self::text('thin', $backupData['label']);
}
self::draw('thin', 'line');
self::text('thin', Language::text('BACKUP_WINDOW_ABOUT', 0));
self::draw('thin', 'empty');
self::text('thin', Language::text('BACKUP_WINDOW_ABOUT', 1));
self::draw('thin', 'empty');
self::text('thin', Language::text('BACKUP_WINDOW_ABOUT', 2));
self::draw('thin', 'empty');
self::text('thin', Language::text('BACKUP_WINDOW_ABOUT', 3));
self::draw('thin', 'empty');
self::text('thin', Language::text('BACKUP_WINDOW_ABOUT', 4));
self::draw('thin', 'line');
self::text('thin', Language::text('BACKUP_WINDOW_ABOUT', 5), 'center');
self::draw('thin', 'bottom');
}
/**
* text
*
* @param mixed $style
* @param mixed $message
* @param mixed $align
* @return void
*/
private static function text(string $style, string $message, string $align = 'left'): void
{
$textMaxSize = self::LAYOUT_SIZE - 2;
if (mb_strlen($message) <= $textMaxSize) {
echo self::BOX_STYLES[$style][5].self::stringpad(' '.$message.' ', self::LAYOUT_SIZE, ' ', self::textAlign($align)).self::BOX_STYLES[$style][5]."\n";
} else {
$delimiter = ' ';
if (strpos($message, ' ') === false) {
$delimiter = '/';
}
$words = explode($delimiter, $message);
$pharase[0] = [];
$pharaseCount = 0;
foreach($words as $word) {
if (mb_strlen(implode($delimiter, $pharase[$pharaseCount]).$delimiter.$word) > $textMaxSize) {
$pharaseCount++;
$pharase[$pharaseCount] = [];
}
$pharase[$pharaseCount][] = $word;
}
foreach($pharase as $line) {
echo self::BOX_STYLES[$style][5].' '.self::stringpad(trim(implode($delimiter, $line).$delimiter), $textMaxSize, ' ', self::textAlign($align)).' '.self::BOX_STYLES[$style][5]."\n";
}
}
}
/**
* textAlign
*
* @param mixed $align
* @return int
*/
private static function textAlign(string $align): int
{
switch($align){
case 'center':
return STR_PAD_BOTH;
case 'right':
return STR_PAD_LEFT;
case 'left':
return STR_PAD_RIGHT;
default:
return STR_PAD_LEFT;
}
}
/**
* draw
*
* @param mixed $style
* @param mixed $type
* @return void
*/
private static function draw(string $style, string $type): void
{
switch($type) {
case 'top':
echo self::BOX_STYLES[$style][0].self::stringpad('', self::LAYOUT_SIZE, self::BOX_STYLES[$style][4], STR_PAD_LEFT).self::BOX_STYLES[$style][1]."\n";
break;
case 'bottom':
echo self::BOX_STYLES[$style][2].self::stringpad('', self::LAYOUT_SIZE, self::BOX_STYLES[$style][4], STR_PAD_LEFT).self::BOX_STYLES[$style][3]."\n";
break;
case 'line':
echo self::BOX_STYLES[$style][6].self::stringpad('', self::LAYOUT_SIZE, self::BOX_STYLES[$style][4], STR_PAD_LEFT).self::BOX_STYLES[$style][7]."\n";
break;
case 'empty':
echo self::BOX_STYLES[$style][5].self::stringpad('', self::LAYOUT_SIZE, " ", STR_PAD_LEFT).self::BOX_STYLES[$style][5]."\n";
break;
}
}
/**
* Source: https://stackoverflow.com/a/2050909
* Author: Felix Kling
*
* This function copy the entire source directory to a destination directory. PHP's native copy()
* function doesn't copy folders, much less do it recursively.
*
* @param string $sourceDirectory The directory that will be copied.
*
* @param string $destinationDirectory The destination folder that will receive the
* copy of the source directory.
*
* @param string $childFolder (Optional) Adds a child folder inside the
* destination directory and copies the source
* directory to this child folder.
*
* @return void
*/
private static function copyDirectory(string $sourceDirectory, string $destinationDirectory, string $childFolder = '', array $ignorePaths = []): void {
$directory = opendir($sourceDirectory);
if (is_dir($destinationDirectory) === false) {
mkdir($destinationDirectory);
}
if ($childFolder !== '') {
if (is_dir("$destinationDirectory/$childFolder") === false) {
mkdir("$destinationDirectory/$childFolder");
}
while (($file = readdir($directory)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
if (is_dir("$sourceDirectory/$file") === true) {
self::copyDirectory("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file", '', $ignorePaths);
} else {
foreach ($ignorePaths as $ignore) {
if ($ignore == substr($sourceDirectory, 0, strlen($ignore))) {
return;
}
}
copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file");
}
}
closedir($directory);
return;
}
while (($file = readdir($directory)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
if (is_dir("$sourceDirectory/$file") === true) {
self::copyDirectory("$sourceDirectory/$file", "$destinationDirectory/$file", '', $ignorePaths);
}
else {
foreach ($ignorePaths as $ignore) {
if ($ignore == substr($sourceDirectory, 0, strlen($ignore))) {
return;
}
}
copy("$sourceDirectory/$file", "$destinationDirectory/$file");
}
}
closedir($directory);
}
/**
* copyFile
*
* @param mixed $sourceFile
* @param mixed $destinationFile
* @return void
*/
private static function copyFile($sourceFile, $destinationFile) {
$path = pathinfo($destinationFile);
if (!file_exists($path['dirname'])) {
mkdir($path['dirname'], 0777, true);
}
copy($sourceFile, $destinationFile);
}
/**
* Source: https://intecsols.com/delete-files-and-folders-from-a-folder-using-php-by-intecsols/
* Author: Syed Muhammad Waqas
*
* This function delete the entire directory even if it has files inside it. PHP's native rmdir()
* function doesn't remove folders with files inside.
*
* @param string $directory Directory that will be removed.
*
* @return void
*/
private static function deleteAll(string $directory): void
{
foreach(glob($directory . '/*') as $file) {
if(is_dir($file)) {
self::deleteAll($file);
} else {
unlink($file);
}
}
rmdir($directory);
}
/**
* Source: https://www.php.net/manual/pt_BR/function.str-pad.php#116244
* Author: wes
*
* This function is the multibyte version of str_pad() function from PHP.
*
* @param mixed $string
*
* @param mixed $padlength
*
* @param mixed $pad_str
*
* @param mixed $align
*
* @param mixed $encoding
*
* @return string
*/
private static function stringpad(string $string, int $padlength, string $padstring = ' ', int $align = STR_PAD_RIGHT, ?string $encoding = NULL): string
{
$encoding = $encoding === NULL ? mb_internal_encoding() : $encoding;
$padBefore = $align === STR_PAD_BOTH || $align === STR_PAD_LEFT;
$padAfter = $align === STR_PAD_BOTH || $align === STR_PAD_RIGHT;
$padlength -= mb_strlen($string, $encoding);
$targetLength = $padBefore && $padAfter ? $padlength / 2 : $padlength;
$strToRepeatLength = mb_strlen($padstring, $encoding);
$repeatTimes = ceil($targetLength / $strToRepeatLength);
$repeatedString = str_repeat($padstring, max(0, $repeatTimes)); // safe if used with valid utf-8 strings
$stringbefore = $padBefore ? mb_substr($repeatedString, 0, floor($targetLength), $encoding) : '';
$stringafter = $padAfter ? mb_substr($repeatedString, 0, ceil($targetLength), $encoding) : '';
return $stringbefore.$string.$stringafter;
}
}
/**
* Language
*/
final class Language
{
const AVAILABLE_LANGUAGES = ['br', 'en'];
const NO_VERSION_FILE = [
'en' => [
'The "VERSION" file wasn\'t found in the "galastri" folder.',
'Without this file, the updater cannot continue.',
],
'br' => [
'Não foi encontrado o arquivo "VERSION" dentro da pasta "galastri".',
'Sem este arquivo, o atualizador não pode continuar.',
],
];
const NO_WRITING_PERMISSION = [
'en' => [
'The following folder doesn\'t have writing permissions:',
'Grant write permissions to the folder and run the updater again.',
],
'br' => [
'A seguinte pasta não possui permissões de escrita:',
'Conceda permissões de escrita para a pasta e execute o atualizador novamente.',
],
];
const CHOOSE_A_OPTION = [
'en' => [
'Choose an option: ',
],
'br' => [
'Escolha uma das opções: ',
],
];
const EXIT = [
'en' => [
'Closing the updater!',
'Bye bye! :)',
],
'br' => [
'Encerrando o atualizador!',
'Bye bye! :)',
],
];
const MAIN_INVALID_OPTION = [
'en' => [
'Option "',
'" is invalid. Please, choose a valid option.',
],
'br' => [
'A opção "',
'" é inválida. Por favor, escolha uma opção válida.',
],
];
const NO_BACKUP_FOUND = [
'en' => [
'No backup found.',
],
'br' => [
'Nenhum backup encontrado.',
],
];
const CHOOSE_BACKUP_RESTORATION = [
'en' => [
"Choose a number of the backup to be restored,\n",
'or choose 0 (zero) to cancel: ',
],
'br' => [
"Informe o número do backup a ser restaurado,\n",
'ou informe 0 (zero) para cancelar: ',
],
];
const CANCEL_BACKUP_RESTORATION = [
'en' => [
'No problem! :)',
'Process cancelled. No backup was restored!',
],
'br' => [
'Sem problemas! :)',
'Processo cancelado. Nenhum backup foi restaurado!',
],
];
const CONFIRM_BACKUP_RESTORAION = [
'en' => [
'Confirm the backup restoration? ',
'Confirma the restoration? [y/N]: ',
],
'br' => [
'Confirma a restauração do backup? ',
'Confirma a restauração? [s/N]: ',
],
];
const INVALID_BACKUP_OPTION = [
'en' => [
'The number you choose is invalid. Try again!',
],
'br' => [
'O número informado é inválido. Tente novamente!',
],
];
const CHECKING_UPDATES = [
'en' => [
'Checking for updates. Make sure that you have internet access!',
],
'br' => [
'Verificando atualizações. Certifique-se de que você tem acesso à internet!',
],
];
const RESTORING_BACKUP = [
'en' => [
'Restoring the backup files.',
],
'br' => [
'Restaurando os arquivos do backup.',
],
];
const RESTORING_BACKUP_PROCESS = [
'en' => [
'- Restoring files from ',
],
'br' => [
'- Restaurando os arquivos de ',
],
];
const BACKUP_RESTORED = [
'en' => [
'Restoration process done! :D',
],
'br' => [
'Processo de restauração concluído! :D',
],
];
const INVALID_VERSION = [
'en' => [
'Strange... Your current version is "',
'", but it isn\'t in the list of available versions of Galastri Framework.',
'For security reasons, it is better you update the framework manually.',
],
'br' => [
'Estranho... A sua versão é a "',
'", mas ela não consta na lista de versões existentes do Galastri Framework.',
'Por questões de segurança, é melhor você atualizar o framework manualmente.',
],
];
const UP_TO_DATE_VERSION = [
'en' => [
'There is no new updates available',
'Your version "',
'" is already the most up to date!',
],
'br' => [
'Nenhuma nova atualização disponível.',
'Sua versão "',
'" já é a mais recente!',
],
];
const STARTING_UPDATE = [
'en' => [
'Starting the update process!',
],
'br' => [
'Iniciando o processo de atualização!',
],
];
const UPDATE_PROCESS = [
'en' => [
' - Downloading the package',
' - Package downloaded. Extracting the files.',
' - Applying the update package.',
],
'br' => [
' - Baixando o pacote "',
' - Pacote baixado. Extraindo os arquivos.',
' - Aplicando o pacote de atualização.',
],
];
const UPDATER_UPDATED = [
'en' => [
'The updater updated itself!',
'We need to restart the updater before continue.',
'Run the updater again and restart the updating process to continue with the installation.',
],
'br' => [
'O atualizador foi atualizado!',
'Precisamos reiniciar o atualizar antes de continuar.',
'Reabra-o e reinicie o processo de atualização para prosseguir com a instalação de novos pacotes.',
],
];
const UPDATE_DONE = [
'en' => [
'Updating process done! :D',
'Your Galastri Framework is now in the version ',
],
'br' => [
'Processo de atualização concluído! :D',
'Seu Galastri Framework agora está na versão ',
],
];
const CONFIRM_UPDATE = [
'en' => [
'Start update? [y/N]: ',
],
'br' => [
'Deseja atualizar? [s/N]: ',
],
];