-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathsetuputils.class.inc.php
More file actions
2170 lines (1970 loc) · 73.3 KB
/
setuputils.class.inc.php
File metadata and controls
2170 lines (1970 loc) · 73.3 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
// Copyright (C) 2010-2024 Combodo SAS
//
// This file is part of iTop.
//
// iTop is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// iTop is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/>
use Combodo\iTop\Application\Helper\Session;
use Combodo\iTop\Application\WebPage\CLIPage;
use Combodo\iTop\Application\WebPage\WebPage;
/**
* The standardized result of any pass/fail check performed by the setup
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
class CheckResult
{
// Severity levels
public const ERROR = 0;
public const WARNING = 1;
public const INFO = 2;
public const TRACE = 3; // for log purposes : replace old SetupLog::Log calls
public $iSeverity;
public $sLabel;
public $sDescription;
public function __construct($iSeverity, $sLabel, $sDescription = '')
{
$this->iSeverity = $iSeverity;
$this->sLabel = $sLabel;
$this->sDescription = $sDescription;
}
/**
* @return string
* @since 3.0.0 N°2214
*/
public function __toString(): string
{
$sPrintDesc = (empty($this->sDescription)) ? '' : " ({$this->sDescription})";
return "{$this->sLabel}$sPrintDesc";
}
/**
* @param \CheckResult[] $aResults
* @param string[] $aCheckResultSeverities list of CheckResult object severities to keep
*
* @return \CheckResult[] only elements that have one of the passed severity
*
* @since 3.0.0 N°2214
*/
public static function FilterCheckResultArray(array $aResults, array $aCheckResultSeverities): array
{
return array_filter(
$aResults,
static function ($v) use ($aCheckResultSeverities) {
if (in_array($v->iSeverity, $aCheckResultSeverities, true)) {
return $v;
}
return false;
},
ARRAY_FILTER_USE_BOTH
);
}
/**
* @param \CheckResult[] $aResults
*
* @return string[]
* @uses \CheckResult::__toString
*
* @since 3.0.0 N°2214
*/
public static function FromObjectsToStrings(array $aResults): array
{
return array_map(static function ($value) {
return $value->__toString();
}, $aResults);
}
}
/**
* All of the functions/utilities needed by both the setup wizard and the installation process
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
class SetupUtils
{
// -- Minimum versions (requirements : forbids installation if not met)
public const PHP_MIN_VERSION = '8.1.0';
public const MYSQL_MIN_VERSION = '5.7.0'; // 5.6 is no longer supported
public const MYSQL_NOT_VALIDATED_VERSION = ''; // MySQL 8 is now OK (N°2010 in 2.7.0) but has no query cache so mind the perf on large volumes !
// -- versions that will be the minimum in next iTop major release (warning if not met)
public const PHP_NEXT_MIN_VERSION = ''; // No new PHP requirement for next iTop version yet
public const MYSQL_NEXT_MIN_VERSION = ''; // No new MySQL requirement for next iTop version yet
// -- First recent version that is not yet validated by Combodo (warning)
public const PHP_NOT_VALIDATED_VERSION = '8.4.0';
public const MIN_MEMORY_LIMIT = '32M';
public const SUHOSIN_GET_MAX_VALUE_LENGTH = 2048;
/**
* Check configuration parameters, for example :
* <ul>
* <li>PHP version
* <li>needed PHP extensions
* <li>memory_limit
* <li>max_upload_file_size
* <li>...
* </ul>
*
* @return CheckResult[]
*
* @uses SetupPage $oP The page used only for its 'log' method
* @uses utils::IsModeCLI() to disable following checks :
* <ul>
* <li>php.ini option : file_uploads
* <li>Temp upload dir valid
* <li>php.ini option : upload_max_filesize
* <li>php.ini option : max_file_uploads
* <li>php.ini option : upload_max_filesize, post_max_size
* <li>php.ini option : session.save_handler
* </ul>
*
* @since 3.0.0 N°2214 disable some checks when in CLI mode
* @since 3.0.0 N°2214 replace SetupLog::Ok calls by CheckResult::TRACE
*/
public static function CheckPhpAndExtensions()
{
$aResult = [];
// For log file(s)
if (!is_dir(APPROOT.'log')) {
@mkdir(APPROOT.'log');
}
self::CheckPhpVersion($aResult);
// Check the common directories
if (utils::IsModeCLI()) {
$aWritableDirs = ['log', 'data'];
} else {
$aWritableDirs = ['log', 'env-production', 'env-production-build', 'conf', 'data'];
}
$aWritableDirsErrors = self::CheckWritableDirs($aWritableDirs);
$aResult = array_merge($aResult, $aWritableDirsErrors);
// Check temp dir (N°5235) : as this path isn't under APPROOT we are doing a custom check and not using \SetupUtils::CheckWritableDirs
$sTmpDir = static::GetTmpDir();
clearstatcache(true, $sTmpDir);
if (is_writable($sTmpDir)) {
$aResult[] = new CheckResult(CheckResult::INFO, "The temp directory is writable by the application.");
} else {
$aResult[] = new CheckResult(CheckResult::WARNING, "The temp directory <b>'".$sTmpDir."'</b> is not writable by the application. Change its permission or use another dir (sys_temp_dir option in php.ini).");
}
$aMandatoryExtensions = self::GetPHPMandatoryExtensions();
$aOptionalExtensions = self::GetPHPOptionalExtensions();
asort($aMandatoryExtensions); // Sort the list to look clean !
ksort($aOptionalExtensions); // Sort the list to look clean !
$aExtensionsOk = [];
$aMissingExtensions = [];
$aMissingExtensionsLinks = [];
// First check the mandatory extensions
foreach ($aMandatoryExtensions as $sExtension) {
if (extension_loaded($sExtension)) {
$aExtensionsOk[] = $sExtension;
} else {
$aMissingExtensions[] = $sExtension;
$aMissingExtensionsLinks[] = "<a href=\"http://www.php.net/manual/en/book.$sExtension.php\" target=\"_blank\">$sExtension</a>";
}
}
if (count($aExtensionsOk) > 0) {
$aResult[] = new CheckResult(CheckResult::INFO, "Required PHP extension(s): ".implode(', ', $aExtensionsOk).".");
}
if (count($aMissingExtensions) > 0) {
$aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".");
}
// Next check the optional extensions
$aExtensionsOk = [];
$aMissingExtensions = [];
foreach ($aOptionalExtensions as $sExtension => $sMessage) {
//if sMessage is an array, extensions in it are conditional between them
if (is_array($sMessage)) {
$bIsAtLeastOneLoaded = false;
$sConditionalMissingMessage = '';
foreach ($sMessage as $sConditionalExtension => $sConditionalMessage) {
if (extension_loaded($sConditionalExtension)) {
$bIsAtLeastOneLoaded = true;
$aExtensionsOk[] = $sConditionalExtension;
} else {
$sConditionalMissingMessage = $sConditionalMessage;
}
}
if (!$bIsAtLeastOneLoaded) {
$aMissingExtensions[$sExtension] = $sConditionalMissingMessage;
}
} else {
if (extension_loaded($sExtension)) {
$aExtensionsOk[] = $sExtension;
} else {
$aMissingExtensions[$sExtension] = $sMessage;
}
}
}
if (count($aExtensionsOk) > 0) {
$aResult[] = new CheckResult(CheckResult::INFO, "Optional PHP extension(s): ".implode(', ', $aExtensionsOk).".");
}
if (count($aMissingExtensions) > 0) {
foreach ($aMissingExtensions as $sExtension => $sMessage) {
$aResult[] = new CheckResult(CheckResult::WARNING, "Missing optional PHP extension: $sExtension. ".$sMessage);
}
}
// Check some ini settings here
if (function_exists('php_ini_loaded_file')) { // PHP >= 5.2.4
$sPhpIniFile = php_ini_loaded_file();
// Other included/scanned files
if ($sFileList = php_ini_scanned_files()) {
if (strlen($sFileList) > 0) {
$aFiles = explode(',', $sFileList);
foreach ($aFiles as $sFile) {
$sPhpIniFile .= ', '.trim($sFile);
}
}
}
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - php.ini file(s): '$sPhpIniFile'");
}
if (!utils::IsModeCLI() && !ini_get('file_uploads')) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').")."
);
}
if (!utils::IsModeCLI()) {
$sUploadTmpDir = self::GetUploadTmpDir();
if (empty($sUploadTmpDir)) {
$sUploadTmpDir = '/tmp';
$aResult[] = new CheckResult(
CheckResult::WARNING,
"Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used."
);
}
// check that the upload directory is indeed writable from PHP
if (!empty($sUploadTmpDir)) {
if (!file_exists($sUploadTmpDir)) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP."
);
} else {
if (!is_writable($sUploadTmpDir)) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"Temporary directory for files upload ($sUploadTmpDir) is not writable."
);
} else {
$aResult[] = new CheckResult(
CheckResult::TRACE,
"Info - Temporary directory for files upload ($sUploadTmpDir) is writable."
);
}
}
}
}
if (!utils::IsModeCLI() && !ini_get('upload_max_filesize')) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').")."
);
}
$iMaxFileUploads = ini_get('max_file_uploads');
if (!utils::IsModeCLI() && !empty($iMaxFileUploads) && ($iMaxFileUploads < 1)) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').")."
);
}
if (!utils::IsModeCLI()) {
$iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
$iMaxPostSize = utils::ConvertToBytes(ini_get('post_max_size'));
if ($iMaxPostSize <= $iMaxUploadSize) {
$aResult[] = new CheckResult(
CheckResult::WARNING,
"post_max_size (".ini_get('post_max_size').") in php.ini should be strictly greater than upload_max_filesize (".ini_get('upload_max_filesize').") otherwise you cannot upload files of the maximum size."
);
}
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - post_max_size: ".ini_get('post_max_size'));
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - max_file_uploads: ".ini_get('max_file_uploads'));
}
// Check some more ini settings here, needed for file upload
$sMemoryLimit = trim(ini_get('memory_limit'));
if (empty($sMemoryLimit)) {
// On some PHP installations, memory_limit does not exist as a PHP setting!
// (encountered on a 5.2.0 under Windows)
// In that case, ini_set will not work, let's keep track of this and proceed anyway
$aResult[] = new CheckResult(CheckResult::WARNING, "No memory limit has been defined in this instance of PHP");
} else {
// Check that the limit will allow us to load the data
//
$iCurrentMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
$iMinMemoryLimit = utils::ConvertToBytes(self::MIN_MEMORY_LIMIT);
if (!utils::IsMemoryLimitOk($iCurrentMemoryLimit, $iMinMemoryLimit)) {
$aResult[] = new CheckResult(CheckResult::ERROR, "memory_limit ($sMemoryLimit) is too small, the minimum value to run the application is ".self::MIN_MEMORY_LIMIT.".");
} else {
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - memory_limit is $sMemoryLimit, ok.");
}
}
// Special case for APC
if (extension_loaded('apc')) {
$sAPCVersion = phpversion('apc');
$aResult[] = new CheckResult(CheckResult::INFO, "APC detected (version $sAPCVersion). The APC cache will be used to speed-up ".ITOP_APPLICATION.".");
}
// Special case Suhosin extension
if (extension_loaded('suhosin')) {
$sSuhosinVersion = phpversion('suhosin');
$aOk[] = "Suhosin extension detected (version $sSuhosinVersion).";
$iGetMaxValueLength = ini_get('suhosin.get.max_value_length');
if ($iGetMaxValueLength < self::SUHOSIN_GET_MAX_VALUE_LENGTH) {
$aResult[] = new CheckResult(
CheckResult::WARNING,
"suhosin.get.max_value_length ($iGetMaxValueLength) is too small, the minimum value recommended to run the application is ".self::SUHOSIN_GET_MAX_VALUE_LENGTH."."
);
} else {
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - suhosin.get.max_value_length = $iGetMaxValueLength, ok.");
}
}
if (function_exists('php_ini_loaded_file')) { // PHP >= 5.2.4
$sPhpIniFile = php_ini_loaded_file();
// Other included/scanned files
if ($sFileList = php_ini_scanned_files()) {
if (strlen($sFileList) > 0) {
$aFiles = explode(',', $sFileList);
foreach ($aFiles as $sFile) {
$sPhpIniFile .= ', '.trim($sFile);
}
}
}
$aResult[] = new CheckResult(CheckResult::INFO, "Loaded php.ini files: $sPhpIniFile");
}
// Check the configuration of the sessions persistence, since this is critical for the authentication
if (!utils::IsModeCLI()) {
if (ini_get('session.save_handler') == 'files') {
$sSavePath = ini_get('session.save_path');
$aResult[] = new CheckResult(CheckResult::TRACE, "Info - session.save_path is: '$sSavePath'.");
// According to the PHP documentation, the format can be /path/where/to_save_sessions or "N;/path/where/to_save_sessions" or "N;MODE;/path/where/to_save_sessions"
$sSavePath = ltrim(rtrim($sSavePath, '"'), '"'); // remove surrounding quotes (if any)
if (!empty($sSavePath)) {
if (($iPos = strrpos($sSavePath, ';', 0)) !== false) {
// The actual path is after the last semicolon
$sSavePath = substr($sSavePath, $iPos + 1);
}
if (!is_writable($sSavePath)) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"The value for session.save_path ($sSavePath) is not writable for the web server. Make sure that PHP can actually save session variables. (Refer to the PHP documentation: http://php.net/manual/en/session.configuration.php#ini.session.save-path)"
);
} else {
$aResult[] = new CheckResult(
CheckResult::INFO,
"The value for session.save_path ($sSavePath) is writable for the web server."
);
}
} else {
$aResult[] = new CheckResult(
CheckResult::WARNING,
"Empty path for session.save_path. Make sure that PHP can actually save session variables. (Refer to the PHP documentation: http://php.net/manual/en/session.configuration.php#ini.session.save-path)"
);
}
} else {
$aResult[] = new CheckResult(
CheckResult::INFO,
"session.save_handler is: '".ini_get('session.save_handler')."' (different from 'files')."
);
}
}
return $aResult;
}
/**
* Call the platform checks. If those checks return CheckResult::ERROR, then output and log them, then exit. Otherwise just return.
*
* @param CLIPage $oCliPage
* @param int $iExitCode
*
* @uses CheckPhpAndExtensions
* @uses \CheckResult::FilterCheckResultArray()
* @uses CLIPage::output()
* @uses \IssueLog::Error()
* @uses \exit()
*
* @since 3.0.0 N°2214 Add PHP version checks in CLI scripts
*/
public static function CheckPhpAndExtensionsForCli($oCliPage, $iExitCode = -1)
{
$aPhpCheckResults = self::CheckPhpAndExtensions();
$aPhpCheckErrors = CheckResult::FilterCheckResultArray($aPhpCheckResults, [CheckResult::ERROR]);
if (empty($aPhpCheckErrors)) {
return;
}
$sMessageTitle = 'Error: Requirements are not met !';
$oCliPage->p($sMessageTitle);
$aPhpCheckErrorsForPrint = CheckResult::FromObjectsToStrings($aPhpCheckErrors);
foreach ($aPhpCheckErrorsForPrint as $sError) {
$oCliPage->p(' * '.$sError);
}
$oCliPage->output();
// some CLI scripts are launched automatically
// we need a log so that we don't miss errors after migration !
IssueLog::Error($oCliPage->s_title.' '.$sMessageTitle, LogChannels::CLI, $aPhpCheckErrorsForPrint);
exit($iExitCode);
}
/**
* @param CheckResult[] $aResult checks log
*
* @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE
*/
private static function CheckPhpVersion(array &$aResult)
{
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - CheckPHPVersion');
$sPhpVersion = phpversion();
if (version_compare($sPhpVersion, self::PHP_MIN_VERSION, '>=')) {
$aResult[] = new CheckResult(
CheckResult::INFO,
"The current PHP Version (".$sPhpVersion.") is greater than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")"
);
$sPhpNextMinVersion = self::PHP_NEXT_MIN_VERSION; // mandatory before PHP 5.5 (arbitrary expressions), keeping compat because we're in the setup !
if (!empty($sPhpNextMinVersion)) {
if (version_compare($sPhpVersion, self::PHP_NEXT_MIN_VERSION, '>=')) {
$aResult[] = new CheckResult(
CheckResult::INFO,
"The current PHP Version (".$sPhpVersion.") is greater than the minimum version required to run next ".ITOP_APPLICATION." major release, which is (".self::PHP_NEXT_MIN_VERSION.")"
);
} else {
$aResult[] = new CheckResult(
CheckResult::WARNING,
"The current PHP Version (".$sPhpVersion.") is lower than the minimum version required to run next ".ITOP_APPLICATION." major release, which is (".self::PHP_NEXT_MIN_VERSION.")"
);
}
}
if (version_compare($sPhpVersion, self::PHP_NOT_VALIDATED_VERSION, '>=')) {
$aResult[] = new CheckResult(
CheckResult::WARNING,
"The current PHP Version (".$sPhpVersion.") is not yet validated by Combodo. You may experience some incompatibility issues."
);
}
} else {
$aResult[] = new CheckResult(
CheckResult::ERROR,
"Error: The current PHP Version (".$sPhpVersion.") is lower than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")"
);
}
}
/**
* Check that the selected modules meet their dependencies
*
* @param $sSourceDir
* @param $sExtensionDir
* @param $aSelectedModules
*
* @return array
*
* @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE
*/
public static function CheckSelectedModules($sSourceDir, $sExtensionDir, $aSelectedModules)
{
$aResult = [];
$aDirsToScan = [APPROOT.$sSourceDir];
$sExtensionsPath = APPROOT.$sExtensionDir;
if (is_dir($sExtensionsPath)) {
// if the extensions dir exists, scan it for additional modules as well
$aDirsToScan[] = $sExtensionsPath;
}
require_once(APPROOT.'setup/modulediscovery.class.inc.php');
try {
ModuleDiscovery::GetAvailableModules($aDirsToScan, true, $aSelectedModules);
} catch (Exception $e) {
$aResult[] = new CheckResult(CheckResult::ERROR, $e->getMessage());
}
return $aResult;
}
/**
* Check that the backup could be executed
*
* @param $sDBBackupPath
* @param $sMySQLBinDir
*
* @return \CheckResult[] An array of CheckResults objects
*
* @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE
*/
public static function CheckBackupPrerequisites($sDBBackupPath, $sMySQLBinDir = null)
{
$aResult = [];
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - CheckBackupPrerequisites');
// zip extension
//
if (!extension_loaded('phar')) {
$sMissingExtensionLink = "<a href=\"http://www.php.net/manual/en/book.phar.php\" target=\"_blank\">zip</a>";
$aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension: phar", $sMissingExtensionLink);
}
if (!extension_loaded('zlib')) {
$sMissingExtensionLink = "<a href=\"http://www.php.net/manual/en/book.zlib.php\" target=\"_blank\">zip</a>";
$aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension: zlib", $sMissingExtensionLink);
}
// availability of exec()
//
$aDisabled = explode(', ', ini_get('disable_functions'));
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - PHP functions disabled: '.implode(', ', $aDisabled));
if (in_array('exec', $aDisabled)) {
$aResult[] = new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server");
}
MetaModel::LoadConfig(utils::GetConfig());
// availability of mysqldump
if (empty($sMySQLBinDir) && null != MetaModel::GetConfig()) {
$sMySQLBinDir = MetaModel::GetConfig()->GetModuleSetting('itop-backup', 'mysql_bindir', '');
}
try {
$oConfig = MetaModel::GetConfig();
CMDBSource::InitFromConfig($oConfig);
$sMySQLDump = DBBackup::MakeSafeMySQLCommand($sMySQLBinDir, DBBackup::GetDumpFunction());
} catch (Exception $e) {
$aResult[] = new CheckResult(CheckResult::ERROR, $e->getMessage());
return $aResult;
}
if (!empty($sMySQLBinDir)) {
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - Found mysql_bindir: '.$sMySQLBinDir);
}
$sCommand = "$sMySQLDump -V 2>&1";
$aOutput = [];
$iRetCode = 0;
exec($sCommand, $aOutput, $iRetCode);
if ($iRetCode == 0) {
$aResult[] = new CheckResult(CheckResult::INFO, "mysqldump is present: Ok.");
} elseif ($iRetCode == 1) {
// Unfortunately $aOutput is not really usable since we don't know its encoding (character set)
$aResult[] = new CheckResult(
CheckResult::ERROR,
"mysqldump could not be found. Please make sure it is installed and in the path."
);
} else {
// Unfortunately $aOutput is not really usable since we don't know its encoding (character set)
$aResult[] = new CheckResult(
CheckResult::ERROR,
"mysqldump could not be executed (retcode=$iRetCode): Please make sure it is installed and ".(empty($sMySQLBinDir) ? "in the path" : "located at : $sMySQLDump")
);
}
foreach ($aOutput as $sLine) {
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - mysqldump -V said: '.$sLine);
}
// create and test destination location
//
$sDestDir = dirname($sDBBackupPath);
setuputils::builddir($sDestDir);
if (!is_dir($sDestDir)) {
$aResult[] = new CheckResult(CheckResult::ERROR, "$sDestDir does not exist and could not be created.");
}
// check disk space
// to do... evaluate how we can correlate the DB size with the size of the dump (and the zip!)
// E.g. 2,28 Mb after a full install, giving a zip of 26 Kb (data = 26 Kb)
// Example of query (DB without a suffix)
//$sDBSize = "SELECT SUM(ROUND(DATA_LENGTH/1024/1024, 2)) AS size_mb FROM information_schema.TABLES WHERE TABLE_SCHEMA = `$sDBName`";
return $aResult;
}
/**
* Check that graphviz can be launched
*
* @param string $sGraphvizPath The path where graphviz' dot program is installed
*
* @return CheckResult[] The result of the check AS CheckResult::INFO or CheckResult::WARNING, plus debug traces as some
* CheckResult::TRACE
*
* @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE
*/
public static function CheckGraphviz($sGraphvizPath)
{
$aResult = [];
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - CheckGraphviz');
// availability of exec()
//
$aDisabled = explode(', ', ini_get('disable_functions'));
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - PHP functions disabled: '.implode(', ', $aDisabled));
if (in_array('exec', $aDisabled)) {
$aResult[] = new CheckResult(
CheckResult::ERROR,
self::GetStringForJsonEncode('The PHP exec() function has been disabled on this server', 'Could not find Graphviz\' dot')
);
}
// availability of dot / dot.exe
if (empty($sGraphvizPath)) {
$sGraphvizPath = 'dot';
} else {
clearstatcache();
if (!is_file($sGraphvizPath) || !is_executable($sGraphvizPath)) {
//N°3412 avoid shell injection
$aResult = [];
$aResult[] = new CheckResult(
CheckResult::WARNING,
self::GetStringForJsonEncode("$sGraphvizPath could not be executed: Please make sure it is installed and in the path", 'Graphviz could not be executed')
);
return $aResult;
}
if (!utils::IsWindowsEnvironment()) {
$sGraphvizPath = escapeshellcmd($sGraphvizPath);
}
}
$sCommand = "\"$sGraphvizPath\" -V 2>&1";
$aOutput = [];
$iRetCode = 0;
exec($sCommand, $aOutput, $iRetCode);
if ($iRetCode == 0) {
$aResult[] = new CheckResult(
CheckResult::INFO,
self::GetStringForJsonEncode("dot is present: ".$aOutput[0], 'Graphviz\' dot found')
);
} elseif ($iRetCode == 1) {
$aResult[] = new CheckResult(
CheckResult::WARNING,
self::GetStringForJsonEncode(
"dot could not be found: ".implode(' ', $aOutput)." - Please make sure it is installed and in the path.",
'Could not find Graphviz\' dot'
)
);
} else {
$aResult[] = new CheckResult(
CheckResult::WARNING,
self::GetStringForJsonEncode(
"dot could not be executed (retcode=$iRetCode): Please make sure it is installed and in the path",
'Could not find Graphviz\' dot'
)
);
}
foreach ($aOutput as $sLine) {
$aResult[] = new CheckResult(CheckResult::TRACE, 'Info - '.$sGraphvizPath.' -V said: '.$sLine);
}
return $aResult;
}
/**
* This was introduced as on Windows certain messages are not returned correctly :(
*
* @param string $sValue
* @param string $sFallbackValue
*
* @return string
*
* @since 3.0.0
*/
private static function GetStringForJsonEncode(string $sValue, string $sFallbackValue): string
{
return (json_encode($sValue) !== false)
? $sValue
: $sFallbackValue;
}
/**
* Helper function to retrieve the system's temporary directory
* Emulates sys_get_temp_dir if needed (PHP < 5.2.1)
*
* @return string Path to the system's temp directory
* @uses \sys_get_temp_dir()
*/
public static function GetTmpDir()
{
return realpath(sys_get_temp_dir());
}
/**
* Helper function to retrieve the directory where files are to be uploaded
*
* @return string Path to the temp directory used for uploading files
*/
public static function GetUploadTmpDir()
{
$sPath = ini_get('upload_tmp_dir');
if (empty($sPath)) {
$sPath = self::GetTmpDir();
}
return $sPath;
}
/**
* Helper to recursively remove a directory
* @param $dir
* @throws Exception
*/
public static function rrmdir($dir)
{
if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\')) {
throw new Exception("Attempting to delete directory: '$dir'");
}
self::tidydir($dir);
self::rmdir_safe($dir);
}
/**
* Helper to recursively cleanup a directory
*
* @param $dir
*
* @throws Exception
*/
public static function tidydir(string $dir): void
{
if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\')) {
throw new Exception("Attempting to delete directory: '$dir'");
}
if (is_dir($dir)) {
$aFiles = scandir($dir); // Warning glob('.*') does not seem to return the broken symbolic links, thus leaving a non-empty directory
if ($aFiles !== false) {
foreach ($aFiles as $file) {
if (($file != '.') && ($file != '..')) {
if (is_dir($dir.'/'.$file)) {
self::tidydir($dir.'/'.$file);
self::rmdir_safe($dir.'/'.$file);
} else {
if (!unlink($dir.'/'.$file)) {
SetupLog::Ok("Warning - FAILED to remove file '$dir/$file'");
} elseif (file_exists($dir.'/'.$file)) {
SetupLog::Ok("Warning - FAILED to remove file '$dir/.$file'");
}
}
}
}
}
}
}
/**
* Helper to build the full path of a new directory
* @param $dir
*/
public static function builddir($dir)
{
if (empty($dir)) {
// avoid infinite loops :/
return;
}
if (!is_dir($dir)) {
$parent = dirname($dir);
self::builddir($parent);
if (!mkdir($dir) && !is_dir($dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir));
}
}
}
public static function rmdir_safe($dir)
{
// avoid unnecessary warning
// Try 100 times...
$i = 100;
if (is_dir($dir)) {
while ((@rmdir($dir) === false) && $i > 0) {
// Magic trick for windows
// sometimes the folder is empty but rmdir fails
$oDir = opendir($dir);
if ($oDir !== false) {
closedir($oDir);
}
$i--;
}
if ($i == 0) {
rmdir($dir);
}
}
}
/**
* Helper to copy a directory to a target directory, skipping .SVN files (for developer's comfort!)
* Returns true if successful
* @param $sSource
* @param $sDest
* @param bool $bUseSymbolicLinks
* @return bool
* @throws Exception
*/
public static function copydir($sSource, $sDest, $bUseSymbolicLinks = false)
{
if (is_dir($sSource)) {
if (!is_dir($sDest)) {
mkdir($sDest, 0777 /* Default */, true);
}
$aFiles = scandir($sSource);
if (sizeof($aFiles) > 0) {
foreach ($aFiles as $sFile) {
if ($sFile == '.' || $sFile == '..' || $sFile == '.svn' || $sFile == '.git') {
// Skip
continue;
}
if (is_dir($sSource.'/'.$sFile)) {
// Recurse
self::copydir($sSource.'/'.$sFile, $sDest.'/'.$sFile, $bUseSymbolicLinks);
} else {
if ($bUseSymbolicLinks) {
if (function_exists('symlink')) {
if (file_exists($sDest.'/'.$sFile)) {
unlink($sDest.'/'.$sFile);
}
symlink($sSource.'/'.$sFile, $sDest.'/'.$sFile);
} else {
throw(new Exception("Error, cannot *copy* '$sSource/$sFile' to '$sDest/$sFile' using symbolic links, 'symlink' is not supported on this system."));
}
} else {
if (is_link($sDest.'/'.$sFile)) {
unlink($sDest.'/'.$sFile);
}
copy($sSource.'/'.$sFile, $sDest.'/'.$sFile);
}
}
}
}
return true;
} elseif (is_file($sSource)) {
if ($bUseSymbolicLinks) {
if (function_exists('symlink')) {
return symlink($sSource, $sDest);
} else {
throw(new Exception("Error, cannot *copy* '$sSource' to '$sDest' using symbolic links, 'symlink' is not supported on this system."));
}
} else {
return copy($sSource, $sDest);
}
} else {
return false;
}
}
/**
* Helper to move a directory when the parent directory of the target dir cannot be written
* To be used as alternative to rename()
* Files/Subdirs of the source directory are moved one by one
* Returns void
*
* @param string $sSource
* @param string $sDest
* @param boolean $bRemoveSource If true $sSource will be removed, otherwise $sSource will just be emptied
* @throws Exception
*/
public static function movedir($sSource, $sDest, $bRemoveSource = true)
{
if (!is_dir($sSource)) {
throw new Exception("movedir: the source directory '$sSource' is not a valid directory or cannot be read");
}
if (!is_dir($sDest)) {
self::builddir($sDest);
} else {
self::tidydir($sDest);
}
self::copydir($sSource, $sDest);
self::tidydir($sSource);
if ($bRemoveSource === true) {
self::rmdir_safe($sSource);
}
}
public static function GetPreviousInstance($sDir)
{
$sSourceDir = '';
$sSourceEnvironment = '';
$sConfigFile = '';
$aResult = [
'found' => false,
];
if (file_exists($sDir.'/config-itop.php')) {
$sSourceDir = $sDir;
$sSourceEnvironment = '';
$sConfigFile = $sDir.'/config-itop.php';
$aResult['found'] = true;
} elseif (file_exists($sDir.'/conf/production/config-itop.php')) {
$sSourceDir = $sDir;
$sSourceEnvironment = 'production';
$sConfigFile = $sDir.'/conf/production/config-itop.php';
$aResult['found'] = true;
}
if ($aResult['found']) {
$oPrevConf = new Config($sConfigFile);
$aResult = [
'found' => true,
'source_dir' => $sSourceDir,
'source_environment' => $sSourceEnvironment,
'configuration_file' => $sConfigFile,
'db_server' => $oPrevConf->Get('db_host'),
'db_user' => $oPrevConf->Get('db_user'),
'db_pwd' => $oPrevConf->Get('db_pwd'),
'db_name' => $oPrevConf->Get('db_name'),
'db_prefix' => $oPrevConf->Get('db_subname'),
'db_tls_enabled' => $oPrevConf->Get('db_tls.enabled'),
'db_tls_ca' => $oPrevConf->Get('db_tls.ca'),
'graphviz_path' => $oPrevConf->Get('graphviz_path'),
'mysql_bindir' => $oPrevConf->GetModuleSetting('itop-backup', 'mysql_bindir', ''),
];
}
return $aResult;
}
/**
* @param string $sDir
*
* @return bool|float false if failure
* @uses \disk_free_space()
*/
public static function CheckDiskSpace($sDir)
{
while (($f = @disk_free_space($sDir)) == false) {
if ($sDir == dirname($sDir)) {
break;
}
if ($sDir == '.') {
break;
}
$sDir = dirname($sDir);
}
return $f;
}
/**
* @param float $fBytes size in raw bytes, for example 162594750464.0
* @return string formatted string, for example "161.62 GB"
*
* @link https://en.wiktionary.org/wiki/byte byte and not Byte
* @link https://en.wikipedia.org/wiki/Kilobyte kB and not KB (IEC 80000-13)
* @link https://en.wiktionary.org/wiki/petabyte petabyte PB
* @link https://en.wiktionary.org/wiki/exabyte exabyte EB
*/
public static function HumanReadableSize($fBytes)
{
$aSizes = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'];
$index = 0;
while (($fBytes > 1000) && ($index < count($aSizes))) {