-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathutils.inc.php
More file actions
3229 lines (2901 loc) · 103 KB
/
utils.inc.php
File metadata and controls
3229 lines (2901 loc) · 103 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) 2013-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
*/
use Combodo\iTop\Application\Helper\Session;
use Combodo\iTop\Application\UI\Base\iUIBlock;
use Combodo\iTop\Application\UI\Base\Layout\UIContentBlock;
use Combodo\iTop\Application\UI\Hook\iKeyboardShortcut;
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Service\InterfaceDiscovery\InterfaceDiscovery;
use Combodo\iTop\Service\Module\ModuleService;
use ScssPhp\ScssPhp\Compiler;
use ScssPhp\ScssPhp\OutputStyle;
use ScssPhp\ScssPhp\ValueConverter;
use Soundasleep\Html2Text;
/**
* Static class utils
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
define('ITOP_CONFIG_FILE', 'config-itop.php');
define('ITOP_DEFAULT_CONFIG_FILE', APPCONF.ITOP_DEFAULT_ENV.'/'.ITOP_CONFIG_FILE);
define('SERVER_NAME_PLACEHOLDER', '$SERVER_NAME$');
define('SERVER_MAX_URL_LENGTH', 2048);
class FileUploadException extends Exception
{
}
/**
* Helper functions to interact with forms: read parameters, upload files...
* @package iTop
*/
class utils
{
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_INTEGER = 'integer';
/**
* Datamodel class
* @var string
* @since 2.7.10 3.0.0
* @since 2.7.10 3.0.4 3.1.1 3.2.0 N°6606 update PHPDoc
* @uses MetaModel::IsValidClass()
*/
public const ENUM_SANITIZATION_FILTER_CLASS = 'class';
/**
* @var string
* @since 2.7.10 3.0.4 3.1.1 3.2.0 N°6606
* @uses class_exists()
*/
public const ENUM_SANITIZATION_FILTER_PHP_CLASS = 'php_class';
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_STRING = 'string';
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_CONTEXT_PARAM = 'context_param';
/**
* @var string To filter routes passed to back-end router before being redirected to corresponding controller / method
* @since 3.1.0
*/
public const ENUM_SANITIZATION_FILTER_ROUTE = 'route';
/**
* @var string To filter operation codes passed to back-end router before being redirected to corresponding controller (/ business logic in case of legacy operations)
* @since 3.1.0
*/
public const ENUM_SANITIZATION_FILTER_OPERATION = 'operation';
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_PARAMETER = 'parameter';
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_FIELD_NAME = 'field_name';
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_TRANSACTION_ID = 'transaction_id';
/**
* @var string For XML / HTML node identifiers
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER = 'element_identifier';
/**
* @var string For XML / HTML node id/class selector
* @since 3.1.2 3.2.1
*/
public const ENUM_SANITIZATION_FILTER_ELEMENT_SELECTOR = 'element_selector';
/**
* @var string For variables names
* @since 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_VARIABLE_NAME = 'variable_name';
/**
* @var string
* @since 2.7.10 3.0.0
*/
public const ENUM_SANITIZATION_FILTER_RAW_DATA = 'raw_data';
/**
* @var string
* @since 3.0.2 3.1.0 N°4899
* @since 2.7.10 N°6606
*/
public const ENUM_SANITIZATION_FILTER_URL = 'url';
/**
* @var string
* @since 3.0.0
* @used-by static::GetMentionedObjectsFromText
*/
public const ENUM_TEXT_FORMAT_PLAIN = 'text';
/**
* @var string
* @since 3.0.0
* @used-by static::GetMentionedObjectsFromText
*/
public const ENUM_TEXT_FORMAT_HTML = 'html';
/**
* @var string
* @since 3.0.0
* @used-by static::GetMentionedObjectsFromText
*/
public const ENUM_TEXT_FORMAT_MARKDOWN = 'markdown';
/**
* @var string
* @since 3.0.0
*/
public const DEFAULT_SANITIZATION_FILTER = self::ENUM_SANITIZATION_FILTER_RAW_DATA;
/**
* Cache when getting config from disk or set externally (using {@link SetConfig})
* @internal
* @var Config $oConfig
* @see GetConfig
*/
private static $oConfig = null;
// Parameters loaded from a file, parameters of the page/command line still have precedence
private static $m_aParamsFromFile = null;
private static $m_aParamSource = [];
private static $iNextId = 0;
/**
* @var ?string
* @used-by GetAbsoluteUrlAppRoot
*/
private static $sAbsoluteUrlAppRootCache = null;
protected static function LoadParamFile($sParamFile)
{
if (!file_exists($sParamFile)) {
throw new Exception("Could not find the parameter file: '".utils::HtmlEntities($sParamFile)."'");
}
if (!is_readable($sParamFile)) {
throw new Exception("Could not load parameter file: '".utils::HtmlEntities($sParamFile)."'");
}
$sParams = file_get_contents($sParamFile);
if (is_null(self::$m_aParamsFromFile)) {
self::$m_aParamsFromFile = [];
}
$aParamLines = explode("\n", $sParams ?? '');
foreach ($aParamLines as $sLine) {
$sLine = trim($sLine);
// Ignore the line after a '#'
if (($iCommentPos = strpos($sLine, '#')) !== false) {
$sLine = substr($sLine, 0, $iCommentPos);
$sLine = trim($sLine);
}
// Note: the line is supposed to be already trimmed
if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches)) {
$sParam = $aMatches[1];
$value = trim($aMatches[2]);
self::$m_aParamsFromFile[$sParam] = $value;
self::$m_aParamSource[$sParam] = $sParamFile;
}
}
}
public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
{
$sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI, 'raw_data');
foreach (explode(',', $sFileSpec) as $sFile) {
$sFile = trim($sFile);
if (!empty($sFile)) {
self::LoadParamFile($sFile);
}
}
}
/**
* Return the source file from which the parameter has been found,
* useful when it comes to pass user credential to a process executed
* in the background
* @param string $sName Parameter name
* @return string|null The file name if any, or null
*/
public static function GetParamSourceFile($sName)
{
if (array_key_exists($sName, self::$m_aParamSource)) {
return self::$m_aParamSource[$sName];
} else {
return null;
}
}
public static function IsModeCLI()
{
$sCleanName = strtolower(trim(PHP_SAPI));
return ($sCleanName === 'cli');
}
/**
* @return bool true if we're in an XHR query
* @see \Symfony\Component\HttpFoundation\Request::IsXmlHttpRequest
*
* @since 3.0.0 N°3750 method creation
*/
public static function IsXmlHttpRequest()
{
$sXhrHeaderName = 'X-Requested-With';
$sXhrHeaderIndexName = 'HTTP_'.str_replace('-', '_', strtoupper($sXhrHeaderName));
$sXhrHeader = $_SERVER[$sXhrHeaderIndexName] ?? null;
return ('XMLHttpRequest' === $sXhrHeader);
}
protected static $bPageMode = null;
/**
* @var boolean[]
*/
protected static $aModes = [];
public static function InitArchiveMode()
{
if (Session::IsSet('archive_mode')) {
$iDefault = Session::Get('archive_mode');
} else {
$iDefault = 0;
}
// Read and record the value for switching the archive mode
$iCurrent = self::ReadParam('with-archive', $iDefault);
if (Session::IsInitialized()) {
Session::Set('archive_mode', $iCurrent);
}
// Read and use the value for the current page (web services)
$iCurrent = self::ReadParam('with_archive', $iCurrent, true);
self::$bPageMode = ($iCurrent == 1);
}
/**
* @param boolean $bMode if true then activate archive mode (archived objects are visible), otherwise archived objects are
* hidden (archive = "soft deletion")
*/
public static function PushArchiveMode($bMode)
{
array_push(self::$aModes, $bMode);
}
public static function PopArchiveMode()
{
array_pop(self::$aModes);
}
/**
* @return boolean true if archive mode is enabled
*/
public static function IsArchiveMode()
{
if (count(self::$aModes) > 0) {
$bRet = end(self::$aModes);
} else {
if (self::$bPageMode === null) {
self::InitArchiveMode();
}
$bRet = self::$bPageMode;
}
return $bRet;
}
/**
* Helper to be called by the GUI and define if the user will see obsolete data (otherwise, the user will have to dig further)
* @return bool
*/
public static function ShowObsoleteData()
{
$bDefault = MetaModel::GetConfig()->Get('obsolescence.show_obsolete_data'); // default is false
$bShow = appUserPreferences::GetPref('show_obsolete_data', $bDefault);
if (static::IsArchiveMode()) {
$bShow = true;
}
return $bShow;
}
public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false, $sSanitizationFilter = 'parameter')
{
global $argv;
$retValue = $defaultValue;
if (!is_null(self::$m_aParamsFromFile)) {
if (isset(self::$m_aParamsFromFile[$sName])) {
$retValue = self::$m_aParamsFromFile[$sName];
}
}
if (isset($_REQUEST[$sName])) {
$retValue = $_REQUEST[$sName];
} elseif ($bAllowCLI && isset($argv)) {
foreach ($argv as $iArg => $sArg) {
if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches)) {
$retValue = $aMatches[1];
}
}
}
return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
}
public static function ReadPostedParam($sName, $defaultValue = '', $sSanitizationFilter = 'parameter')
{
$retValue = isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
}
public static function Sanitize($value, $defaultValue, $sSanitizationFilter)
{
if ($value === $defaultValue) {
// Preserve the real default value (can be used to detect missing mandatory parameters)
$retValue = $value;
} else {
$retValue = self::Sanitize_Internal($value, $sSanitizationFilter);
if ($retValue === false) {
$retValue = $defaultValue;
}
}
return $retValue;
}
/**
* @param string|string[] $value
* @param string $sSanitizationFilter one of utils::ENUM_SANITIZATION_* const
*
* @return string|string[]|bool boolean for :
* * the 'class' filter (true if valid, false otherwise)
* * if the filter fails ({@link \filter_var()} return value)
*
* @throws \CoreException
*
* @uses \filter_var()
*
* @since 2.5.2 2.6.0 new 'transaction_id' filter
* @since 2.7.0 new 'element_identifier' filter
* @since 3.0.0 new utils::ENUM_SANITIZATION_* const
* @since 2.7.7, 3.0.2, 3.1.0 N°4899 - new 'url' filter
* @since 2.7.10 N°6606 use the utils::ENUM_SANITIZATION_* const
* @since 2.7.10 N°6606 new case for ENUM_SANITIZATION_FILTER_PHP_CLASS
* @since 3.2.1-1 N°8242 Allow value to be an array for every filter
*
* @link https://www.php.net/manual/en/filter.filters.sanitize.php PHP sanitization filters
*/
protected static function Sanitize_Internal($value, $sSanitizationFilter)
{
if (is_array($value)) {
$retValue = [];
foreach ($value as $key => $val) {
$retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays
if ($retValue[$key] === false) {
return false;
}
}
return $retValue;
}
switch ($sSanitizationFilter) {
case static::ENUM_SANITIZATION_FILTER_INTEGER:
$retValue = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
break;
case static::ENUM_SANITIZATION_FILTER_CLASS:
$retValue = $value;
if (($value != '') && !MetaModel::IsValidClass($value)) {
throw new CoreException(Dict::Format('UI:OQL:UnknownClassNoFix', utils::HtmlEntities($value)));
}
break;
case static::ENUM_SANITIZATION_FILTER_STRING:
$retValue = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
break;
case static::ENUM_SANITIZATION_FILTER_PHP_CLASS:
$retValue = $value;
if (!class_exists($value)) {
$retValue = false;
}
break;
case static::ENUM_SANITIZATION_FILTER_CONTEXT_PARAM:
case static::ENUM_SANITIZATION_FILTER_ROUTE:
case static::ENUM_SANITIZATION_FILTER_OPERATION:
case static::ENUM_SANITIZATION_FILTER_PARAMETER:
case static::ENUM_SANITIZATION_FILTER_FIELD_NAME:
case static::ENUM_SANITIZATION_FILTER_TRANSACTION_ID:
switch ($sSanitizationFilter) {
case static::ENUM_SANITIZATION_FILTER_TRANSACTION_ID:
// Same as parameter type but keep the dot character
// transaction_id, the dot is mostly for Windows servers when using file storage as the tokens are named *.tmp
// - See N°1835
// - Note: It must be included at the regexp beginning otherwise you'll get an invalid character error
$retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[\. A-Za-z0-9_=-]*$/']]);
break;
case static::ENUM_SANITIZATION_FILTER_ROUTE:
case static::ENUM_SANITIZATION_FILTER_OPERATION:
// - Routes should be of the "controller_namespace_code.controller_method_name" form
// - Operations should be allowed to be namespaced as well even though then don't have dedicated controller yet
$retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[\.A-Za-z0-9_-]*$/']]);
break;
case static::ENUM_SANITIZATION_FILTER_PARAMETER:
$retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[ A-Za-z0-9_=-]*$/']]); // the '=', '%3D, '%2B', '%2F'
// Characters are used in serialized filters (starting 2.5, only the url encoded versions are presents, but the "=" is kept for BC)
break;
case static::ENUM_SANITIZATION_FILTER_FIELD_NAME:
$retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[A-Za-z0-9_]+(->[A-Za-z0-9_]+)*$/']]); // att_code or att_code->name or AttCode->Name or AttCode->Key2->Name
break;
case static::ENUM_SANITIZATION_FILTER_CONTEXT_PARAM:
$retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[ A-Za-z0-9_=%:+-]*$/']]);
break;
}
break;
// For XML / HTML node identifiers
case static::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER:
$retValue = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
$retValue = filter_var(
$retValue,
FILTER_VALIDATE_REGEXP,
['options' => ['regexp' => '/^[A-Za-z0-9][A-Za-z0-9_-]*$/']]
);
break;
// For XML / HTML node id selector
case static::ENUM_SANITIZATION_FILTER_ELEMENT_SELECTOR:
$retValue = filter_var(
$value,
FILTER_VALIDATE_REGEXP,
['options' => ['regexp' => '/^[#\.][A-Za-z0-9][A-Za-z0-9_-]*$/']]
);
break;
case static::ENUM_SANITIZATION_FILTER_VARIABLE_NAME:
$retValue = preg_replace('/[^a-zA-Z0-9_]/', '', $value);
break;
// For URL
case static::ENUM_SANITIZATION_FILTER_URL:
$retValue = filter_var($value, FILTER_SANITIZE_URL);
$retValue = filter_var($retValue, FILTER_VALIDATE_URL);
break;
default:
case static::ENUM_SANITIZATION_FILTER_RAW_DATA:
$retValue = $value;
// Do nothing
}
return $retValue;
}
/**
* Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
*
* @param string $sName Name of the input used from uploading the file
* @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
*
* @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
* @throws \FileUploadException
*/
public static function ReadPostedDocument($sName, $sIndex = null)
{
$oDocument = new ormDocument(); // an empty document
if (isset($_FILES[$sName])) {
$aFileInfo = $_FILES[$sName];
$sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
switch ($sError) {
case UPLOAD_ERR_OK:
$sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
$sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
$sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
$doc_content = file_get_contents($sTmpName);
$sMimeType = self::GetFileMimeType($sTmpName);
$oDocument = new ormDocument($doc_content, $sMimeType, $sName);
break;
case UPLOAD_ERR_NO_FILE:
// no file to load, it's a normal case, just return an empty document
break;
case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_INI_SIZE:
throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
break;
case UPLOAD_ERR_PARTIAL:
throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
break;
case UPLOAD_ERR_CANT_WRITE:
throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
break;
case UPLOAD_ERR_EXTENSION:
$sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
break;
default:
throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
break;
}
}
return $oDocument;
}
/**
* Interprets the results posted by a normal or paginated list (in multiple selection mode)
*
* @param DBSearch $oFullSetFilter The criteria defining the whole sets of objects being selected
*
* @return array An array of object IDs corresponding to the objects selected in the set
* @throws \CoreException
* @throws \CoreUnexpectedValue
* @throws \MySQLException
*/
public static function ReadMultipleSelection($oFullSetFilter)
{
$aSelectedObj = utils::ReadParam('selectObject', []);
$sSelectionMode = utils::ReadParam('selectionMode', '');
if ($sSelectionMode != '') {
// Paginated selection
$aExceptions = utils::ReadParam('storedSelection', []);
if ($sSelectionMode == 'positive') {
// Only the explicitely listed items are selected
$aSelectedObj = $aExceptions;
} else {
// All items of the set are selected, except the one explicitely listed
$aSelectedObj = [];
$oFullSet = new DBObjectSet($oFullSetFilter);
$sClassAlias = $oFullSetFilter->GetClassAlias();
$oFullSet->OptimizeColumnLoad([$sClassAlias => ['friendlyname']]); // We really need only the IDs but it does not work since id is not a real field
while ($oObj = $oFullSet->Fetch()) {
if (!in_array($oObj->GetKey(), $aExceptions)) {
$aSelectedObj[] = $oObj->GetKey();
}
}
}
}
return $aSelectedObj;
}
/**
* Interprets the results posted by a normal or paginated list (in multiple selection mode)
*
* @param DBSearch $oFullSetFilter The criteria defining the whole sets of objects being selected
*
* @return Array An array of object IDs:friendlyname corresponding to the objects selected in the set
* @throws \CoreException
*/
public static function ReadMultipleSelectionWithFriendlyname($oFullSetFilter)
{
$sSelectionMode = utils::ReadParam('selectionMode', '');
if ($sSelectionMode != 'positive' && $sSelectionMode != 'negative') {
throw new CoreException('selectionMode must be either positive or negative');
}
// Paginated selection
$aSelectedIds = utils::ReadParam('storedSelection', []);
$aSelectedObjIds = utils::ReadParam('selectObject', []);
//it means that the user has selected all the results of the search query
if (count($aSelectedObjIds) > 0) {
$sFilter = utils::ReadParam("sFilter", '', false, 'raw_data');
if ($sFilter != '') {
$oFullSetFilter = DBSearch::unserialize($sFilter);
}
}
if (count($aSelectedIds) > 0) {
if ($sSelectionMode == 'positive') {
// Only the explicitly listed items are selected
$oFullSetFilter->AddCondition('id', $aSelectedIds, 'IN');
} else {
// All items of the set are selected, except the one explicitly listed
$oFullSetFilter->AddCondition('id', $aSelectedIds, 'NOTIN');
}
}
$aSelectedObj = [];
$oFullSet = new DBObjectSet($oFullSetFilter);
$sClassAlias = $oFullSetFilter->GetClassAlias();
$oFullSet->OptimizeColumnLoad([$sClassAlias => ['friendlyname']]); // We really need only the IDs but it does not work since id is not a real field
while ($oObj = $oFullSet->Fetch()) {
$aSelectedObj[$oObj->GetKey()] = $oObj->Get('friendlyname');
}
return $aSelectedObj;
}
public static function GetNewTransactionId()
{
return privUITransaction::GetNewTransactionId();
}
public static function IsTransactionValid($sId, $bRemoveTransaction = true)
{
return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
}
public static function RemoveTransaction($sId)
{
return privUITransaction::RemoveTransaction($sId);
}
/**
* Build as static::GetNewTransactionId()
*
* @param string $sTransactionId
*
* @return string unique tmp id for the current upload based on the transaction system (db). Build as static::GetNewTransactionId()
*/
public static function GetUploadTempId($sTransactionId = null)
{
if ($sTransactionId === null) {
$sTransactionId = static::GetNewTransactionId();
}
return $sTransactionId;
}
public static function ReadFromFile($sFileName)
{
if (!file_exists($sFileName)) {
return false;
}
return file_get_contents($sFileName);
}
/**
* @param mixed $value The value as read from php.ini (eg 256k, 2M, 1G etc.)
*
* @return int conversion to number of bytes
*
* @since 2.7.5 3.0.0 convert to int numeric values
*
* @link https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes Shorthand bytes value reference in PHP.net FAQ
*/
public static function ConvertToBytes($value)
{
if (!is_numeric($value)) {
$iLength = strlen($value);
$iReturn = substr($value, 0, $iLength - 1);
$sUnit = strtoupper(substr($value, $iLength - 1));
switch ($sUnit) {
case 'G':
$iReturn *= 1024;
// no break
case 'M':
$iReturn *= 1024;
// no break
case 'K':
$iReturn *= 1024;
}
} else {
$iReturn = (int)$value;
}
return $iReturn;
}
/**
* Checks if the memory limit is at least what is required
*
* @param int $iMemoryLimit set limit in bytes, use {@link utils::ConvertToBytes()} to convert current php.ini value
* @param int $iRequiredLimit required limit in bytes
*
* @return bool
*/
public static function IsMemoryLimitOk($iMemoryLimit, $iRequiredLimit)
{
if ($iMemoryLimit === -1) {
// -1 means : no limit (see https://www.php.net/manual/fr/ini.core.php#ini.memory-limit)
return true;
}
return ($iMemoryLimit >= $iRequiredLimit);
}
/**
* Set memory_limit to required value
*
* @param string $sRequiredLimit required limit, for example '512M'
*
* @return bool|null null if nothing was done, true if modifying memory_limit was successful, false otherwise
*
* @uses utils::ConvertToBytes()
* @uses \ini_get('memory_limit')
* @uses \ini_set()
* @uses utils::ConvertToBytes()
*
* @since 2.7.5 N°3806
*/
public static function SetMinMemoryLimit($sRequiredLimit)
{
$iRequiredLimit = static::ConvertToBytes($sRequiredLimit);
$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
return false;
}
$iMemoryLimit = static::ConvertToBytes($sMemoryLimit);
if (static::IsMemoryLimitOk($iMemoryLimit, $iRequiredLimit)) {
return null;
}
return ini_set('memory_limit', $iRequiredLimit);
}
/**
* Format a value into a more friendly format (KB, MB, GB, TB) instead a juste a Bytes amount.
*
* @param float $value
* @param int $iPrecision
*
* @return string
*/
public static function BytesToFriendlyFormat($value, $iPrecision = 0)
{
$sReturn = '';
// Kilobytes
if ($value >= 1024) {
$sReturn = 'K';
$value = $value / 1024;
if ($iPrecision === 0) {
$iPrecision = 1;
}
}
// Megabytes
if ($value >= 1024) {
$sReturn = 'M';
$value = $value / 1024;
}
// Gigabytes
if ($value >= 1024) {
$sReturn = 'G';
$value = $value / 1024;
}
// Terabytes
if ($value >= 1024) {
$sReturn = 'T';
$value = $value / 1024;
}
$value = round($value, $iPrecision);
return $value.''.$sReturn.'B';
}
/**
* Helper function to convert a string to a date, given a format specification. It replaces strtotime which does not allow for
* specifying a date in a french format (for instance) Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
*
* @param string $sDate
* @param string $sFormat
*
* @return string|false false if the input format is not correct, timestamp otherwise
*/
public static function StringToTime($sDate, $sFormat)
{
// Source: http://php.net/manual/fr/function.strftime.php
// (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
static $aDateTokens = null;
static $aDateRegexps = null;
if (is_null($aDateTokens)) {
$aSpec = [
'%d' => '(?<day>[0-9]{2})',
'%m' => '(?<month>[0-9]{2})',
'%y' => '(?<year>[0-9]{2})',
'%Y' => '(?<year>[0-9]{4})',
'%H' => '(?<hour>[0-2][0-9])',
'%i' => '(?<minute>[0-5][0-9])',
'%s' => '(?<second>[0-5][0-9])',
];
$aDateTokens = array_keys($aSpec);
$aDateRegexps = array_values($aSpec);
}
$sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches)) {
$sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
$sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
$sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
$sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
$sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
$sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
} else {
return false;
}
// http://www.spaweditor.com/scripts/regex/index.php
}
/**
* Convert an old date/time format specification (using % placeholders)
* to a format compatible with DateTime::createFromFormat
* @param string $sOldDateTimeFormat
* @return string
*/
public static function DateTimeFormatToPHP($sOldDateTimeFormat)
{
$aSearch = ['%d', '%m', '%y', '%Y', '%H', '%i', '%s'];
$aReplacement = ['d', 'm', 'y', 'Y', 'H', 'i', 's'];
return str_replace($aSearch, $aReplacement, $sOldDateTimeFormat);
}
/**
* Convert an old strtime() date/time format specification {@link https://www.php.net/manual/fr/function.strftime.php}
* to a format compatible with \DateTime::format {@link https://www.php.net/manual/fr/datetime.format.php}
*
* Example: '%Y-%m-%d %H:%M:%S' => 'Y-m-d H:i:s'
*
* Note: Not all strftime() formats can be converted, in which case they will be present in the returned string (eg. '%U' or '%W')
*
* @param string $sOldStrftimeFormat
*
* @return string
* @since 3.1.0
*/
public static function StrftimeFormatToDateTimeFormat(string $sOldStrftimeFormat): string
{
$aSearch = [
'%d', '%m', '%y', '%Y', '%H', '%M', '%S', // Most popular formats
'%a', '%A', '%e', '%j', '%u', '%w', // Day formats
'%U', '%V', '%W', // Week formats
'%b', '%B', '%h', // Month formats
'%C', '%g', '%G', // Year formats
'%k', '%I', '%l', '%p', '%P', '%r', '%R', '%T', '%X', '%z', '%Z', // Time formats
'%c', '%D', '%F', '%s', '%x', // Datetime formats
'%n', '%t', '%%', // Misc. formats
];
$aReplacement = [
'd', 'm', 'y', 'Y', 'H', 'i', 's',
'D', 'l', 'j', 'z', 'N', 'w',
'%U', 'W', '%W',
'M', 'F', 'M',
'%C', 'y', 'Y',
'G', 'h', 'g', 'A', 'a', 'h:i:s A', 'H:i', 'H:i:s', '%X', 'O', 'T',
'%c', 'm/d/y', 'Y-m-d', 'U', '%x',
'%n', '%t', '%',
];
return str_replace($aSearch, $aReplacement, $sOldStrftimeFormat);
}
/**
* Allow to set cached config. Useful when running with {@link Parameters} for example.
* @param \Config $oConfig
*/
public static function SetConfig(Config $oConfig)
{
self::$oConfig = $oConfig;
}
/**
* @param boolean $bForceGetFromDisk if true then will always read from disk without using instances in memory
*
* @return \Config Get object in the following order :
* <ol>
* <li>from {@link MetaModel::GetConfig} if loaded
* <li>{@link oConfig} attribute if set
* <li>from disk (current env, using {@link GetConfigFilePath}) => if loaded this will be stored in {@link oConfig} attribute
* <li>from disk, env production => if loaded this will be stored in {@link oConfig} attribute
* <li>default Config object
* </ol>
* @throws \ConfigException
* @throws \CoreException
*
* @since 2.7.0 N°2478 this method will now always call {@link MetaModel::GetConfig} first, and cache in this class is only set when loading from disk
* @since 3.0.0 N°4158 new $bReadFromDisk parameter
*/
public static function GetConfig($bForceGetFromDisk = false)
{
if (!$bForceGetFromDisk) {
$oMetaModelConfig = MetaModel::GetConfig();
if ($oMetaModelConfig !== null) {
return $oMetaModelConfig;
}
if (self::$oConfig !== null) {
return self::$oConfig;
}
}
$sCurrentEnvConfigPath = self::GetConfigFilePath();
if (file_exists($sCurrentEnvConfigPath)) {
$oCurrentEnvDiskConfig = new Config($sCurrentEnvConfigPath);
self::SetConfig($oCurrentEnvDiskConfig);
return self::$oConfig;
}
$sProductionEnvConfigPath = self::GetConfigFilePath('production');
if (file_exists($sProductionEnvConfigPath)) {
$oProductionEnvDiskConfig = new Config($sProductionEnvConfigPath);
self::SetConfig($oProductionEnvDiskConfig);
return self::$oConfig;
}
return new Config();
}
public static function InitTimeZone($oConfig = null)
{
if (is_null($oConfig)) {
$oConfig = self::GetConfig();
}
$sItopTimeZone = $oConfig->Get('timezone');
if (!empty($sItopTimeZone)) {
date_default_timezone_set($sItopTimeZone);
}
// else
// {
// // Leave as is... up to the admin to set a value somewhere...
// // see http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
// }
}
/**
* @return bool The boolean value of the conf. "behind_reverse_proxy" (except if there is no REMOTE_ADDR int his case, it return false)
*
* @since 2.7.4
*/
public static function IsProxyTrusted()
{
if (empty($_SERVER['REMOTE_ADDR'])) {
return false;
}
$bTrustProxies = (bool) self::GetConfig()->Get('behind_reverse_proxy');
return $bTrustProxies;