/
session.class.php
1661 lines (1414 loc) · 47.9 KB
/
session.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-2021 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;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Session Class
**/
class Session {
// GLPI MODE
const NORMAL_MODE = 0;
const TRANSLATION_MODE = 1; // no more used
const DEBUG_MODE = 2;
/**
* Destroy the current session
*
* @return void
**/
static function destroy() {
self::start();
// Unset all of the session variables.
session_unset();
// destroy may cause problems (no login / back to login page)
$_SESSION = [];
// write_close may cause troubles (no login / back to login page)
}
/**
* Init session for the user is defined
*
* @param Auth $auth Auth object to init session
*
* @return void
**/
static function init(Auth $auth) {
global $CFG_GLPI;
if ($auth->auth_succeded) {
// Restart GLPI session : complete destroy to prevent lost datas
$tosave = ['glpi_plugins', 'glpicookietest', 'phpCAS', 'glpicsrftokens',
'glpiskipMaintenance'];
$save = [];
foreach ($tosave as $t) {
if (isset($_SESSION[$t])) {
$save[$t] = $_SESSION[$t];
}
}
self::destroy();
session_regenerate_id();
self::start();
$_SESSION = $save;
$_SESSION['valid_id'] = session_id();
// Define default time :
$_SESSION["glpi_currenttime"] = date("Y-m-d H:i:s");
// Normal mode for this request
$_SESSION["glpi_use_mode"] = self::NORMAL_MODE;
// Check ID exists and load complete user from DB (plugins...)
if (isset($auth->user->fields['id'])
&& $auth->user->getFromDB($auth->user->fields['id'])) {
if (!$auth->user->fields['is_deleted']
&& ($auth->user->fields['is_active']
&& (($auth->user->fields['begin_date'] < $_SESSION["glpi_currenttime"])
|| is_null($auth->user->fields['begin_date']))
&& (($auth->user->fields['end_date'] > $_SESSION["glpi_currenttime"])
|| is_null($auth->user->fields['end_date'])))) {
$_SESSION["glpiID"] = $auth->user->fields['id'];
$_SESSION["glpifriendlyname"] = $auth->user->getFriendlyName();
$_SESSION["glpiname"] = $auth->user->fields['name'];
$_SESSION["glpirealname"] = $auth->user->fields['realname'];
$_SESSION["glpifirstname"] = $auth->user->fields['firstname'];
$_SESSION["glpidefault_entity"] = $auth->user->fields['entities_id'];
$_SESSION["glpiextauth"] = $auth->extauth;
if (isset($_SESSION['phpCAS']['user'])) {
$_SESSION["glpiauthtype"] = Auth::CAS;
$_SESSION["glpiextauth"] = 0;
} else {
$_SESSION["glpiauthtype"] = $auth->user->fields['authtype'];
}
$_SESSION["glpiroot"] = $CFG_GLPI["root_doc"];
$_SESSION["glpi_use_mode"] = $auth->user->fields['use_mode'];
$_SESSION["glpi_plannings"] = importArrayFromDB($auth->user->fields['plannings']);
$_SESSION["glpicrontimer"] = time();
// Default tab
// $_SESSION['glpi_tab']=1;
$_SESSION['glpi_tabs'] = [];
$auth->user->computePreferences();
foreach ($CFG_GLPI['user_pref_field'] as $field) {
if ($field == 'language' && isset($_POST['language']) && $_POST['language'] != '') {
$_SESSION["glpi$field"] = $_POST[$field];
} else if (isset($auth->user->fields[$field])) {
$_SESSION["glpi$field"] = $auth->user->fields[$field];
}
}
// Do it here : do not reset on each page, cause export issue
if ($_SESSION["glpilist_limit"] > $CFG_GLPI['list_limit_max']) {
$_SESSION["glpilist_limit"] = $CFG_GLPI['list_limit_max'];
}
// Init not set value for language
if (empty($_SESSION["glpilanguage"])) {
$_SESSION["glpilanguage"] = self::getPreferredLanguage();
}
$_SESSION['glpi_dropdowntranslations'] = DropdownTranslation::getAvailableTranslations($_SESSION["glpilanguage"]);
self::loadLanguage();
if ($auth->password_expired) {
$_SESSION['glpi_password_expired'] = 1;
// Do not init profiles, as user has to update its password to be able to use GLPI
return;
}
// glpiprofiles -> other available profile with link to the associated entities
Plugin::doHook("init_session");
self::initEntityProfiles(self::getLoginUserID());
// Use default profile if exist
if (isset($_SESSION['glpiprofiles'][$auth->user->fields['profiles_id']])) {
self::changeProfile($auth->user->fields['profiles_id']);
} else { // Else use first
self::changeProfile(key($_SESSION['glpiprofiles']));
}
if (!Session::getCurrentInterface()) {
$auth->auth_succeded = false;
$auth->addToError(__("You don't have right to connect"));
}
} else {
$auth->auth_succeded = false;
$auth->addToError(__("You don't have access to this application because your account was deactivated or removed"));
}
} else {
$auth->auth_succeded = false;
$auth->addToError(__("You don't have right to connect"));
}
}
}
/**
* Set the directory where are store the session file
*
* @return void
**/
static function setPath() {
if (ini_get("session.save_handler") == "files"
&& session_status() !== PHP_SESSION_ACTIVE) {
session_save_path(GLPI_SESSION_DIR);
}
}
/**
* Start the GLPI php session
*
* @return void
**/
static function start() {
if (session_status() === PHP_SESSION_NONE) {
// Force session to use cookies and prevent JS scripts to access to them
ini_set('session.cookie_httponly', '1');
ini_set('session.use_only_cookies', '1');
session_name("glpi_".md5(realpath(GLPI_ROOT)));
@session_start();
}
// Define current time for sync of action timing
$_SESSION["glpi_currenttime"] = date("Y-m-d H:i:s");
}
/**
* Get root entity name
*
* @since 0.84
*
* @return string
**/
function getRootEntityName() {
if (isset($_SESSION['glpirootentityname'])) {
return $_SESSION['glpirootentityname'];
}
$entity = new Entity();
if ($entity->getFromDB(0)) {
$_SESSION['glpirootentityname'] = $entity->fields['name'];
} else {
$_SESSION['glpirootentityname'] = 'No root entity / DB troubles';
}
return $_SESSION['glpirootentityname'];
}
/**
* Is GLPI used in multi-entities mode?
*
* @return boolean
**/
static function isMultiEntitiesMode() {
if (!isset($_SESSION['glpi_multientitiesmode'])) {
if (countElementsInTable("glpi_entities") > 1) {
$_SESSION['glpi_multientitiesmode'] = 1;
} else {
$_SESSION['glpi_multientitiesmode'] = 0;
}
}
return $_SESSION['glpi_multientitiesmode'];
}
/**
* Does user have right to see all entities?
*
* @since 9.3.2
*
* @return boolean
**/
static function canViewAllEntities() {
// Command line can see all entities
return (isCommandLine()
|| ((countElementsInTable("glpi_entities")) == count($_SESSION["glpiactiveentities"])));
}
/** Add an item to the navigate through search results list
*
* @param string $itemtype Device type
* @param integer $ID ID of the item
**/
static function addToNavigateListItems($itemtype, $ID) {
$_SESSION['glpilistitems'][$itemtype][] = $ID;
}
/** Initialise a list of items to use navigate through search results
*
* @param string $itemtype Device type
* @param string $title List title (default '')
**/
static function initNavigateListItems($itemtype, $title = "") {
if (empty($title)) {
$title = __('List');
}
$url = '';
if (!isset($_SERVER['REQUEST_URI']) || (strpos($_SERVER['REQUEST_URI'], "tabs") > 0)) {
if (isset($_SERVER['HTTP_REFERER'])) {
$url = $_SERVER['HTTP_REFERER'];
}
} else {
$url = $_SERVER['REQUEST_URI'];
}
$_SESSION['glpilisttitle'][$itemtype] = $title;
$_SESSION['glpilistitems'][$itemtype] = [];
$_SESSION['glpilisturl'][$itemtype] = $url;
}
/**
* Change active entity to the $ID one. Update glpiactiveentities session variable.
* Reload groups related to this entity.
*
* @param integer|'All' $ID ID of the new active entity ("all"=>load all possible entities)
* (default 'all')
* @param boolean $is_recursive Also display sub entities of the active entity? (false by default)
*
* @return boolean true on success, false on failure
**/
static function changeActiveEntities($ID = "all", $is_recursive = false) {
$newentities = [];
if (isset($_SESSION['glpiactiveprofile'])) {
if ($ID === "all") {
$ancestors = [];
foreach ($_SESSION['glpiactiveprofile']['entities'] as $val) {
$ancestors = array_unique(array_merge(getAncestorsOf("glpi_entities",
$val['id']),
$ancestors));
$newentities[$val['id']] = $val['id'];
if ($val['is_recursive']) {
$entities = getSonsOf("glpi_entities", $val['id']);
if (count($entities)) {
foreach ($entities as $key2 => $val2) {
$newentities[$key2] = $key2;
}
}
}
}
} else {
/// Check entity validity
$ancestors = getAncestorsOf("glpi_entities", $ID);
$ok = false;
foreach ($_SESSION['glpiactiveprofile']['entities'] as $val) {
if (($val['id'] == $ID) || in_array($val['id'], $ancestors)) {
// Not recursive or recursive and root entity is recursive
if (!$is_recursive || $val['is_recursive']) {
$ok = true;
}
}
}
if (!$ok) {
return false;
}
$newentities[$ID] = $ID;
if ($is_recursive) {
$entities = getSonsOf("glpi_entities", $ID);
if (count($entities)) {
foreach ($entities as $key2 => $val2) {
$newentities[$key2] = $key2;
}
}
}
}
}
if (count($newentities) > 0) {
$_SESSION['glpiactiveentities'] = $newentities;
$_SESSION['glpiactiveentities_string'] = "'".implode("', '", $newentities)."'";
$active = reset($newentities);
$_SESSION['glpiparententities'] = $ancestors;
$_SESSION['glpiparententities_string'] = implode("', '", $ancestors);
if (!empty($_SESSION['glpiparententities_string'])) {
$_SESSION['glpiparententities_string'] = "'".$_SESSION['glpiparententities_string']."'";
}
// Active entity loading
$_SESSION["glpiactive_entity"] = $active;
$_SESSION["glpiactive_entity_recursive"] = $is_recursive;
$_SESSION["glpiactive_entity_name"] = Dropdown::getDropdownName("glpi_entities",
$active);
$_SESSION["glpiactive_entity_shortname"] = getTreeLeafValueName("glpi_entities", $active);
if ($is_recursive || $ID=="all") {
//TRANS: %s is the entity name
$_SESSION["glpiactive_entity_name"] = sprintf(__('%1$s (%2$s)'),
$_SESSION["glpiactive_entity_name"],
__('tree structure'));
$_SESSION["glpiactive_entity_shortname"] = sprintf(__('%1$s (%2$s)'),
$_SESSION["glpiactive_entity_shortname"],
__('tree structure'));
}
if (countElementsInTable('glpi_entities') <= count($_SESSION['glpiactiveentities'])) {
$_SESSION['glpishowallentities'] = 1;
} else {
$_SESSION['glpishowallentities'] = 0;
}
// Clean session variable to search system
if (isset($_SESSION['glpisearch']) && count($_SESSION['glpisearch'])) {
foreach ($_SESSION['glpisearch'] as $itemtype => $tab) {
if (isset($tab['start']) && ($tab['start'] > 0)) {
$_SESSION['glpisearch'][$itemtype]['start'] = 0;
}
}
}
self::loadGroups();
Plugin::doHook("change_entity");
return true;
}
return false;
}
/**
* Change active profile to the $ID one. Update glpiactiveprofile session variable.
*
* @param integer $ID ID of the new profile
*
* @return void
**/
static function changeProfile($ID) {
if (isset($_SESSION['glpiprofiles'][$ID])
&& count($_SESSION['glpiprofiles'][$ID]['entities'])) {
$profile = new Profile();
if ($profile->getFromDB($ID)) {
$profile->cleanProfile();
$data = $profile->fields;
$data['entities'] = $_SESSION['glpiprofiles'][$ID]['entities'];
$_SESSION['glpiactiveprofile'] = $data;
$_SESSION['glpiactiveentities'] = [];
Search::resetSaveSearch();
$active_entity_done = false;
// Try to load default entity if it is a root entity
foreach ($data['entities'] as $val) {
if ($val['id'] == $_SESSION["glpidefault_entity"]) {
if (self::changeActiveEntities($val['id'], $val['is_recursive'])) {
$active_entity_done = true;
}
}
}
if (!$active_entity_done) {
// Try to load default entity
if (!self::changeActiveEntities($_SESSION["glpidefault_entity"], true)) {
// Load all entities
self::changeActiveEntities("all");
}
}
Plugin::doHook("change_profile");
}
}
// Clean specific datas
if (isset($_SESSION['glpimenu'])) {
unset($_SESSION['glpimenu']);
}
}
/**
* Set the entities session variable. Load all entities from DB
*
* @param integer $userID ID of the user
*
* @return void
**/
static function initEntityProfiles($userID) {
global $DB;
$_SESSION['glpiprofiles'] = [];
if (!$DB->tableExists('glpi_profiles_users')) {
//table does not exists in old GLPI versions
return;
}
$iterator = $DB->request([
'SELECT' => [
'glpi_profiles.id',
'glpi_profiles.name'
],
'DISTINCT' => true,
'FROM' => 'glpi_profiles_users',
'INNER JOIN' => [
'glpi_profiles' => [
'ON' => [
'glpi_profiles_users' => 'profiles_id',
'glpi_profiles' => 'id'
]
]
],
'WHERE' => [
'glpi_profiles_users.users_id' => $userID
],
'ORDERBY' => 'glpi_profiles.name'
]);
if (count($iterator)) {
while ($data = $iterator->next()) {
$key = $data['id'];
$_SESSION['glpiprofiles'][$key]['name'] = $data['name'];
$entities_iterator = $DB->request([
'SELECT' => [
'glpi_profiles_users.entities_id AS eID',
'glpi_profiles_users.id AS kID',
'glpi_profiles_users.is_recursive',
'glpi_entities.*'
],
'FROM' => 'glpi_profiles_users',
'LEFT JOIN' => [
'glpi_entities' => [
'ON' => [
'glpi_profiles_users' => 'entities_id',
'glpi_entities' => 'id'
]
]
],
'WHERE' => [
'glpi_profiles_users.profiles_id' => $key,
'glpi_profiles_users.users_id' => $userID
],
'ORDERBY' => 'glpi_entities.completename'
]);
while ($data = $entities_iterator->next()) {
// Do not override existing entity if define as recursive
if (!isset($_SESSION['glpiprofiles'][$key]['entities'][$data['eID']])
|| $data['is_recursive']
) {
$_SESSION['glpiprofiles'][$key]['entities'][$data['eID']] = [
'id' => $data['eID'],
'name' => $data['name'],
'is_recursive' => $data['is_recursive']
];
}
}
}
}
}
/**
* Load current user's group on active entity
*
* @return void
**/
static function loadGroups() {
global $DB;
$_SESSION["glpigroups"] = [];
$iterator = $DB->request([
'SELECT' => Group_User::getTable() . '.groups_id',
'FROM' => Group_User::getTable(),
'LEFT JOIN' => [
Group::getTable() => [
'ON' => [
Group::getTable() => 'id',
Group_User::getTable() => 'groups_id'
]
]
],
'WHERE' => [
Group_User::getTable(). '.users_id' => self::getLoginUserID()
] + getEntitiesRestrictCriteria(
Group::getTable(),
'entities_id',
$_SESSION['glpiactiveentities'],
true
)
]);
while ($data = $iterator->next()) {
$_SESSION["glpigroups"][] = $data["groups_id"];
}
}
/**
* Include the good language dict.
*
* Get the default language from current user in $_SESSION["glpilanguage"].
* And load the dict that correspond.
*
* @param string $forcelang Force to load a specific lang
* @param boolean $with_plugins Whether to load plugin languages or not
*
* @return void
**/
static function loadLanguage($forcelang = '', $with_plugins = true) {
global $CFG_GLPI, $TRANSLATE;
if (!isset($_SESSION["glpilanguage"])) {
$_SESSION["glpilanguage"] = self::getPreferredLanguage();
}
$trytoload = $_SESSION["glpilanguage"];
// Force to load a specific lang
if (!empty($forcelang)) {
$trytoload = $forcelang;
}
// If not set try default lang file
if (empty($trytoload)) {
$trytoload = $CFG_GLPI["language"];
}
if (isset($CFG_GLPI["languages"][$trytoload])) {
$newfile = "/" . $CFG_GLPI["languages"][$trytoload][1];
}
if (empty($newfile) || !is_file(GLPI_I18N_DIR . $newfile)) {
$newfile = "/en_GB.mo";
}
if (isset($CFG_GLPI["languages"][$trytoload][5])) {
$_SESSION['glpipluralnumber'] = $CFG_GLPI["languages"][$trytoload][5];
}
$TRANSLATE = new Laminas\I18n\Translator\Translator;
$TRANSLATE->setLocale($trytoload);
if (class_exists('Locale')) {
// Locale class may be missing if intl extension is not installed.
// In this case, we may still want to be able to load translations (for instance for requirements checks).
\Locale::setDefault($trytoload);
} else {
Toolbox::logWarning('Missing required intl PHP extension');
}
$cache = Config::getCache('cache_trans', 'core', false);
if ($cache !== false && !defined('TU_USER')) {
$TRANSLATE->setCache($cache);
}
$TRANSLATE->addTranslationFile('gettext', GLPI_I18N_DIR.$newfile, 'glpi', $trytoload);
$core_folders = scandir(GLPI_LOCAL_I18N_DIR);
$core_folders = array_filter($core_folders, function($dir) {
if (!is_dir(GLPI_LOCAL_I18N_DIR . "/$dir")) {
return false;
}
if ($dir == 'core') {
return true;
}
return Toolbox::startsWith($dir, 'core_');
});
foreach ($core_folders as $core_folder) {
$mofile = GLPI_LOCAL_I18N_DIR . "/$core_folder/" . $newfile;
$phpfile = str_replace('.mo', '.php', $mofile);
// Load local PHP file if it exists
if (file_exists($phpfile)) {
$TRANSLATE->addTranslationFile('phparray', $phpfile, 'glpi', $trytoload);
}
// Load local MO file if it exists -- keep last so it gets precedence
if (file_exists($mofile)) {
$TRANSLATE->addTranslationFile('gettext', $mofile, 'glpi', $trytoload);
}
}
// Load plugin dicts
if ($with_plugins) {
foreach (Plugin::getPlugins() as $plug) {
Plugin::loadLang($plug, $forcelang, $trytoload);
}
}
return $trytoload;
}
/**
* Return preffered language (from HTTP headers, fallback to default GLPI lang).
*
* @return string
*/
public static function getPreferredLanguage(): string {
global $CFG_GLPI;
// Extract accepted languages from headers
// Accept-Language: fr-FR, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5
$accepted_languages = [];
$values = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '');
foreach ($values as $value) {
$parts = explode(';q=', trim($value));
$language = str_replace('-', '_', $parts[0]);
$qfactor = $parts[1] ?? 1; //q-factor defaults to 1
$accepted_languages[$language] = $qfactor;
}
arsort($accepted_languages); // sort by qfactor
foreach (array_keys($accepted_languages) as $language) {
if (array_key_exists($language, $CFG_GLPI['languages'])) {
return $language;
}
}
if (isset($CFG_GLPI['language'])) {
// Default config in GLPI >= 0.72
return $CFG_GLPI['language'];
} else if (isset($CFG_GLPI['default_language'])) {
// Default config in GLPI < 0.72 : keep it for upgrade process
return $CFG_GLPI['default_language'];
}
return 'en_GB';
}
/**
* Get plural form number
*
* @return integer
*/
static function getPluralNumber() {
global $DEFAULT_PLURAL_NUMBER;
if (isset($_SESSION['glpipluralnumber'])) {
return $_SESSION['glpipluralnumber'];
} else {
return $DEFAULT_PLURAL_NUMBER;
}
}
/**
* Detect cron mode or interactive
*
* @since 0.84
*
* @return boolean
**/
static function isCron() {
return (isset($_SESSION["glpicronuserrunning"])
&& (isCommandLine()
|| strpos($_SERVER['PHP_SELF'], '/cron.php')));
}
/**
* Get the Login User ID or return cron user ID for cron jobs
*
* @param boolean $force_human Force human / do not return cron user (true by default)
*
* @return false|int|string false if user is not logged in
* int for user id, string for cron jobs
**/
static function getLoginUserID($force_human = true) {
if (!$force_human
&& self::isCron()) { // Check cron jobs
return $_SESSION["glpicronuserrunning"];
}
if (isset($_SESSION["glpiID"])) {
return $_SESSION["glpiID"];
}
return false;
}
/**
* Redirect User to login if not logged in
*
* @since 0.85
*
* @return void
**/
static function redirectIfNotLoggedIn() {
if (!self::getLoginUserID()) {
Html::redirectToLogin();
}
}
/**
* Global check of session to prevent PHP vulnerability
*
* @since 0.85
*
* @see https://wiki.php.net/rfc/strict_sessions
*
* @return void|true
**/
static function checkValidSessionId() {
if (!isset($_SESSION['valid_id'])
|| ($_SESSION['valid_id'] !== session_id())) {
Html::redirectToLogin('error=3');
}
return true;
}
/**
* Check if I have access to the central interface
*
* @return void
**/
static function checkCentralAccess() {
self::checkValidSessionId();
if (Session::getCurrentInterface() != "central") {
// Gestion timeout session
self::redirectIfNotLoggedIn();
Html::displayRightError();
}
}
/**
* Check if I have the right to access to the FAQ (profile or anonymous FAQ)
*
* @return void
**/
static function checkFaqAccess() {
global $CFG_GLPI;
if (!$CFG_GLPI["use_public_faq"]) {
self::checkValidSessionId();
if (!self::haveRight('knowbase', KnowbaseItem::READFAQ)) {
Html::displayRightError();
}
}
}
/**
* Check if I have access to the helpdesk interface
*
* @return void
**/
static function checkHelpdeskAccess() {
self::checkValidSessionId();
if (Session::getCurrentInterface() != "helpdesk") {
// Gestion timeout session
self::redirectIfNotLoggedIn();
Html::displayRightError();
}
}
/**
* Check if I am logged in
*
* @return void
**/
static function checkLoginUser() {
self::checkValidSessionId();
if (!isset($_SESSION["glpiname"])) {
// Gestion timeout session
self::redirectIfNotLoggedIn();
Html::displayRightError();
}
}
/**
* Check if I have the right $right to module $module (conpare to session variable)
*
* @param string $module Module to check
* @param integer $right Right to check
*
* @return void
**/
static function checkRight($module, $right) {
self::checkValidSessionId();
if (!self::haveRight($module, $right)) {
// Gestion timeout session
self::redirectIfNotLoggedIn();
Html::displayRightError();
}
}
/**
* Check if I one right of array $rights to module $module (conpare to session variable)
*
* @param string $module Module to check
* @param array $rights Rights to check
*
* @return void
**/
static function checkRightsOr($module, $rights = []) {
self::checkValidSessionId();
if (!self::haveRightsOr($module, $rights)) {
self::redirectIfNotLoggedIn();
Html::displayRightError();
}
}
/**
* Check if I have one of the right specified
*
* You can't use this function if several rights for same module name
*
* @param array $modules Array of modules where keys are modules and value are right
*
* @return void
**/
static function checkSeveralRightsOr($modules) {
self::checkValidSessionId();
$valid = false;
if (count($modules)) {
foreach ($modules as $mod => $right) {
// Itemtype
if (preg_match('/[A-Z]/', $mod[0])) {
if ($item = getItemForItemtype($mod)) {
if ($item->canGlobal($right)) {
$valid = true;
}
}
} else if (self::haveRight($mod, $right)) {
$valid = true;
}
}
}
if (!$valid) {
// Gestion timeout session
self::redirectIfNotLoggedIn();
Html::displayRightError();
}
}
/**
* Check if you could access to ALL the entities of an list
*
* @param array $tab List ID of entities
*
* @return boolean
**/
static function haveAccessToAllOfEntities($tab) {
if (is_array($tab) && count($tab)) {
foreach ($tab as $val) {
if (!self::haveAccessToEntity($val)) {
return false;
}
}
}
return true;
}
/**
* Check if you could access (read) to the entity of id = $ID
*
* @param integer $ID ID of the entity
* @param boolean $is_recursive if recursive item (default 0)
*
* @return boolean
**/
static function haveAccessToEntity($ID, $is_recursive = 0) {
// Quick response when passing wrong ID : default value of getEntityID is -1
if ($ID < 0) {
return false;
}
if (!isset($_SESSION['glpiactiveentities'])) {
return false;
}
if (in_array($ID, $_SESSION['glpiactiveentities'])) {
return true;
}
if (!$is_recursive) {
return false;
}
/// Recursive object
return in_array($ID, getAncestorsOf("glpi_entities", $_SESSION['glpiactiveentities']));
}
/**
* Check if you could access to one entity of an list
*
* @param array $tab list ID of entities
* @param boolean $is_recursive if recursive item (default 0)
*
* @return boolean
**/
static function haveAccessToOneOfEntities($tab, $is_recursive = 0) {
if (is_array($tab) && count($tab)) {
foreach ($tab as $val) {