/
Toolbox.php
3634 lines (3194 loc) · 110 KB
/
Toolbox.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
/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2022 Teclib' and contributors.
* @copyright 2003-2014 by the INDEPNET Development Team.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------
*/
use Glpi\Console\Application;
use Glpi\Event;
use Glpi\Mail\Protocol\ProtocolInterface;
use Glpi\Toolbox\Sanitizer;
use Glpi\Toolbox\VersionParser;
use Laminas\Mail\Storage\AbstractStorage;
use Mexitek\PHPColors\Color;
use Monolog\Logger;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Toolbox Class
**/
class Toolbox
{
/**
* Wrapper for max_input_vars
*
* @since 0.84
*
* @return integer
**/
public static function get_max_input_vars()
{
$max = ini_get('max_input_vars'); // Security limit since PHP 5.3.9
if (!$max) {
$max = ini_get('suhosin.post.max_vars'); // Security limit from Suhosin
}
return $max;
}
/**
* Convert first caracter in upper
*
* @since 0.83
* @since 9.3 Rework
*
* @param string $str string to change
*
* @return string
**/
public static function ucfirst($str)
{
$first_letter = mb_strtoupper(mb_substr($str, 0, 1));
$str_end = mb_substr($str, 1, mb_strlen($str));
return $first_letter . $str_end;
}
/**
* to underline shortcut letter
*
* @since 0.83
*
* @param string $str from dico
* @param string $shortcut letter of shortcut
*
* @return string
**/
public static function shortcut($str, $shortcut)
{
$pos = self::strpos(self::strtolower($str), self::strtolower($shortcut));
if ($pos !== false) {
return self::substr($str, 0, $pos) .
"<u>" . self::substr($str, $pos, 1) . "</u>" .
self::substr($str, $pos + 1);
}
return $str;
}
/**
* substr function for utf8 string
*
* @param string $str string
* @param string $tofound string to found
* @param integer $offset The search offset. If it is not specified, 0 is used.
*
* @return integer|false
**/
public static function strpos($str, $tofound, $offset = 0)
{
return mb_strpos($str, $tofound, $offset, "UTF-8");
}
/**
* Replace str_pad()
* who bug with utf8
*
* @param string $input input string
* @param integer $pad_length padding length
* @param string $pad_string padding string
* @param integer $pad_type padding type
*
* @return string
**/
public static function str_pad($input, $pad_length, $pad_string = " ", $pad_type = STR_PAD_RIGHT)
{
$diff = (strlen($input) - self::strlen($input));
return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
}
/**
* strlen function for utf8 string
*
* @param string $str
*
* @return integer length of the string
**/
public static function strlen($str)
{
return mb_strlen($str, "UTF-8");
}
/**
* substr function for utf8 string
*
* @param string $str
* @param integer $start start of the result substring
* @param integer $length The maximum length of the returned string if > 0 (default -1)
*
* @return string
**/
public static function substr($str, $start, $length = -1)
{
if ($length == -1) {
$length = self::strlen($str) - $start;
}
return mb_substr($str, $start, $length, "UTF-8");
}
/**
* strtolower function for utf8 string
*
* @param string $str
*
* @return string lower case string
**/
public static function strtolower($str)
{
return mb_strtolower($str, "UTF-8");
}
/**
* strtoupper function for utf8 string
*
* @param string $str
*
* @return string upper case string
**/
public static function strtoupper($str)
{
return mb_strtoupper($str, "UTF-8");
}
/**
* Is a string seems to be UTF-8 one ?
*
* @param $str string string to analyse
*
* @return boolean
**/
public static function seems_utf8($str)
{
return mb_check_encoding($str, "UTF-8");
}
/**
* Encode string to UTF-8
*
* @param string $string string to convert
* @param string $from_charset original charset (if 'auto' try to autodetect)
*
* @return string utf8 string
**/
public static function encodeInUtf8($string, $from_charset = "ISO-8859-1")
{
if (strcmp($from_charset, "auto") == 0) {
$from_charset = mb_detect_encoding($string);
}
return mb_convert_encoding($string, "UTF-8", $from_charset);
}
/**
* Decode string from UTF-8 to specified charset
*
* @param string $string string to convert
* @param string $to_charset destination charset (default "ISO-8859-1")
*
* @return string converted string
**/
public static function decodeFromUtf8($string, $to_charset = "ISO-8859-1")
{
return mb_convert_encoding($string, $to_charset, "UTF-8");
}
/**
* @deprecated 10.0.0
*/
public static function sodiumEncrypt($content, $key = null)
{
Toolbox::deprecated('Use "GLPIKey::encrypt()"');
$glpikey = new GLPIKey();
return $glpikey->encrypt($content, $key);
}
/**
* @deprecated 10.0.0
*/
public static function sodiumDecrypt($content, $key = null)
{
Toolbox::deprecated('Use "GLPIKey::decrypt()"');
$glpikey = new GLPIKey();
return $glpikey->decrypt($content, $key);
}
/**
* Prevent from XSS
* Clean code
*
* @param array|string $value item to prevent
*
* @return array|string clean item
*
* @see unclean_cross_side_scripting_deep*
*
* @deprecated 10.0.0
**/
public static function clean_cross_side_scripting_deep($value)
{
Toolbox::deprecated('Use "Glpi\Toolbox\Sanitizer::encodeHtmlSpecialCharsRecursive()"');
return Sanitizer::encodeHtmlSpecialCharsRecursive($value);
}
/**
* Invert fonction from clean_cross_side_scripting_deep
*
* @param array|string $value item to unclean from clean_cross_side_scripting_deep
*
* @return array|string unclean item
*
* @see clean_cross_side_scripting_deep()
*
* @deprecated 10.0.0
**/
public static function unclean_cross_side_scripting_deep($value)
{
Toolbox::deprecated('Use "Glpi\Toolbox\Sanitizer::decodeHtmlSpecialCharsRecursive()"');
global $DB;
return $DB->escape(Sanitizer::decodeHtmlSpecialCharsRecursive($value));
}
/**
* Returns a safe configuration for htmLawed.
*
* @return array
*
* @since 9.5.4
*/
public static function getHtmLawedSafeConfig(): array
{
$config = [
'elements' => '* -applet -canvas -embed -form -object -script -link -meta',
'deny_attribute' => 'on*, srcdoc',
'comment' => 1, // 1: remove HTML comments (and do not display their contents)
'cdata' => 1, // 1: remove CDATA sections (and do not display their contents)
'direct_list_nest' => 1, // 1: Allow usage of ul/ol tags nested in other ul/ol tags
'schemes' => 'href: aim, app, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, tel, telnet, notes; *: file, http, https',
'no_deprecated_attr' => 0, // 0: do not transform deprecated HTML attributes
];
if (!GLPI_ALLOW_IFRAME_IN_RICH_TEXT) {
$config['elements'] .= '-iframe';
}
return $config;
}
/**
* Log in 'php-errors' all args
*
* @param Logger $logger Logger instance, if any
* @param integer $level Log level (defaults to warning)
* @param array $args Arguments (message to log, ...)
*
* @return void
**/
private static function log($logger = null, $level = Logger::WARNING, $args = null)
{
static $tps = 0;
$extra = [];
if (method_exists('Session', 'getLoginUserID')) {
$extra['user'] = Session::getLoginUserID() . '@' . php_uname('n');
}
if ($tps && function_exists('memory_get_usage')) {
$extra['mem_usage'] = number_format(microtime(true) - $tps, 3) . '", ' .
number_format(memory_get_usage() / 1024 / 1024, 2) . 'Mio)';
}
$msg = "";
if (function_exists('debug_backtrace')) {
$bt = debug_backtrace();
if (count($bt) > 2) {
if (isset($bt[2]['class'])) {
$msg .= $bt[2]['class'] . '::';
}
$msg .= $bt[2]['function'] . '() in ';
}
$msg .= $bt[1]['file'] . ' line ' . $bt[1]['line'] . "\n";
}
if ($args == null) {
$args = func_get_args();
} else if (!is_array($args)) {
$args = [$args];
}
foreach ($args as $arg) {
if (is_array($arg) || is_object($arg)) {
$msg .= str_replace("\n", "\n ", print_r($arg, true));
} else if (is_null($arg)) {
$msg .= 'NULL ';
} else if (is_bool($arg)) {
$msg .= ($arg ? 'true' : 'false') . ' ';
} else {
$msg .= $arg . ' ';
}
}
$tps = microtime(true);
if ($logger === null) {
global $PHPLOGGER;
$logger = $PHPLOGGER;
}
try {
$logger->addRecord($level, $msg, $extra);
} catch (\Exception $e) {
//something went wrong, make sure logging does not cause fatal
error_log($e);
}
global $SQLLOGGER;
if (isCommandLine() && $level >= Logger::WARNING && $logger !== $SQLLOGGER) {
// Do not output related messages to $SQLLOGGER as they are redundant with
// output made by "ErrorHandler::handleSql*()" methods.
echo $msg;
}
}
/**
* PHP debug log
*/
public static function logDebug()
{
self::log(null, Logger::DEBUG, func_get_args());
}
/**
* PHP notice log
*/
public static function logNotice()
{
self::deprecated(
'Use either native trigger_error($msg, E_USER_NOTICE) to log notices,'
. ' either Glpi\\Application\\ErrorHandler::handleException() to log exceptions,'
. ' either Toolbox::logInfo() or Toolbox::logDebug() to log messages not related to errors.'
);
self::log(null, Logger::NOTICE, func_get_args());
}
/**
* PHP info log
*/
public static function logInfo()
{
self::log(null, Logger::INFO, func_get_args());
}
/**
* PHP warning log
*/
public static function logWarning()
{
self::deprecated(
'Use either native trigger_error($msg, E_USER_WARNING) to log warnings,'
. ' either Glpi\\Application\\ErrorHandler::handleException() to log exceptions,'
. ' either Toolbox::logInfo() or Toolbox::logDebug() to log messages not related to errors.'
);
self::log(null, Logger::WARNING, func_get_args());
}
/**
* PHP error log
*/
public static function logError()
{
self::deprecated(
'Use either native trigger_error($msg, E_USER_WARNING) to log errors,'
. ' either Glpi\\Application\\ErrorHandler::handleException() to log exceptions,'
. ' either Toolbox::logInfo() or Toolbox::logDebug() to log messages not related to errors.'
);
self::log(null, Logger::ERROR, func_get_args());
}
/**
* SQL debug log
*/
public static function logSqlDebug()
{
global $SQLLOGGER;
$args = func_get_args();
self::log($SQLLOGGER, Logger::DEBUG, $args);
}
/**
* SQL warning log
*/
public static function logSqlWarning()
{
global $SQLLOGGER;
$args = func_get_args();
self::log($SQLLOGGER, Logger::WARNING, $args);
}
/**
* SQL error log
*/
public static function logSqlError()
{
global $SQLLOGGER;
$args = func_get_args();
self::log($SQLLOGGER, Logger::ERROR, $args);
}
/**
* Generate a Backtrace
*
* @param string $log Log file name (default php-errors) if false, return the string
* @param string $hide Call to hide (but display script/line)
* @param array $skip Calls to not display at all
*
* @return string
*
* @since 0.85
**/
public static function backtrace($log = 'php-errors', $hide = '', array $skip = [])
{
if (function_exists("debug_backtrace")) {
$message = " Backtrace :\n";
$traces = debug_backtrace();
foreach ($traces as $trace) {
$script = (isset($trace["file"]) ? $trace["file"] : "") . ":" .
(isset($trace["line"]) ? $trace["line"] : "");
if (strpos($script, GLPI_ROOT) === 0) {
$script = substr($script, strlen(GLPI_ROOT) + 1);
}
if (strlen($script) > 50) {
$script = "..." . substr($script, -47);
} else {
$script = str_pad($script, 50);
}
$call = (isset($trace["class"]) ? $trace["class"] : "") .
(isset($trace["type"]) ? $trace["type"] : "") .
(isset($trace["function"]) ? $trace["function"] . "()" : "");
if ($call == $hide) {
$call = '';
}
if (!in_array($call, $skip)) {
$message .= " $script $call\n";
}
}
} else {
$message = " Script : " . $_SERVER["SCRIPT_FILENAME"] . "\n";
}
if ($log) {
self::logInFile($log, $message, true);
}
return $message;
}
/**
* Send a deprecated message in log (with backtrace)
* @param string $message the message to send
* @return void
*/
public static function deprecated($message = "Called method is deprecated")
{
trigger_error($message, E_USER_DEPRECATED);
}
/**
* Log a message in log file
*
* @param string $name name of the log file
* @param string $text text to log
* @param boolean $force force log in file not seeing use_log_in_files config
*
* @return boolean
**/
public static function logInFile($name, $text, $force = false)
{
global $CFG_GLPI;
$user = '';
if (method_exists('Session', 'getLoginUserID')) {
$user = " [" . Session::getLoginUserID() . '@' . php_uname('n') . "]";
}
$ok = true;
if (
(isset($CFG_GLPI["use_log_in_files"]) && $CFG_GLPI["use_log_in_files"])
|| $force
) {
$ok = error_log(date("Y-m-d H:i:s") . "$user\n" . $text, 3, GLPI_LOG_DIR . "/" . $name . ".log");
}
global $application;
if ($application instanceof Application) {
$application->getOutput()->writeln('<comment>' . $text . '</comment>', OutputInterface::VERBOSITY_VERY_VERBOSE);
} else if (
isset($_SESSION['glpi_use_mode'])
&& ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE)
&& isCommandLine()
) {
$stderr = fopen('php://stderr', 'w');
fwrite($stderr, $text);
fclose($stderr);
}
return $ok;
}
/**
* Switch error mode for GLPI
*
* @param integer|null $mode From Session::*_MODE
* @param boolean|null $debug_sql
* @param boolean|null $debug_vars
* @param boolean|null $log_in_files
*
* @return void
*
* @since 0.84
**/
public static function setDebugMode($mode = null, $debug_sql = null, $debug_vars = null, $log_in_files = null)
{
global $CFG_GLPI;
if (isset($mode)) {
$_SESSION['glpi_use_mode'] = $mode;
}
if (isset($debug_sql)) {
$CFG_GLPI['debug_sql'] = $debug_sql;
}
if (isset($debug_vars)) {
$CFG_GLPI['debug_vars'] = $debug_vars;
}
if (isset($log_in_files)) {
$CFG_GLPI['use_log_in_files'] = $log_in_files;
}
// If debug mode activated : display some information
if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
// Force reporting of all errors
error_reporting(E_ALL);
// Disable native error displaying as it will be done by custom handler
ini_set('display_errors', 'Off');
}
}
/**
* Send a file (not a document) to the navigator
* See Document->send();
*
* @param string $file storage filename
* @param string $filename file title
* @param string|null $mime file mime type
* @param boolean $add_expires add expires headers maximize cacheability ?
*
* @return void
**/
public static function sendFile($file, $filename, $mime = null, $expires_headers = false)
{
// Test securite : document in DOC_DIR
$tmpfile = str_replace(GLPI_DOC_DIR, "", $file);
if (strstr($tmpfile, "../") || strstr($tmpfile, "..\\")) {
Event::log(
$file,
"sendFile",
1,
"security",
$_SESSION["glpiname"] . " try to get a non standard file."
);
echo "Security attack!!!";
die(1);
}
if (!file_exists($file)) {
echo "Error file $file does not exist";
die(1);
}
// if $mime is defined, ignore mime type by extension
if ($mime === null && preg_match('/\.(...)$/', $file)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
}
// don't download picture files, see them inline
$attachment = "";
// if not begin 'image/'
if (
strncmp($mime, 'image/', 6) !== 0
&& $mime != 'application/pdf'
// svg vector of attack, force attachment
// see https://github.com/glpi-project/glpi/issues/3873
|| $mime == 'image/svg+xml'
) {
$attachment = ' attachment;';
}
$etag = md5_file($file);
$lastModified = filemtime($file);
// Make sure there is nothing in the output buffer (In case stuff was added by core or misbehaving plugin).
// If there is any extra data, the sent file will be corrupted.
while (ob_get_level() > 0) {
ob_end_clean();
}
// Now send the file with header() magic
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModified) . " GMT");
header("Etag: $etag");
header_remove('Pragma');
header('Cache-Control: private');
if ($expires_headers) {
$max_age = WEEK_TIMESTAMP;
header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + $max_age));
}
header(
"Content-disposition:$attachment filename=\"" .
addslashes(iconv('UTF-8', 'ISO-8859-1', $filename)) .
"\"; filename*=utf-8''" .
rawurlencode($filename)
);
header("Content-type: " . $mime);
// HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
// http://tools.ietf.org/html/rfc7232#section-3.3
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) === $etag) {
http_response_code(304); //304 - Not Modified
exit;
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) {
http_response_code(304); //304 - Not Modified
exit;
}
readfile($file) or die("Error opening file $file");
}
/**
* Add slash for variable & array
*
* @param string|string[] $value value to add slashes
*
* @return string|string[]
**/
public static function addslashes_deep($value)
{
global $DB;
$value = ((array) $value === $value)
? array_map([__CLASS__, 'addslashes_deep'], $value)
: (is_null($value)
? null : (is_resource($value) || is_object($value)
? $value : $DB->escape(
str_replace(
[''', ''', ''', ''', '"'],
["'", "'", "'", "'", "\""],
$value
)
))
);
return $value;
}
/**
* Strip slash for variable & array
*
* @param array|string $value item to stripslashes
*
* @return array|string stripslashes item
**/
public static function stripslashes_deep($value)
{
$value = ((array) $value === $value)
? array_map([__CLASS__, 'stripslashes_deep'], $value)
: (is_null($value)
? null : (is_resource($value) || is_object($value)
? $value : stripslashes($value)));
return $value;
}
/** Converts an array of parameters into a query string to be appended to a URL.
*
* @param array $array parameters to append to the query string.
* @param string $separator separator may be defined as & to display purpose
* @param string $parent This should be left blank (it is used internally by the function).
*
* @return string Query string to append to a URL.
**/
public static function append_params($array, $separator = '&', $parent = '')
{
$params = [];
foreach ($array as $k => $v) {
if (is_array($v)) {
$params[] = self::append_params(
$v,
$separator,
(empty($parent) ? rawurlencode($k)
: $parent . '%5B' . rawurlencode($k) . '%5D')
);
} else {
$params[] = (!empty($parent) ? $parent . '%5B' . rawurlencode($k) . '%5D' : rawurlencode($k)) . '=' . rawurlencode($v);
}
}
//Remove empty values
$params = array_filter($params);
return implode($separator, $params);
}
/**
* Compute PHP memory_limit
*
* @param string $ininame name of the ini ooption to retrieve (since 9.1)
*
* @return integer memory limit
**/
public static function getMemoryLimit($ininame = 'memory_limit')
{
$mem = ini_get($ininame);
$matches = [];
preg_match("/([-0-9]+)([KMG]*)/", $mem, $matches);
$mem = "";
// no K M or G
if (isset($matches[1])) {
$mem = $matches[1];
if (isset($matches[2])) {
switch ($matches[2]) {
case "G":
$mem *= 1024;
// nobreak;
case "M":
$mem *= 1024;
// nobreak;
case "K":
$mem *= 1024;
// nobreak;
}
}
}
return $mem;
}
/**
* Check is current memory_limit is enough for GLPI
*
* @since 0.83
*
* @return integer
* 0 if PHP not compiled with memory_limit support,
* 1 no memory limit (memory_limit = -1),
* 2 insufficient memory for GLPI,
* 3 enough memory for GLPI
**/
public static function checkMemoryLimit()
{
$mem = self::getMemoryLimit();
if ($mem == "") {
return 0;
}
if ($mem == "-1") {
return 1;
}
if ($mem < (64 * 1024 * 1024)) {
return 2;
}
return 3;
}
/**
* Get the filesize of a complete directory (from php.net)
*
* @param string $path directory or file to get size
*
* @return null|integer
*
* @deprecated 10.0.0
**/
public static function filesizeDirectory($path)
{
Toolbox::deprecated();
if (!is_dir($path)) {
return filesize($path);
}
if ($handle = opendir($path)) {
$size = 0;
while (false !== ($file = readdir($handle))) {
if (($file != '.') && ($file != '..')) {
$size += filesize($path . '/' . $file);
$size += self::filesizeDirectory($path . '/' . $file);
}
}
closedir($handle);
return $size;
}
return null;
}
/** Format a size passing a size in octet
*
* @param integer $size Size in octet
*
* @return string formatted size
**/
public static function getSize($size)
{
//TRANS: list of unit (o for octet)
$bytes = [__('o'), __('Kio'), __('Mio'), __('Gio'), __('Tio')];
foreach ($bytes as $val) {
if ($size > 1024) {
$size = $size / 1024;
} else {
break;
}
}
//TRANS: %1$s is a number maybe float or string and %2$s the unit
return sprintf(__('%1$s %2$s'), round($size, 2), $val);
}
/**
* Delete a directory and file contains in it
*
* @param string $dir directory to delete
*
* @return void
**/
public static function deleteDir($dir)
{
if (file_exists($dir)) {
chmod($dir, 0777);
if (is_dir($dir)) {
$id_dir = opendir($dir);
while (($element = readdir($id_dir)) !== false) {
if (($element != ".") && ($element != "..")) {
if (is_dir($dir . "/" . $element)) {
self::deleteDir($dir . "/" . $element);
} else {
unlink($dir . "/" . $element);
}
}
}
closedir($id_dir);
rmdir($dir);
} else { // Delete file
unlink($dir);
}
}
}
/**
* Resize a picture to the new size
* Always produce a JPG file!
*
* @since 0.85
*
* @param string $source_path path of the picture to be resized
* @param string $dest_path path of the new resized picture
* @param integer $new_width new width after resized (default 71)
* @param integer $new_height new height after resized (default 71)
* @param integer $img_y y axis of picture (default 0)
* @param integer $img_x x axis of picture (default 0)
* @param integer $img_width width of picture (default 0)
* @param integer $img_height height of picture (default 0)
* @param integer $max_size max size of the picture (default 500, is set to 0 no resize)
*
* @return boolean
**/
public static function resizePicture(
$source_path,
$dest_path,
$new_width = 71,
$new_height = 71,
$img_y = 0,
$img_x = 0,
$img_width = 0,
$img_height = 0,
$max_size = 500
) {
//get img information (dimensions and extension)
$img_infos = getimagesize($source_path);
if (empty($img_width)) {
$img_width = $img_infos[0];
}
if (empty($img_height)) {
$img_height = $img_infos[1];
}
if (empty($new_width)) {
$new_width = $img_infos[0];