forked from mautic/mautic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upgrade.php
1381 lines (1144 loc) · 43.3 KB
/
upgrade.php
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
/*
* @copyright 2014 Mautic Contributors. All rights reserved
* @author Mautic
*
* @link http://mautic.org
*
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
ini_set('display_errors', 'Off');
date_default_timezone_set('UTC');
define('MAUTIC_MINIMUM_PHP', '5.6.19');
define('MAUTIC_MAXIMUM_PHP', '7.3.999');
// Are we running the minimum version?
if (version_compare(PHP_VERSION, MAUTIC_MINIMUM_PHP, 'lt')) {
echo 'Your server does not meet the minimum PHP requirements. Mautic requires PHP version '.MAUTIC_MINIMUM_PHP.' while your server has '.PHP_VERSION.'. Please contact your host to update your PHP installation.'."\n";
exit;
}
// Are we running a version newer than what Mautic supports?
if (version_compare(PHP_VERSION, MAUTIC_MAXIMUM_PHP, 'gt')) {
echo 'Mautic does not support PHP version '.PHP_VERSION.' at this time. To use Mautic, you will need to downgrade to an earlier version.'."\n";
exit;
}
$standalone = (int) getVar('standalone', 0);
$task = getVar('task');
define('IN_CLI', php_sapi_name() === 'cli');
define('MAUTIC_ROOT', (IN_CLI || $standalone || empty($task)) ? __DIR__ : dirname(__DIR__));
define('MAUTIC_UPGRADE_ERROR_LOG', MAUTIC_ROOT.'/upgrade_errors.txt');
define('MAUTIC_APP_ROOT', MAUTIC_ROOT.'/app');
if ($standalone || IN_CLI) {
if (!file_exists(__DIR__.'/upgrade')) {
mkdir(__DIR__.'/upgrade');
}
define('MAUTIC_UPGRADE_ROOT', __DIR__.'/upgrade');
} else {
define('MAUTIC_UPGRADE_ROOT', __DIR__);
}
// Get local parameters
$localParameters = get_local_config();
if (isset($localParameters['cache_path'])) {
$cacheDir = str_replace('%kernel.root_dir%', MAUTIC_APP_ROOT, $localParameters['cache_path'].'/prod');
} else {
$cacheDir = MAUTIC_APP_ROOT.'/cache/prod';
}
define('MAUTIC_CACHE_DIR', $cacheDir);
/*
* Updating to 2.8.1: Check to see if we have a mautic_session_name
* and use that to populate the actual session name that will be
* generated after a successful update.
*/
if (isset($_COOKIE['mautic_session_name'])) {
$sessionValue = $_COOKIE[$_COOKIE['mautic_session_name']];
include MAUTIC_APP_ROOT.'/config/paths.php';
$localConfigPath = str_replace('%kernel.root_dir%', MAUTIC_APP_ROOT, $paths['local_config']);
$newSessionName = md5(md5($localConfigPath).$localParameters['secret_key']);
setcookie($newSessionName, $sessionValue, 0, '/', '', false, true);
unset($_COOKIE['mautic_session_name']);
setcookie('mautic_session_name', null, -1);
}
// Fetch the update state out of the request if applicable
$state = json_decode(base64_decode(getVar('updateState', 'W10=')), true);
// Prime the state if it's empty
if (empty($state)) {
$state['pluginComplete'] = false;
$state['bundleComplete'] = false;
$state['cacheComplete'] = false;
$state['coreComplete'] = false;
$state['vendorComplete'] = false;
}
$status = ['complete' => false, 'error' => false, 'updateState' => $state, 'stepStatus' => 'In Progress'];
// Web request upgrade
if (!IN_CLI) {
$request = explode('?', $_SERVER['REQUEST_URI'])[0];
$url = "//{$_SERVER['HTTP_HOST']}{$request}";
$isSSL = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off');
$cookie_path = (isset($localParameters['cookie_path'])) ? $localParameters['cookie_path'] : '/';
$cookie_domain = (isset($localParameters['cookie_domain'])) ? $localParameters['cookie_domain'] : '';
$cookie_secure = (isset($localParameters['cookie_secure'])) ? $localParameters['cookie_secure'] : $isSSL;
$cookie_httponly = (isset($localParameters['cookie_httponly'])) ? $localParameters['cookie_httponly'] : false;
setcookie('mautic_update', $task, time() + 300, $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly);
$query = '';
$maxCount = (!empty($standalone)) ? 25 : 5;
switch ($task) {
case '':
html_body("<div class='well text-center'><h3><a href='$url?task=startUpgrade&standalone=1'>Click here to start upgrade.</a></h3><br /><strong>Do not refresh or stop the process. This may take serveral minutes.</strong></div>");
case 'startUpgrade':
$nextTask = 'fetchUpdates';
break;
case 'fetchUpdates':
list($success, $message) = fetch_updates();
if (!$success) {
html_body("<div alert='alert alert-danger'>$message</div>");
}
$query = "version=$message&";
$nextTask = 'extractUpdate';
break;
case 'extractUpdate':
list($success, $message) = extract_package(getVar('version'));
if (!$success) {
html_body("<div alert='alert alert-danger'>$message</div>");
}
$nextTask = 'moveBundles';
break;
case 'moveBundles':
$status = move_mautic_bundles($status, $maxCount);
if (empty($status['complete'])) {
if (!isset($state['refresh_count'])) {
$state['refresh_count'] = 1;
}
$nextTask = 'moveBundles';
$query = 'count='.$state['refresh_count'].'&';
$state['refresh_count'] += 1;
} else {
$nextTask = 'moveCore';
unset($state['refresh_count']);
}
break;
case 'moveCore':
$status = move_mautic_core($status);
$nextTask = 'moveVendors';
break;
case 'moveVendors':
$status = move_mautic_vendors($status, $maxCount);
$nextTask = (!empty($status['complete'])) ? 'clearCache' : 'moveVendors';
if (empty($status['complete'])) {
if (!isset($state['refresh_count'])) {
$state['refresh_count'] = 1;
}
$nextTask = 'moveVendors';
$query = 'count='.$state['refresh_count'].'&';
$state['refresh_count'] += 1;
} else {
$nextTask = 'clearCache';
unset($state['refresh_count']);
}
break;
case 'clearCache':
clear_mautic_cache();
$nextTask = 'buildCache';
$redirect = true;
break;
case 'buildCache':
build_cache();
$nextTask = (!empty($standalone)) ? 'applyMigrations' : 'applyCriticalMigrations';
$redirect = true;
break;
case 'applyCriticalMigrations':
// Apply critical migrations
apply_critical_migrations();
$nextTask = 'finish';
$redirect = true;
break;
case 'clearCache':
clear_mautic_cache();
$nextTask = 'buildCache';
$redirect = true;
break;
case 'applyMigrations':
// Apply critical migrations
apply_migrations();
$nextTask = 'finish';
break;
case 'finish':
clear_mautic_cache();
if (!empty($standalone)) {
html_body("<div class='well'><h3 class='text-center'>Success!</h3><h4 class='text-danger text-center'>Remove this script!</h4></div>");
} else {
$status['complete'] = true;
$status['stepStatus'] = 'Success';
$status['nextStep'] = 'Processing Database Updates';
$status['nextStepStatus'] = 'In Progress';
$status['updateState']['cacheComplete'] = true;
}
break;
default:
$status['error'] = true;
$status['message'] = 'Invalid task';
$status['stepStatus'] = 'Failed';
break;
}
if ($standalone || !empty($redirect)) {
// Standalone updater or redirecting to help prevent timeouts
if (!empty($nextTask)) {
if ('finish' == $nextTask) {
header("Location: $url?task=$nextTask&standalone=$standalone");
} else {
header("Location: $url?{$query}task=$nextTask&standalone=$standalone&updateState=".get_state_param($state));
}
exit;
}
} else {
// Request through Mautic's UI
$status['updateState'] = get_state_param($status['updateState']);
send_response($status);
}
} else {
// CLI upgrade
echo 'Checking for new updates...';
list($success, $message) = fetch_updates();
if (!$success) {
echo "failed. $message";
exit;
}
$version = $message;
echo "updating to $version!\n";
echo 'Extracting the update package...';
list($success, $message) = extract_package($version);
if (!$success) {
echo "failed. $message";
exit;
}
echo "done!\n";
echo 'Moving files...';
$status = move_mautic_bundles($status, -1);
$status = move_mautic_core($status);
$status = move_mautic_vendors($status, -1);
if (empty($status['complete'])) {
echo 'failed. Review udpate errors log for details.';
exit;
}
unset($status['complete']);
echo "done!\n";
echo 'Clearing the cache...';
if (!clear_mautic_cache()) {
echo 'failed. Review udpate errors log for details.';
exit;
}
echo "done!\n";
echo 'Rebuilding the cache...';
if (!build_cache()) {
echo 'failed. Review udpate errors log for details.';
exit;
}
echo "done!\n";
echo 'Applying migrations...';
if (!apply_migrations()) {
echo 'failed. Review udpate errors log for details.';
exit;
}
echo "done!\n";
echo 'Cleaning up...';
if (!recursive_remove_directory(MAUTIC_UPGRADE_ROOT)) {
echo "failed. Manually delete the upgrade folder.\n";
}
if (!clear_mautic_cache()) {
echo 'failed. Manually delete app/cache/prod.';
}
echo "done!\n";
echo "\nSuccess!";
}
/**
* Get local parameters.
*
* @return mixed
*/
function get_local_config()
{
static $parameters;
if (null === $parameters) {
// Used in paths.php
$root = MAUTIC_APP_ROOT;
/** @var array $paths */
include MAUTIC_APP_ROOT.'/config/paths.php';
// Include local config to get cache_path
$localConfig = str_replace('%kernel.root_dir%', MAUTIC_APP_ROOT, $paths['local_config']);
/** @var array $parameters */
include $localConfig;
$localParameters = $parameters;
//check for parameter overrides
if (file_exists(MAUTIC_APP_ROOT.'/config/parameters_local.php')) {
/** @var $parameters */
include MAUTIC_APP_ROOT.'/config/parameters_local.php';
$localParameters = array_merge($localParameters, $parameters);
}
foreach ($localParameters as $k => &$v) {
if (!empty($v) && is_string($v) && preg_match('/getenv\((.*?)\)/', $v, $match)) {
$v = (string) getenv($match[1]);
}
}
$parameters = $localParameters;
}
return $parameters;
}
/**
* Fetch a list of updates.
*
* @return array
*/
function fetch_updates()
{
global $localParameters;
$version = file_get_contents(__DIR__.'/app/version.txt');
try {
// Generate a unique instance ID for the site
$instanceId = hash('sha1', $localParameters['secret_key'].'Mautic'.$localParameters['db_driver']);
$data = [
'application' => 'Mautic',
'version' => $version,
'phpVersion' => PHP_VERSION,
'dbDriver' => $localParameters['db_driver'],
'serverOs' => php_uname('s').' '.php_uname('r'),
'instanceId' => $instanceId,
'installSource' => (isset($localParameters['install_source'])) ? $localParameters['install_source'] : 'Mautic',
];
make_request('https://updates.mautic.org/stats/send', 'post', $data);
} catch (\Exception $exception) {
// Not so concerned about failures here, move along
}
// Get the update data
try {
$appData = [
'appVersion' => $version,
'phpVersion' => PHP_VERSION,
'stability' => (isset($localParameters['update_stability'])) ? $localParameters['update_stability'] : 'stable',
];
$data = make_request('https://updates.mautic.org/index.php?option=com_mauticdownload&task=checkUpdates', 'post', $appData);
$update = json_decode($data);
// Check if this version is up to date
if ($update->latest_version || version_compare($version, $update->version, 'ge')) {
return [false, 'Up to date!'];
}
// Fetch the package
try {
download_package($update);
} catch (\Exception $e) {
return [
false,
"Could not automatically download the package. Please download {$update->package}, place it in the same directory as this upgrade script, and try again. ".
"When moving the file, name it `{$update->version}-update.zip`",
];
}
return [true, $update->version];
} catch (\Exception $exception) {
return [false, $exception->getMessage()];
}
}
/**
* @param object $update
*
* @throws Exception
*
* @return bool
*/
function download_package($update)
{
$packageName = $update->version.'-update.zip';
$target = __DIR__.'/'.$packageName;
if (file_exists($target)) {
return true;
}
$data = make_request($update->package);
if (!file_put_contents($target, $data)) {
throw new \Exception();
}
}
/**
* @param $zipFile
*
* @return int
*/
function extract_package($version)
{
$zipFile = __DIR__.'/'.$version.'-update.zip';
if (!file_exists($zipFile)) {
return [false, 'Package could not be found!'];
}
$zipper = new \ZipArchive();
$archive = $zipper->open($zipFile);
if ($archive !== true) {
return [false, 'Could not open or read update package.'];
}
if (!$zipper->extractTo(MAUTIC_UPGRADE_ROOT)) {
return [false, 'Could not extract update package'];
}
$zipper->close();
return [true, 'success'];
}
/**
* Clears the application cache.
*
* Since this script is being executed via web requests and standalone from the Mautic application, we don't have access to Symfony's
* CLI suite. So we'll go with Option B in this instance and just nuke the entire production cache and let Symfony rebuild it on the next
* application cycle.
*
* @param array $status
*
* @return array
*/
function clear_mautic_cache()
{
if (!recursive_remove_directory(MAUTIC_CACHE_DIR)) {
process_error_log(['Could not remove the application cache. You will need to manually delete '.MAUTIC_CACHE_DIR.'.']);
return false;
}
// Follow the same pattern as the console command and flush opcache/apc as appropriate.
if (function_exists('opcache_reset')) {
opcache_reset();
}
if (function_exists('apc_clear_cache')) {
apc_clear_cache();
}
return true;
}
/**
* @param $command
* @param array $args
*
* @return array
*
* @throws Exception
*/
function run_symfony_command($command, array $args)
{
static $application;
require_once MAUTIC_APP_ROOT.'/autoload.php';
require_once MAUTIC_APP_ROOT.'/AppKernel.php';
$args = array_merge(
['console', $command],
$args
);
if (null == $application) {
$kernel = new \AppKernel('prod', true);
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);
}
$input = new \Symfony\Component\Console\Input\ArgvInput($args);
$output = new \Symfony\Component\Console\Output\NullOutput();
$exitCode = $application->run($input, $output);
unset($input, $output);
return $exitCode === 0;
}
/**
* Build the cache.
*
* @return array
*/
function build_cache()
{
// Rebuild the cache
return run_symfony_command('cache:clear', ['--no-interaction', '--env=prod', '--no-debug', '--no-warmup']);
}
/**
* Apply critical migrations.
*/
function apply_critical_migrations()
{
$criticalMigrations = json_decode(file_get_contents(__DIR__.'/critical_migrations.txt'), true);
$success = true;
$minExecutionTime = 300;
$maxExecutionTime = (int) ini_get('max_execution_time');
if ($maxExecutionTime > 0 && $maxExecutionTime < $minExecutionTime) {
ini_set('max_execution_time', $minExecutionTime);
}
if ($criticalMigrations) {
foreach ($criticalMigrations as $version) {
if (!run_symfony_command('doctrine:migrations:migrate', ['--no-interaction', '--env=prod', '--no-debug', $version])) {
$success = false;
}
}
}
return $success;
}
/**
* Apply all migrations.
*
* @return bool
*/
function apply_migrations()
{
$minExecutionTime = 300;
$maxExecutionTime = (int) ini_get('max_execution_time');
if ($maxExecutionTime > 0 && $maxExecutionTime < $minExecutionTime) {
ini_set('max_execution_time', $minExecutionTime);
}
return run_symfony_command('doctrine:migrations:migrate', ['--no-interaction', '--env=prod', '--no-debug']);
}
/**
* Copy a folder.
*
* This function is based on \Joomla\Filesystem\Folder:copy()
*
* @param string $src The path to the source folder
* @param string $dest The path to the destination folder
*
* @return array|string|bool True on success, a single error message on a "boot" fail, or an array of errors from the recursive operation
*/
function copy_directory($src, $dest)
{
@set_time_limit(ini_get('max_execution_time'));
$errorLog = [];
// Eliminate trailing directory separators, if any
$src = rtrim($src, DIRECTORY_SEPARATOR);
$dest = rtrim($dest, DIRECTORY_SEPARATOR);
// Make sure the destination exists
if (!is_dir($dest)) {
if (!@mkdir($dest, 0755, true)) {
return sprintf(
'Could not move files from %s to production since the folder could not be created.',
str_replace(MAUTIC_UPGRADE_ROOT, '', $src)
);
}
}
if (!($dh = @opendir($src))) {
return sprintf('Could not read directory %s to move files.', str_replace(MAUTIC_UPGRADE_ROOT, '', $src));
}
// Walk through the directory copying files and recursing into folders.
while (($file = readdir($dh)) !== false) {
$sfid = $src.'/'.$file;
$dfid = $dest.'/'.$file;
switch (filetype($sfid)) {
case 'dir':
if ($file != '.' && $file != '..') {
$ret = copy_directory($sfid, $dfid);
if ($ret !== true) {
if (is_array($ret)) {
$errorLog += $ret;
} else {
$errorLog[] = $ret;
}
}
}
break;
case 'file':
if (!@rename($sfid, $dfid)) {
$errorLog[] = sprintf('Could not move file %s to production.', str_replace(MAUTIC_UPGRADE_ROOT, '', $sfid));
}
break;
}
}
if (!empty($errorLog)) {
return $errorLog;
}
return true;
}
/**
* Fetches a request variable and returns the sanitized version of it.
*
* @param string $name
* @param string $default
* @param int $filter
*
* @return mixed|string
*/
function getVar($name, $default = '', $filter = FILTER_SANITIZE_STRING)
{
if (isset($_REQUEST[$name])) {
return filter_var($_REQUEST[$name], $filter);
}
return $default;
}
/**
* Moves the Mautic bundles from the upgrade directory to production.
*
* A typical update package will only include changed files in the bundles. However, in this script we will assume that all of
* the bundle resources are included here and recursively iterate over the bundles in batches to update the filesystem.
*
* @param array $status
* @param int $maxCount
*
* @return array
*/
function move_mautic_bundles(array $status, $maxCount = 5)
{
$errorLog = [];
// First, we will move any addon bundles into position
if (is_dir(MAUTIC_UPGRADE_ROOT.'/plugins') && !$status['updateState']['pluginComplete']) {
$iterator = new DirectoryIterator(MAUTIC_UPGRADE_ROOT.'/plugins');
// Sanity check, make sure there are actually directories here to process
$dirs = glob(MAUTIC_UPGRADE_ROOT.'/plugins/*', GLOB_ONLYDIR);
if (count($dirs)) {
/** @var DirectoryIterator $directory */
foreach ($iterator as $directory) {
// Sanity checks
if (!$directory->isDot() && $directory->isDir()) {
$src = $directory->getPath().'/'.$directory->getFilename();
$dest = str_replace(MAUTIC_UPGRADE_ROOT, MAUTIC_ROOT, $src);
$result = copy_directory($src, $dest);
if ($result !== true) {
if (is_array($result)) {
$errorLog += $result;
} else {
$errorLog[] = $result;
}
}
$deleteDir = recursive_remove_directory($src);
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', str_replace(MAUTIC_UPGRADE_ROOT, '', $src));
}
}
}
}
// At this point, there shouldn't be any plugins remaining; nuke the folder
$deleteDir = recursive_remove_directory(MAUTIC_UPGRADE_ROOT.'/plugins');
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', '/plugins');
}
process_error_log($errorLog);
$status['updateState']['pluginComplete'] = true;
if ($maxCount != -1) {
// Finished with plugins, get a response back to the app so we can iterate to the next part
return $status;
}
}
// Now we move the main app bundles into production
if (is_dir(MAUTIC_UPGRADE_ROOT.'/app/bundles') && !$status['updateState']['bundleComplete']) {
// Initialize the bundle state if it isn't
if (!isset($status['updateState']['completedBundles'])) {
$status['updateState']['completedBundles'] = [];
}
$completed = true;
$iterator = new DirectoryIterator(MAUTIC_UPGRADE_ROOT.'/app/bundles');
// Sanity check, make sure there are actually directories here to process
$dirs = glob(MAUTIC_UPGRADE_ROOT.'/app/bundles/*', GLOB_ONLYDIR);
if (count($dirs)) {
$count = 0;
/** @var DirectoryIterator $directory */
foreach ($iterator as $directory) {
// Exit the loop if the count has reached 5
if ($maxCount != -1 && $count === $maxCount) {
$completed = false;
break;
}
// Sanity checks
if (!$directory->isDot() && $directory->isDir()) {
// Don't process this bundle if we've already tried it
if (isset($status['updateState']['completedBundles'][$directory->getFilename()])) {
continue;
}
$src = $directory->getPath().'/'.$directory->getFilename();
$dest = str_replace(MAUTIC_UPGRADE_ROOT, MAUTIC_ROOT, $src);
$result = copy_directory($src, $dest);
if ($result !== true) {
if (is_array($result)) {
$errorLog += $result;
} else {
$errorLog[] = $result;
}
}
$deleteDir = recursive_remove_directory($src);
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', str_replace(MAUTIC_UPGRADE_ROOT, '', $src));
}
$status['updateState']['completedBundles'][$directory->getFilename()] = true;
++$count;
}
}
}
if ($completed) {
$status['updateState']['bundleComplete'] = true;
// At this point, there shouldn't be any bundles remaining; nuke the folder
$deleteDir = recursive_remove_directory(MAUTIC_UPGRADE_ROOT.'/app/bundles');
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', '/app/bundles');
}
}
process_error_log($errorLog);
// If we haven't finished the bundles yet, throw a response back to repeat the step
if (!$status['updateState']['bundleComplete']) {
return $status;
}
}
// To get here, all of the bundle updates must have been processed (or there are literally none). Step complete.
$status['complete'] = true;
return $status;
}
/**
* Moves the Mautic core files that are not part of bundles or vendors into production.
*
* The "core" files are broken into groups for purposes of the update script: bundles, vendor, and everything else. This step
* will take care of the everything else.
*
* @param array $status
*
* @return array
*/
function move_mautic_core(array $status)
{
$errorLog = [];
// Multilevel directories
$nestedDirectories = [
'/media',
'/themes',
'/translations',
'/app/middlewares',
];
foreach ($nestedDirectories as $dir) {
if (is_dir(MAUTIC_UPGRADE_ROOT.$dir)) {
copy_directories($dir, $errorLog);
// At this point, we can remove the media directory
$deleteDir = recursive_remove_directory(MAUTIC_UPGRADE_ROOT.$dir);
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', $dir);
}
}
}
// Single level directories with files only
$fileOnlyDirectories = [
'/app/config',
'/app/migrations',
'/app',
'/bin',
];
foreach ($fileOnlyDirectories as $dir) {
if (copy_files($dir, $errorLog)) {
// At this point, we can remove the config directory
$deleteDir = recursive_remove_directory(MAUTIC_UPGRADE_ROOT.$dir);
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', $dir);
}
}
}
// Now move any root level files
$iterator = new FilesystemIterator(MAUTIC_UPGRADE_ROOT);
/** @var FilesystemIterator $file */
foreach ($iterator as $file) {
// Sanity checks
if ($file->isFile() && !in_array($file->getFilename(), ['deleted_files.txt', 'critical_migrations.txt', 'upgrade.php'])) {
$src = $file->getPath().'/'.$file->getFilename();
$dest = str_replace(MAUTIC_UPGRADE_ROOT, MAUTIC_ROOT, $src);
if (!@rename($src, $dest)) {
$errorLog[] = sprintf('Could not move file %s to production.', str_replace(MAUTIC_UPGRADE_ROOT, '', $src));
}
}
}
process_error_log($errorLog);
// In this step, we'll also go ahead and remove deleted files, return the results from that
return remove_mautic_deleted_files($status);
}
/**
* Moves the Mautic dependencies from the upgrade directory to production.
*
* Since the /vendor folder is not stored under version control, we cannot accurately track changes in third party dependencies
* between releases. Therefore, this step will recursively iterate over the vendors in batches to remove each package completely
* and replace it with the new version.
*
* @param array $status
* @param int $maxCount
*
* @return array
*/
function move_mautic_vendors(array $status, $maxCount = 5)
{
$errorLog = [];
// If there isn't even a vendor directory, just skip this step
if (!is_dir(MAUTIC_UPGRADE_ROOT.'/vendor')) {
$status['complete'] = true;
$status['stepStatus'] = 'Success';
$status['nextStep'] = 'Clearing Application Cache';
$status['nextStepStatus'] = 'In Progress';
$status['updateState']['vendorComplete'] = true;
return $status;
}
// Initialize the vendor state if it isn't
if (!isset($status['updateState']['completedVendors'])) {
$status['updateState']['completedVendors'] = [];
}
// Symfony is the largest of our vendors, we will process it first
if (is_dir(MAUTIC_UPGRADE_ROOT.'/vendor/symfony') && !isset($status['updateState']['completedVendors']['symfony'])) {
// Initialize the Symfony state if it isn't, this step will recurse
if (!isset($status['updateState']['completedSymfony'])) {
$status['updateState']['completedSymfony'] = [];
}
$completed = true;
$iterator = new DirectoryIterator(MAUTIC_UPGRADE_ROOT.'/vendor/symfony');
// Sanity check, make sure there are actually directories here to process
$dirs = glob(MAUTIC_UPGRADE_ROOT.'/vendor/symfony/*', GLOB_ONLYDIR);
if (count($dirs)) {
$count = 0;
/** @var DirectoryIterator $directory */
foreach ($iterator as $directory) {
// Exit the loop if the count has reached 5
if ($maxCount != -1 && $count === $maxCount) {
$completed = false;
break;
}
// Sanity checks
if (!$directory->isDot() && $directory->isDir()) {
// Don't process this directory if we've already tried it
if (isset($status['updateState']['completedSymfony'][$directory->getFilename()])) {
continue;
}
$src = $directory->getPath().'/'.$directory->getFilename();
$dest = str_replace(MAUTIC_UPGRADE_ROOT, MAUTIC_ROOT, $src);
// We'll need to completely remove the existing vendor first
recursive_remove_directory($dest);
$result = copy_directory($src, $dest);
if ($result !== true) {
if (is_array($result)) {
$errorLog += $result;
} else {
$errorLog[] = $result;
}
}
$deleteDir = recursive_remove_directory($src);
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', str_replace(MAUTIC_UPGRADE_ROOT, '', $src));
}
$status['updateState']['completedSymfony'][$directory->getFilename()] = true;
++$count;
}
}
}
if ($completed) {
$status['updateState']['completedVendors']['symfony'] = true;
// At this point, there shouldn't be any Symfony code remaining; nuke the folder
$deleteDir = recursive_remove_directory(MAUTIC_UPGRADE_ROOT.'/vendor/symfony');
if (!$deleteDir) {
$errorLog[] = sprintf('Failed to remove the upgrade directory %s folder', '/vendor/symfony');
}
}
process_error_log($errorLog);
// If we haven't finished Symfony yet, throw a response back to repeat the step
if (!isset($status['updateState']['completedVendors']['symfony'])) {
return $status;
}
}
// Once we've gotten here, we can safely iterate through the rest of the vendor directory; the rest of the contents are rather small in size
$completed = true;
$iterator = new DirectoryIterator(MAUTIC_UPGRADE_ROOT.'/vendor');
// Sanity check, make sure there are actually directories here to process
$dirs = glob(MAUTIC_UPGRADE_ROOT.'/vendor/*', GLOB_ONLYDIR);