-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
toolbox.class.php
3001 lines (2584 loc) · 90.7 KB
/
toolbox.class.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
* Copyright (C) 2015-2018 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI 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 2 of the License, or
* (at your option) any later version.
*
* GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
use Glpi\Event;
use Monolog\Logger;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Toolbox Class
**/
class Toolbox {
/**
* Wrapper for max_input_vars
*
* @since 0.84
*
* @return integer
**/
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 $str string to change
*
* @return string changed
**/
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 $str string from dico
* @param $shortcut letter of shortcut
*
* @return string
**/
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 $str string string
* @param $tofound string string to found
* @param $offset integer The search offset. If it is not specified, 0 is used.
* (default 0)
*
* @return substring
**/
static function strpos($str, $tofound, $offset = 0) {
return mb_strpos($str, $tofound, $offset, "UTF-8");
}
/**
* Replace str_pad()
* who bug with utf8
*
* @param $input string input string
* @param $pad_length integer padding length
* @param $pad_string string padding string (default '')
* @param $pad_type integer padding type (default STR_PAD_RIGHT)
*
* @return string
**/
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 $str string
*
* @return length of the string
**/
static function strlen($str) {
return mb_strlen($str, "UTF-8");
}
/**
* substr function for utf8 string
*
* @param $str string
* @param $start integer start of the result substring
* @param $length integer The maximum length of the returned string if > 0 (default -1)
*
* @return substring
**/
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 $str string
*
* @return lower case string
**/
static function strtolower($str) {
return mb_strtolower($str, "UTF-8");
}
/**
* strtoupper function for utf8 string
*
* @param $str string
*
* @return upper case string
**/
static function strtoupper($str) {
return mb_strtoupper($str, "UTF-8");
}
/**
* Is a string seems to be UTF-8 one ?
*
* @param $str string string to analyze
*
* @return boolean
**/
static function seems_utf8($str) {
return mb_check_encoding($str, "UTF-8");
}
/**
* Encode string to UTF-8
*
* @param $string string string to convert
* @param $from_charset string original charset (if 'auto' try to autodetect)
* (default "ISO-8859-1")
*
* @return utf8 string
**/
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 $to_charset string destination charset (default "ISO-8859-1")
*
* @return converted string
**/
static function decodeFromUtf8($string, $to_charset = "ISO-8859-1") {
return mb_convert_encoding($string, $to_charset, "UTF-8");
}
/**
* Encrypt a string
*
* @param $string string to encrypt
* @param $key string key used to encrypt
*
* @return encrypted string
**/
static function encrypt($string, $key = null) {
if ($key === null) {
$key = self::getGlpiSecKey();
}
if ($key === GLPIKEY && !defined('TU_USER')) {
self::deprecated('Using GLPIKEY is not secure!');
}
$result = '';
for ($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result .= $char;
}
return base64_encode($result);
}
/**
* Decrypt a string
*
* @param $string string to decrypt
* @param $key string key used to decrypt
*
* @return decrypted string
**/
static function decrypt($string, $key = null) {
if ($key === null) {
$key = self::getGlpiSecKey();
}
$result = '';
$string = base64_decode($string);
for ($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result .= $char;
}
return Toolbox::unclean_cross_side_scripting_deep($result);
}
/**
* Get GLPI security key used for decryptable passwords
*
* Will read key from config/glpi.key if present.
* For 9.4 branch, this will defaults to GLPIKEY.
*
* @return string
*/
public static function getGlpiSecKey() {
$glpikey = new GLPIKey();
return $glpikey->get();
}
/**
* Prevent from XSS
* Clean code
*
* @param $value array or string: item to prevent (array or string)
*
* @return clean item
*
* @see unclean_cross_side_scripting_deep*
**/
static function clean_cross_side_scripting_deep($value) {
if ((array) $value === $value) {
return array_map([__CLASS__, 'clean_cross_side_scripting_deep'], $value);
}
if (!is_string($value)) {
return $value;
}
$in = ['<', '>'];
$out = ['<', '>'];
return str_replace($in, $out, $value);
}
/**
* Invert fonction from clean_cross_side_scripting_deep
*
* @param $value array or string item to unclean from clean_cross_side_scripting_deep
*
* @return unclean item
*
* @see clean_cross_side_scripting_deep
**/
static function unclean_cross_side_scripting_deep($value) {
if ((array) $value === $value) {
return array_map([__CLASS__, 'unclean_cross_side_scripting_deep'], $value);
}
if (!is_string($value)) {
return $value;
}
$in = ['<', '>'];
$out = ['<', '>'];
return str_replace($out, $in, $value);
}
/**
* Invert fonction from clean_cross_side_scripting_deep to display HTML striping XSS code
*
* @since 0.83.3
*
* @param $value array or string: item to unclean from clean_cross_side_scripting_deep
*
* @return unclean item
*
* @see clean_cross_side_scripting_deep
**/
static function unclean_html_cross_side_scripting_deep($value) {
include_once(GLPI_HTMLAWED);
if ((array) $value === $value) {
$value = array_map([__CLASS__, 'unclean_html_cross_side_scripting_deep'], $value);
} else {
$value = self::unclean_cross_side_scripting_deep($value);
}
// revert unclean inside <pre>
if (is_string($value)) {
$count = preg_match_all('/(<pre[^>]*>)(.*?)(<\/pre>)/is', $value, $matches);
for ($i = 0; $i < $count; ++$i) {
$complete = $matches[0][$i];
$cleaned = self::clean_cross_side_scripting_deep($matches[2][$i]);
$cleancomplete = $matches[1][$i].$cleaned.$matches[3][$i];
$value = str_replace($complete, $cleancomplete, $value);
}
$config = ['safe'=>1];
$config["elements"] = "*+iframe+audio+video";
$config["direct_list_nest"] = 1;
$value = htmLawed($value, $config);
// Special case : remove the 'denied:' for base64 img in case the base64 have characters
// combinaison introduce false positive
foreach (['png', 'gif', 'jpg', 'jpeg'] as $imgtype) {
$value = str_replace('src="denied:data:image/'.$imgtype.';base64,',
'src="data:image/'.$imgtype.';base64,', $value);
}
}
return $value;
}
/**
* 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;
}
$logger->addRecord($level, $msg, $extra);
if (defined('TU_USER') && $level >= Logger::NOTICE) {
throw new \RuntimeException($msg);
} else if (isCommandLine() && $level >= Logger::WARNING) {
echo $msg;
}
}
/**
* PHP debug log
*/
static function logDebug() {
self::log(null, Logger::DEBUG, func_get_args());
}
/**
* PHP info log
*/
static function loginfo() {
self::log(null, Logger::INFO, func_get_args());
}
/**
* PHP warning log
*/
static function logWarning() {
self::log(null, Logger::WARNING, func_get_args());
}
/**
* PHP error log
*/
static function logError() {
self::log(null, Logger::ERROR, func_get_args());
}
/**
* SQL error log
*/
static function logSqlDebug() {
global $SQLLOGGER;
$args = func_get_args();
self::log($SQLLOGGER, Logger::DEBUG, $args);
}
/**
* SQL error log
*/
static function logSqlError() {
global $SQLLOGGER;
$args = func_get_args();
$msg = $args[0];
try {
self::log($SQLLOGGER, Logger::ERROR, $args);
} catch (\RuntimeException $e) {
$msg = $e->getMessage();
} finally {
if (class_exists('GlpitestSQLError')) { // For unit test
throw new \GlpitestSQLError($msg);
}
}
}
/**
* Generate a Backtrace
*
* @param $log String log file name (default php-errors)
* if false, return the strung
* @param $hide String call to hide (but display script/line) (default '')
* @param $skip Array of call to not display at all
*
* @since 0.85
*
* @return string if $log is false
**/
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);
} else {
return $message;
}
}
/**
* Send a deprecated message in log (with backtrace)
* @param string $message the message to send
* @return void
*/
static function deprecated($message = "Called method is deprecated") {
try {
self::log(null, Logger::NOTICE, [$message]);
} finally {
if (defined('TU_USER')) {
if (isCommandLine()) {
echo self::backtrace(null);
} else {
self::backtrace();
}
}
}
}
/**
* Log a message in log file
*
* @param $name string name of the log file
* @param $text string text to log
* @param $force boolean force log in file not seeing use_log_in_files config (false by default)
**/
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");
}
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;
}
/**
* Specific error handler in Normal mode
*
* @param $errno integer level of the error raised.
* @param $errmsg string error message.
* @param $filename string filename that the error was raised in.
* @param $linenum integer line number the error was raised at.
**/
static function userErrorHandlerNormal($errno, $errmsg, $filename, $linenum) {
// Date et heure de l'erreur
$errortype = [E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
E_DEPRECATED => 'Deprecated function',
E_USER_DEPRECATED => 'User deprecated function'];
// Les niveaux qui seront enregistr??s
$user_errors = [E_USER_ERROR, E_USER_NOTICE, E_USER_WARNING];
$err = ' *** PHP '.$errortype[$errno] . "($errno): $errmsg\n";
$skip = ['Toolbox::backtrace()'];
if (isset($_SESSION['glpi_use_mode']) && $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
$hide = "Toolbox::userErrorHandlerDebug()";
$skip[] = "Toolbox::userErrorHandlerNormal()";
} else {
$hide = "Toolbox::userErrorHandlerNormal()";
}
$err .= self::backtrace(false, $hide, $skip);
// For unit test
if (class_exists('GlpitestPHPerror')) {
if (in_array($errno, [E_ERROR, E_USER_ERROR])) {
throw new GlpitestPHPerror($err);
}
/* for tuture usage
if (in_array($errno, [E_STRICT, E_WARNING, E_CORE_WARNING, E_USER_WARNING, E_DEPRECATED, E_USER_DEPRECATED])) {
throw new GlpitestPHPwarning($err);
}
if (in_array($errno, [E_NOTICE, E_USER_NOTICE])) {
throw new GlpitestPHPnotice($err);
}
*/
}
// Save error
static::logError($err);
return $errortype[$errno];
}
/**
* Specific error handler in Debug mode
*
* @param $errno integer level of the error raised.
* @param $errmsg string error message.
* @param $filename string filename that the error was raised in.
* @param $linenum integer line number the error was raised at.
**/
static function userErrorHandlerDebug($errno, $errmsg, $filename, $linenum) {
// For file record
$type = self::userErrorHandlerNormal($errno, $errmsg, $filename, $linenum);
// Display
if (!isCommandLine()) {
echo '<div style="position:float-left; background-color:red; z-index:10000">'.
'<span class="b">PHP '.$type.': </span>';
echo $errmsg.' in '.$filename.' at line '.$linenum.'</div>';
} else {
echo 'PHP '.$type.': '.$errmsg.' in '.$filename.' at line '.$linenum."\n";
}
}
/**
* Switch error mode for GLPI
*
* @param $mode Integer from Session::*_MODE (default NULL)
* @param $debug_sql Boolean (default NULL)
* @param $debug_vars Boolean (default NULL)
* @param $log_in_files Boolean (default NULL)
*
* @since 0.84
**/
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) {
// Recommended development settings
ini_set('display_errors', 'On');
error_reporting(E_ALL);
set_error_handler(['Toolbox','userErrorHandlerDebug']);
} else if (!defined('TU_USER')) {
// Recommended production settings
ini_set('display_errors', 'Off');
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
set_error_handler(['Toolbox', 'userErrorHandlerNormal']);
}
}
/**
* Send a file (not a document) to the navigator
* See Document->send();
*
* @param $file string: storage filename
* @param $filename string: file title
* @param $mime string: file mime type
*
* @return nothing
**/
static function sendFile($file, $filename, $mime = null) {
// 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, $regs)) {
$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);
// Now send the file with header() magic
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
header("Etag: $etag");
header('Pragma: private'); /// IE BUG + SSL
header('Cache-control: private, must-revalidate'); /// IE BUG + SSL
header(
"Content-disposition:$attachment filename=\"" .
addslashes(utf8_decode($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 $value array or string: value to add slashes (array or string)
*
* @return addslashes value
**/
static function addslashes_deep($value) {
global $DB;
$value = ((array) $value === $value)
? array_map([__CLASS__, 'addslashes_deep'], $value)
: (is_null($value)
? null : (is_resource($value)
? $value : $DB->escape(
str_replace(
[''', ''', ''', ''', '"'],
["'", "'", "'", "'", "\""],
$value
)
))
);
return $value;
}
/**
* Strip slash for variable & array
*
* @param $value array or string: item to stripslashes (array or string)
*
* @return stripslashes item
**/
static function stripslashes_deep($value) {
$value = ((array) $value === $value)
? array_map([__CLASS__, 'stripslashes_deep'], $value)
: (is_null($value)
? null : (is_resource($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 $separator separator may be defined as & to display purpose
* (default '&')
* @param $parent This should be left blank (it is used internally by the function).
* (default '')
*
* @return string : Query string to append to a URL.
**/
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);
}
}
return implode($separator, $params);
}
/**
* Compute PHP memory_limit
*
* @param $ininame String name of the ini ooption to retrieve (since 9.1)
*
* @return memory limit
**/
static function getMemoryLimit($ininame = 'memory_limit') {
$mem = ini_get($ininame);
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 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
**/
static function checkMemoryLimit() {
$mem = self::getMemoryLimit();
if ($mem == "") {
return 0;
}
if ($mem == "-1") {
return 1;
}
if ($mem < (64*1024*1024)) {
return 2;
}
return 3;
}
/**
* Common Checks needed to use GLPI
* @param boolean $isInstall Is the check run on a install process (don't check DB as not configured yet)
*
* @return integer 2 = creation error / 1 = delete error / 0 = OK
*/
static function commonCheckForUseGLPI($isInstall = false) {
global $CFG_GLPI;
$error = 0;
// Title
echo "<tr><th>".__('Test done')."</th><th >".__('Results')."</th></tr>";
// Parser test
echo "<tr class='tab_bg_1'><td class='b left'>".__('Testing PHP Parser')."</td>";
// PHP Version - exclude PHP3, PHP 4 and zend.ze1 compatibility
if (version_compare(PHP_VERSION, GLPI_MIN_PHP) >= 0) {
// PHP version ok, now check PHP zend.ze1_compatibility_mode
if (ini_get("zend.ze1_compatibility_mode") == 1) {
$error = 2;
echo "<td class='red'>
<img src='".$CFG_GLPI['root_doc']."/pics/ko_min.png'>".
__('GLPI is not compatible with the option zend.ze1_compatibility_mode = On.').
"</td>";
} else {
echo "<td><img src='".$CFG_GLPI['root_doc']."/pics/ok_min.png' alt=\"".
sprintf(__s('PHP version is at least %s - Perfect!'), GLPI_MIN_PHP)."\"
title=\"".sprintf(__s('PHP version is at least %s - Perfect!'), GLPI_MIN_PHP)."\"></td>";
}
} else { // PHP <5
$error = 2;
echo "<td class='red'>