/
inc_intra.php
3154 lines (2591 loc) · 115 KB
/
inc_intra.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
/**
*
* eiseIntra core
* ===
*
* Authentication, form elements display, data handling routines
*
*
* @package eiseIntra
* @version 2.3
*
*/
GLOBAL $eiseIntraKey;
include "inc_version.php";
include "inc_config.php";
if (!class_exists('eiseSQL'))
include "inc_mysqli.php";
include "inc_intra_data.php";
include "inc_item.php";
//define('jQueryVersion', '3.3.1'); // you can re-define this constant in your script if you need more modern jQUery version
//define('jQueryVersion', '1.6.1');
define('jQueryVersion', '1.12.4');
/**
* eiseIntra is the core class that encapsulates routines for authenication, form elements display, data handling, redirection and debug.
*
* This class extends eiseIntraData as base class.
*/
class eiseIntra extends eiseIntraData {
/**
* Array with data of currently logged user:
* - all user data from stbl_user table:
* - usrID - user ID
* - usrName - user name
* - usrNameLocal - user name in local language
* - usrPass - user password (password hash)
* - usrFlagDeleted - is user account deleted or not
* - usrPhone - user's office phone
* - usrEmail - user's email address
* - usrEmployeeID - employee table's ID
* - usrGUID - user GUID
* - usrCN - canonical name of the user
* - usrMobile - user's mobile phone
* - usrInsertBy - user ID who added the user
* - usrInsertDate - when user was added
* - usrEditBy - user ID who changed the user
* - usrEditDate - when user record was changed
* - pagID - database page ID
* - pagTitle (string) - page title in English
* - pagTitleLocal (string) - page title in local language
* - FlagRead (string*) - always '1'
* - FlagCreate (string*) - '0' or '1', as set in database
* - FlagUpdate (string*) - '0' or '1', as set in database
* - FlagDelete (string*) - '0' or '1', as set in database
* - FlagWrite (string*) - '0' or '1', as set in database
* - array roles - array of role titles in currently selected language. Example: `['Managers', 'Users']`
* - array roleIDs - array of role IDs. Example: `['MNG', 'USR']`
*
* (*) - type is 'string' because of PHP function mysql_fetch_assoc()'s nature. It fetches anything like strings despite actual data type in the database.
*
*
* For more details on how and when this data is obtained, please proceed to [eiseIntra::checkPermissions()](#eiseintra-checkpermissions).
*
* @category Authentication
*/
public $arrUsrData = array();
/**
* ID of current user.
*
* @category Authentication
*/
public $usrID = null;
/**
* Configuration array. See description at [eiseIntra::$defaultConf](#eiseintra-deafultconf)
*/
public $conf = array();
/**
* Buffer array with field types that's been generated by the form.
* @category Forms
*/
public $fieldTypes = array();
private $arrHTML5AllowedInputTypes =
Array("color"
#, "date", "datetime", "datetime-local", "time"
, "email", "month", "number", "range", "search", "tel", "url", "week", "password", "text", "file");
private $arrClassInputTypes =
Array("ajax_dropdown", "date", "datetime", "datetime-local", "time");
/**
* Default configuration. Exact configuration parameters list is:
*
* - 'dateFormat' - date format, default is "d.m.Y"
* - 'prgDate' - regular expression for input validation/converion
* - 'prgDateReplaceTo' - replace parameter for preg_replace() for dates, to convert dates from local format to ISO
* - 'timeFormat' - time format, default is "H:i" (24-hours time), both are according to PHP date() format function
* - 'prgTime' - regular expression for input validation
* - 'decimalPlaces' - default decimal places, "2" by default
* - 'decimalSeparator' - decimal seprator, default is "."
* - 'thousandsSeparator' - default is ","
* - 'language' - local language, default is 'rus'
* - 'logofftimeout' - log off timeout in minutes, default is 360 //6 hours
* - 'addEiseIntraValueClass' - setting for for display true
* - 'keyboards' - available keyboard variations (default are 'EN,RU')
* - 'system' - eiseIntra path, last slash stripped (default is `ltrim(dirname($_SERVER['PHP_SELF']), '/')`
* - 'dataActionKey' - 'DataAction', GET or POST key for data update or retrieval
* - 'dataReadKey' - 'DataAction', GET or POST key for data update or retrieval
* - 'flagSetGlobalCookieOnRedirect' - see [eiseIntra::getCookiePath()](#eiseintra-getcookiepath) function for details, default is false
* - 'cachePreventorVar' - Query string parameter for cache prevention in link elements with CSS and JSS. E.g.
* - 'cookiePath' - `(isset($eiseIntraCookiePath) ? $eiseIntraCookiePath : '/')`
* - 'cookieExpire' - see [eiseIntra::getCookiePath()](#eiseintra-getcookiepath) function for details
* - 'UserMessageCookieName' - for cookie used to store user messages, default is 'eiMsg'
* - 'defaultPage' - the page that user see right after authentication.
*
* @category Initialization
*/
public static $defaultConf = array(
'versionIntra'=>EISEINTRA_VERSION
, 'dateFormat' => "d.m.Y" //
, 'timeFormat' => "H:i" //
, 'decimalPlaces' => "2"
, 'decimalSeparator' => "."
, 'thousandsSeparator' => ","
, 'language' => 'rus'
, 'logofftimeout' => 360 //6 hours
, 'addEiseIntraValueClass' => true
, 'keyboards' => 'EN,RU'
, 'dataActionKey' => 'DataAction'
, 'dataReadKey' => 'DataAction'
, 'cachePreventorVar' => 'nc'
, 'system' => 'nc'
, 'cookiePath' => 'nc'
, 'cookieExpire' => 'nc'
// , 'flagSetGlobalCookieOnRedirect' = false
, 'selItemMenu' => null
, 'selItemTopLevelMenu' => null
, 'defaultPage' => 'about.php'
, 'pass_hash' => 'md5'
);
static $arrKeyboard = array(
'EN' => 'qwertyuiop[]asdfghjkl;\'\\zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:"|ZXCVBNM<>?'
, 'RU' => 'йцукенгшщзхъфывапролджэёячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЁЯЧСМИТЬБЮ?'
);
/**
* Constructor receives eiseSQL object with database connection as input parameter and performs object initialization with configuration options supplied in $conf array.
*
* @category Authentication
* @category Initialization
*
* @param eiseSQL $oSQL - MySQL connection object.
* @param array $conf - associative array with configuration options. Defaults are set at [eiseIntra::$defaultConf](#eiseintra-deafultconf)
*/
function __construct($oSQL = null, $conf = Array()){ //$oSQL is not mandatory anymore
GLOBAL $eiseIntraCookiePath
, $eiseIntraCookieExpire
, $eiseIntraUserMessageCookieName
, $localLanguage
, $flagNoAuth;
$this->conf = self::$defaultConf;
$this->conf['system'] = ltrim(dirname($_SERVER['PHP_SELF']), '/');
$this->conf['cookiePath'] = (isset($eiseIntraCookiePath) ? $eiseIntraCookiePath : '/');
$this->conf['cookieExpire'] = (isset($eiseIntraCookieExpire) ? $eiseIntraCookieExpire : null);
$this->conf['UserMessageCookieName'] = ($eiseIntraUserMessageCookieName ? $eiseIntraUserMessageCookieName: 'eiMsg');
$this->conf = array_merge($this->conf, $conf);
parent::__construct($oSQL, $this->conf);
$this->buildLess();
$this->requireComponent('base');
if (!$flagNoAuth || $this->conf['context']) {
try {
$this->checkPermissions();
} catch (eiseException $e) {
if(!$this->conf['context']){
switch($e->getCode()){
case 401:
$PageNoAuth = $_SERVER["PHP_SELF"].($_SERVER["QUERY_STRING"]!="" ? ("?".$_SERVER["QUERY_STRING"]) : "");
SetCookie("PageNoAuth", $PageNoAuth);
header ("Location: login.php?error=".$e->getMessage()
//.'&noauth='.urlencode($PageNoAuth)
);
die();
default:
$backref = $this->backref(false);
if($backref){
$this->redirect('ERROR: '.$e->getMessage(), $backref);
} else
die($e->getMessage());
}
} else {
throw $e;
}
}
}
$this->readSettings();
$this->checkLanguage();
if ($this->local){
@include "common/lang.php";
$this->lang = ($lang ? $lang : array());
}
}
/**
* Function decodes authstring login:password
* using decrypt() method
*
* @category Authentication
*
* @param string $authstring - Encoded string
*
* @return array `[string $login, string $password]`
*/
function decodeAuthString($authstring, $flagBase64 = false){
$auth_str = ($flagBase64 ? base64_decode($authstring) : $this->decrypt($authstring));
preg_match("/^([^\:]+)\:([\S ]+)$/i", $auth_str, $arrMatches);
return Array($arrMatches[1], $arrMatches[2]);
}
/**
* Function encodes authstring login:password
* using encrypt() method.
*
* @category Authentication
*
* @param string $login Login
* @param string $password Password
*
* @return string Encoded authentication string.
*/
function encodeAuthString($login, $password){
return $this->encrypt($login.':'.$password);
}
/**
* This function returns combination of global variable $eiseIntraKey
* stored at eiseIntra's inc_config.php and server variable EISINTRA_KEY that can be set in Nginx or Apache config.
* Key length is set to 128-bit (32 bytes/chars).
*
* If concatentated key length is less that 32 bytes, all remaining places are padded with zeros (0).
*
* When both keys are not set, function returns false and eiseIntra::encrypt() and eiseIntra::decrypt() are forced to work only as base64 encoder/decoder.
*
* @return string Key or false, if both key parts are empty.
*
*/
function getEncryptionKey(){
GLOBAL $eiseIntraKey;
$keylen = 32;
$key = substr($eiseIntraKey.$_SERVER['EISEINTRA_KEY'], 0, $keylen);
$ll = $keylen - strlen($key);
if(!$key)
return false;
else
return ($ll>0
? str_pad($key, $keylen, '0')
: $key
);
}
/**
* Function encrypts a string with symmetric encryption
* using the key obtained from getEncryptionKey() method and current encoding algorithm
* (now RIJNDAEL_256 and mcrypt). In case mcrypt is missed in PHP or encryption key is empty, it encodes string with base64.
*
* @category Authentication
*
* @param string $encrypt String to be encrypted.
*
* @return string Encrypted string.
*/
function encrypt($encrypt) {
$key = $this->getEncryptionKey();
if(!$key || !is_callable('mcrypt_encrypt')){
return base64_encode($encrypt);
}
$encrypt = serialize($encrypt);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
$key = pack('H*', $key);
$mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32));
$passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt.$mac, MCRYPT_MODE_CBC, $iv);
$encoded = base64_encode($passcrypt).'|'.base64_encode($iv);
return $encoded;
}
/**
* Function decrypts a string with symmetric decryption
* using the key obtained from getEncryptionKey() method and current encoding algorithm
* (now RIJNDAEL_256 and mcrypt). In case mcrypt is missed in PHP, it encodes string with base64.
*
* @category Authentication
*
* @param string $encrypt String to be encrypted.
*
* @return string Encrypted string.
*/
function decrypt($decrypt) {
$key = $this->getEncryptionKey();
if(!$key || !is_callable('mcrypt_decrypt')){
return base64_decode($decrypt);
}
$decrypt = explode('|', $decrypt.'|');
$decoded = base64_decode($decrypt[0]);
$iv = base64_decode($decrypt[1]);
if(strlen($iv)!==mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)){ return false; }
$key = pack('H*', $key);
$decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv));
$mac = substr($decrypted, -64);
$decrypted = substr($decrypted, 0, -64);
$calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32));
if($calcmac!==$mac){ return false; }
$decrypted = unserialize($decrypted);
return $decrypted;
}
/**
* This function returns password hash according to hashing method specified in $conf['pass_hash'].
* @category Authentication
*
* @param string $pass The password, the string to be encrypted.
*
* @return string Hash of given string.
*/
function password_hash($pass){
switch ($this->conf['pass_hash']) {
case 'md5':
return md5($pass);
case 'php_password_api':
default:
return password_hash($pass);
break;
}
}
/**
* This function verifies the password across the hash according to hashing method specified in $conf['pass_hash'].
* @category Authentication
*
* @param string $pass The password.
* @param string $hash Hash string to be compared with.
*
* @return string Hash of given string.
*/
function password_verify($pass, $hash){
switch ($this->conf['pass_hash']) {
case 'md5':
return (md5($pass)===$hash);
case 'php_password_api':
default:
return password_verify($pass, $hash);
break;
}
}
/**
* Function that checks authentication with credentials database using selected $method.
* Now it supports the following methods:
* 1. LDAP - it checks credentials with specified GLOBAL $ldap_server with GLOBAL $ldap_domain
* 2. database (or DB) - it checks credentials with database table stbl_user
* 3. mysql - it checks credentials of MySQL database user supplied with $login and $password parameters. Together with authentication this
* Function returns true when authentication successfull, otherwise it returns false and $strError parameter
* variable becomes updated with authentication error message.
*
* LDAP method was successfully tested with Active Directory on Windows 2000, 2003, 2008, 2008R2 servers.
*
* @category Authentication
*
* @param string $login - login name
* @param string $password - password
* @param string $method - authentication method. Can be 'LDAP', 'database'(equal to 'DB'), 'mysql'
* @param array $options - Array
* - 'flagNoSession' (boolean) - Use true when you need one-time authentication without $_SESSION modification.
* - 'dbhost' (string) - Database host, used only with 'mysql' authentication method.
* - 'dbname' (string) - Database name. Default database to be selected with 'mysql' authentication method.
*
* @return boolean authentication result: true on success, otherwise false.
*/
function Authenticate($login, $password, $method="LDAP", $options=array()){
$oSQL = $this->oSQL;
switch($method) {
case "LDAP":
GLOBAL $ldap_server;
GLOBAL $ldap_domain;
GLOBAL $ldap_dn;
GLOBAL $ldap_conn, $ldap_anonymous_login, $ldap_anonymous_pass;
if (preg_match("/^([a-z0-9]+)[\/\\\]([a-z0-9]+)$/i", $login, $arrMatch)){
$login = $arrMatch[2];
$ldap_domain = strtolower($arrMatch[1].".e-ise.com");
} else
if (preg_match("/^([a-z0-9\_]+)[\@]([a-z0-9\.\-]+)$/i", $login, $arrMatch)){
$login = $arrMatch[1];
$ldap_domain = $arrMatch[2];
}
$ldap_conn = ldap_connect($ldap_server);
$binding = @ldap_bind($ldap_conn, $ldap_anonymous_login, $ldap_anonymous_pass);
if (!$binding){
$method = "database";
} else {
$ldap_login = $login."@".$ldap_domain;
$ldap_pass = $password;
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
if ( !($binding = ldap_bind($ldap_conn, $ldap_login, $ldap_pass)) ){
throw new eiseException("Bad Windows user name or password {$ldap_login}");
} else
break;
}
case "database":
case "DB":
if(!$oSQL->connect()){
throw new eiseException("Unable to connect to database");
}
$sqlAuth = "SELECT * FROM stbl_user WHERE usrID='{$login}'";
$rwAuth = $oSQL->f($sqlAuth);
if (!$rwAuth)
throw new eiseException($this->translate("User %s not found", $login));
if ($rwAuth['usrFlagDeleted'])
throw new eiseException($this->translate("User %s is blocked", $login));
if (!$this->password_verify($password, $rwAuth['usrPass']))
throw new eiseException($this->translate("Bad user name or password %s ", $login));
break;
case "mysql":
try {
$this->oSQL = new eiseSQL (
(!$options['dbhost'] ? 'localhost' : $options['dbhost'])
, $login
, $password
, (!$options["dbname"] ? 'mysql' : $options["dbname"])
);
} catch(Exception $e){
throw new eiseException($e->getMessage());
}
break;
}
if($options['flagNoSession'])
return true;
$this->session_initialize();
session_regenerate_id();
if($method=="mysql"){
$_SESSION["DBHOST"] = $this->oSQL->dbhost;
$_SESSION["DBPASS"] = $this->oSQL->dbpass;
}
$_SESSION["last_login_time"] = Date("Y-m-d H:i:s");
$_SESSION["usrID"] = $login;
//$_SESSION["usrID"] = 'TIKHONOVA';
$_SESSION["authstring"] = $this->encodeAuthString($login, $password);
$this->usrID = $_SESSION["usrID"];
SetCookie("last_succesfull_usrID", $login, $this->conf['cookieExpire'], $this->conf['cookiePath']);
return true;
}
/**
* This function intialize session with session cookes placed at path set by $this->conf['cookiePath'] configuration variable.
*
* @category Authentication
*/
function session_initialize(){
@session_set_cookie_params(0, $this->conf['cookiePath']);
session_start();
$this->usrID = $_SESSION["usrID"];
}
/**
* This function quits user session.
*
* @category Authentication
*/
function logout(){
GLOBAL $_DEBUG;
session_set_cookie_params(0, $this->conf['cookiePath']);
session_start();
session_unset();
$_SESSION = array();
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
session_destroy();
SetCookie("last_succesfull_usrID", $this->usrID, $this->conf['cookieExpire'], $this->conf['cookiePath']);
$prj_dir = str_replace('/login.php', '', $_SERVER['PHP_SELF']);
if( $prj_dir !== $_SERVER['PHP_SELF']
&& !(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
&& ( $_SERVER['HTTP_REFERER'] && preg_match('/^'.preg_quote($prj_dir, '/').'/', parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)) )
&& $_DEBUG
){
$PageNoAuth = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)
.(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY)!=""
? "?".parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY)
: '');
SetCookie("PageNoAuth", $PageNoAuth);
}
}
/**
* This function fills in $arrUsrData['roles'] and $arrUsrData['roleIDs'] arrays. Can be overriden for virtual roles.
*
* NOTE: Role membership information is collected from stbl_role_user table basing on rluInsertDate timestamp,
* it should not be in the future. It is useful when some actions should be temporarily delegated to the other user in case of vacations, illness etc.
*
* Page permissions can be set with eiseAdmin's GUI at < database >/Pages menu.
* Role membership can be set by system's GUI at system's Setting/Access Control menu or <database>/Roles menu of eiseAdmin.
*
* @category Authentication
* @category Authorization
*
* @param string $usrID - user ID to get role membership info. If set, this function doesn't touch `$intra->arrUsrData['roles']` and `$intra->arrUsrData['roleIDs']`
*
* @return array with role IDs as keys and role titles are values.
*/
function getUserRoles($usrID = null) {
$usrID_src = $usrID;
if(!$usrID)
$usrID = $this->usrID;
$arrRet = array();
$this->arrUsrData['roleIDs'] = [];
$this->arrUsrData['roles'] = [];
$sql = "SELECT rolID as id, rolTitle{$this->local} as title
FROM stbl_role ROL
INNER JOIN stbl_role_user RLU ON RLU.rluRoleID=ROL.rolID
WHERE (rluUserID='$usrID' AND DATEDIFF(NOW(), rluInsertDate)>=0)
OR rolFlagDefault=1";
$rs = $this->oSQL->q($sql);
while ($rw = $this->oSQL->f($rs)){
$arrRet[(string)$rw['id']] = (string)$rw['title'];
if(!$usrID_src){
$this->arrUsrData['roleIDs'][] = (string)$rw['id'];
$this->arrUsrData['roles'][] = (string)$rw['title'];
}
}
return $arrRet;
}
/**
* This function checks current user's permissions on currently open script.
* Also it checks session expiration time, and condition when user is blocked or not in the database.
* Script name is obtained from `$_SERVER['SCRIPT_NAME']` global variable.
* Permission information is collected from stbl_page_role table and calculated according to user role membership defined at stbl_role_user table.
* Permissions are calulated in the following way:
* - if at least one user's role is permitted to do something, it means that this user is permitted to to it.
*
* If user has no permissions to 'Read' the script, function throws an exception.
* When 'Read' permissions are confirmed for the user, function updates [$intra->arrUsrData property](#eiseintra-arrusrdata). Click on [this link](#eiseintra-arrusrdata) to see full description.
*
* NOTE: Role membership information is collected from stbl_role_user table basing on rluInsertDate timestamp,
* it should not be in the future. It is useful when some actions should be temporarily delegated to the other user in case of vacations, illness etc.
*
* Page permissions can be set with eiseAdmin's GUI at < database >/Pages menu.
* Role membership can be set by system's GUI at system's Setting/Access Control menu or <database>/Roles menu of eiseAdmin.
*
* @category Authentication
* @category Authorization
*
* @return array `$intra->arrUsrData`
*/
function checkPermissions( ){
$oSQL = $this->oSQL;
if( !$this->conf['context'] ){
$this->session_initialize();
if ( !$this->usrID ){
throw new eiseException('', 401);
}
GLOBAL $strSubTitle; // backward-compatibility
// checking user timeout
if ($_SESSION["last_login_time"]!="" && $strSubTitle != "DEVELOPMENT" ){
if (time() - strtotime($_SESSION["last_login_time"])>60*$this->conf['logofftimeout']) {
$tt = Date("Y-m-d H:i:s", mktime())." - ".$_SESSION["last_login_time"];
throw new eiseException($this->translate("Session timeout ($tt). Please re-login."), 401);
}
}
} else {
$this->usrID = $this->conf['usrID'];
}
if ( !$this->usrID ){
throw new eiseException('User ID is not specified', 401);
}
if( !$oSQL ){
return array();
}
//checking is user blocked or not?
$rsUser = $oSQL->do_query("SELECT * FROM stbl_user WHERE usrID=".$oSQL->e($this->usrID));
$rwUser = $oSQL->fetch_array($rsUser);
if (!$rwUser["usrID"]){
throw new eiseException($this->translate("Your User ID %s doesnt exist in master database. Contact system administrator.", $this->usrID), 401 );
}
if ($rwUser["usrFlagDeleted"]){
throw new eiseException( $this->translate("Your User ID %s is blocked.", $this->usrID), 401 );
}
$this->usrID = $rwUser['usrID'];
$this->arrUsrData = array_merge($this->arrUsrData, $rwUser);
$this->getUserRoles();
// checking script permissions
$script_name = ltrim(preg_replace("/^(\/[^\/]+)(\/.*)$/", "\\2", ($this->conf['context']
? $this->conf['context']
: $_SERVER["SCRIPT_NAME"]
)
), '/');
$aScriptName = array($oSQL->e($script_name), $oSQL->e('/'.$script_name));
$sqlCheckUser = "SELECT
pagID
, pagTitle
, pagTitleLocal
, pagFile
, MAX(pgrFlagRead) as FlagRead
, MAX(pgrFlagCreate) as FlagCreate
, MAX(pgrFlagUpdate) as FlagUpdate
, MAX(pgrFlagDelete) as FlagDelete
, MAX(pgrFlagWrite) as FlagWrite
FROM
(SELECT
pagID
, pagTitle
, pagTitleLocal
, pagFile
, pgrFlagRead, pgrFlagCreate, pgrFlagUpdate, pgrFlagDelete, pgrFlagWrite
FROM stbl_page PAG
INNER JOIN stbl_page_role PGR ON PAG.pagID=PGR.pgrPageID
WHERE PAG.pagFile IN (".implode(',', $aScriptName).") AND pgrRoleID IN ('".implode("','", $this->arrUsrData['roleIDs'])."')
UNION
SELECT
pagID
, pagTitle
, pagTitleLocal
, pagFile
, pgrFlagRead, pgrFlagCreate, pgrFlagUpdate, pgrFlagDelete, pgrFlagWrite
FROM stbl_page PAG
INNER JOIN stbl_page_role PGR ON PAG.pagID=PGR.pgrPageID
INNER JOIN stbl_role ROL ON PGR.pgrRoleID=ROL.rolID
WHERE PAG.pagFile IN (".implode(',', $aScriptName).") AND rolFlagDefault=1
)
AS t1
GROUP BY pagID, pagTitle";
$rsChkPerms = $oSQL->do_query($sqlCheckUser);
$rwPerms = $oSQL->fetch_array($rsChkPerms);
if (!$rwPerms["FlagRead"]){
throw new eiseException($this->translate("%s access denied to user %s", ($this->conf['context']
? $this->conf['context']
: $_SERVER['PHP_SELF']),
$this->usrID), 403);
}
$this->arrUsrData = array_merge($this->arrUsrData, $rwPerms);
$clear_uri = preg_replace('/^'.preg_quote(dirname($_SERVER['PHP_SELF']), '/').'/', '', $_SERVER['REQUEST_URI']);
if($rwPage = $oSQL->f($oSQL->q("SELECT * FROM stbl_page WHERE pagFile=".$oSQL->e($clear_uri))) ) {
$this->arrUsrData = array_merge( $this->arrUsrData, $rwPage);
}
if(!$this->conf['context'])
$_SESSION["last_login_time"] = Date("Y-m-d H:i:s");
$this->usrID = $this->arrUsrData["usrID"];
$this->conf['usrID'] = $this->arrUsrData["usrID"];
$this->arrUsrData_src = $this->arrUsrData;
return $this->arrUsrData;
}
/**
* This method returns content of top-level "jumper" menu as drop-down list. "Jumper" menu content goes with an associative array passed as parameter to this function.
*
* @category Navigation
*/
public function topLevelMenu($arrItems = array(), $options = array()){
if(!$arrItems)
return '';
$defaultOptions = array('format' => 'html'
, 'element'=>'select'
, 'class'=>array('ei-top-level-menu')
, 'target' => null);
$options = array_merge_recursive($defaultOptions, (array)$options);
$retVal = '';
if(count($arrItems)>0 && strtolower($options['format'])=='html')
$retVal .= '<'.$options['element'].' class="'.implode(' ', $options['class']).'">';
foreach( (array)$arrItems as $itemID=>$item ){
$itemID_HTML = preg_replace('/[^a-z0-9]/i', '', $itemID);
switch( strtolower($options['element']) ){
case 'select':
$retVal .= "\r\n".'<option value="'.(is_array($item) && $item['value'] ? $item['value'] : $itemID).'"'
.' class="menu-item' .'"'
.' id="'.$options['class'][0].'-'.$itemID_HTML .'">'.(is_array($item)
? $item['title']
: $item).'</option>';
break;
case 'ul':
case 'ol':
$retVal .= "\r\n".'<li id="'.$options['class'][0].'-'.$itemID_HTML.'"'
.' class="menu-item"'
.'>'
.(is_array($item)
? ($item['href'] ? '<a href="'.$item['href'].'">' : '').$item['title'].($item['href'] ? '</a>' : '')
: $item).'</li>';
break;
default:
throw new eiseException('Bad element for top-level menu: '.$options['element']);
}
}
if(count($arrItems)>0)
$retVal .= '</'.$options['element'].'>';
return $retVal;
}
/**
* This method returns system menu `<ul>` HTML for menu structure.
*
* @category Navigation
*
* @param string $target - base target for all `<a href="...">` inside menu
*
* @return string HTML with menu structure
*/
public function menu($target = null){
$target = ($target ? ' target="'.$target.'"' : '');
//-----------------------------Standard menu from stbl_page table---------------------------------
$sql = "SELECT PG1.*
, COUNT(DISTINCT PG2.pagID) as iLevelInside
, (SELECT COUNT(*) FROM stbl_page CH
WHERE CH.pagParentID=PG1.pagID AND CH.pagFlagShowInMenu=1) as nChildren
, MAX(PGR.pgrFlagRead) as FlagRead
, MAX(PGR.pgrFlagWrite) as FlagWrite
FROM stbl_page PG1
INNER JOIN stbl_page PG2 ON PG2.pagIdxLeft<=PG1.pagIdxLeft AND PG2.pagIdxRight>=PG1.pagIdxRight
INNER JOIN stbl_page PG3 ON PG3.pagIdxLeft BETWEEN PG1.pagIdxLeft AND PG1.pagIdxRight AND PG3.pagFlagShowInMenu=1
INNER JOIN stbl_page_role PGR ON PG1.pagID = PGR.pgrPageID
INNER JOIN stbl_role ROL ON PGR.pgrRoleID=ROL.rolID
#LEFT JOIN stbl_role_user RLU ON PGR.pgrRoleID=RLU.rluRoleID
WHERE
#(RLU.rluUserID='{$this->usrID}' OR ROL.rolFlagDefault=1)
(ROL.rolID IN ('".implode("','", $this->arrUsrData['roleIDs'])."') OR ROL.rolFlagDefault=1)
AND PG1.pagFlagShowInMenu=1
GROUP BY
PG1.pagID
, PG1.pagParentID
, PG1.pagTitle{$this->local}
, PG1.pagFile
, PG1.pagIdxLeft
, PG1.pagIdxRight
, PG1.pagFlagShowInMenu
HAVING (MAX(PGR.pgrFlagRead)=1 OR MAX(PGR.pgrFlagWrite)=1)
ORDER BY PG1.pagIdxLeft";
$rs = $this->oSQL->do_query($sql);
$ff = $this->oSQL->ff($rs);
$flagSidebarMenu = isset($ff['pagMenuItemClass']);
if (!$flagSidebarMenu)
//if (false)
return $this->menu_simpleTree($rs, $target);
$strRet = '<ul class="sidebar-menu ei-menu">'."\n";
$rw_old["iLevelInside"] = 2;
while ($rw = $this->oSQL->fetch_array($rs)){
$rw["pagFile"] = preg_replace("/^\//", "", $rw["pagFile"]);
if($rw['pagEntityID']){
$rwEnt = $this->oSQL->f("SELECT * FROM stbl_entity WHERE entID='{$rw['pagEntityID']}'");
$entPrefix = ($rwEnt["entPrefix"] ? $rwEnt["entPrefix"] : $rwEnt['entID']);
} else {
unset($rwEnt);
unset($entPrefix);
}
$hrefSuffix = "";
for ($i=$rw_old["iLevelInside"]; $i>$rw["iLevelInside"]; $i--)
$strRet .= "</ul></li>\n\n";
for ($i=$rw_old["iLevelInside"]; $i<$rw["iLevelInside"]; $i++)
$strRet .= '<ul class="sidebar-submenu">'."\n";
if (preg_match("/list\.php$/", $rw["pagFile"]) && $rw["pagEntityID"]!=""){
$hrefSuffix = "?".$entPrefix."_staID=".($rw['pagFlagShowMyItems'] ? '&'.$rw["pagEntityID"].'_'.$rw["pagEntityID"].'FlagMyItems=' : '') ;
$rwEnt = $this->oSQL->f('SELECT * FROM stbl_entity WHERE entID='.$this->oSQL->e($rw["pagEntityID"]));
}
$pagMenuItemClass = $rw['pagMenuItemClass'] ? $rw['pagMenuItemClass'] : $this->getDefaultClass($rw['pagTitle'], $rw['pagFile']);
$customSubMenu = call_user_func_array(array($this, 'menuItem'), array($rw));
$strRet .= "<li".($rw["pagParentID"]==1 && ($rw["FlagWrite"] || !$this->conf['menuCollapseAll']) && $rw["nChildren"]>0
? ' class="active keep-active"'
: "")
." id=\"".$rw["pagID"]."\">"
.($rw["pagFile"] ? '<a'.$target.' href="'.$rw["pagFile"].$hrefSuffix.'">' : '<a href="#">')
."<i class=\"fa {$pagMenuItemClass}\"></i> "
."<span>".$rw["pagTitle{$this->local}"]."</span>"
.($rw["nChildren"]>0 || preg_match('/^\<ul/i', ltrim($customSubMenu))
? ' <i class="fa fa-angle-left pull-right"></i>'
: '')
.'</a>'
.$customSubMenu
.($rw["nChildren"]==0 ? "</li>" : "")
."\n";
if ($hrefSuffix){
if($rw['pagFlagShowMyItems']){
$strRet .= '<li id="'.$rw["pagID"].'-my-items"><a target="pane" href="'
.$rw["pagFile"].'?'.$rw["pagEntityID"].'_staID=&'.$rw["pagEntityID"].'_'.$rw["pagEntityID"].'FlagMyItems=1">'
.'<i class="fa fa-heart"></i>'
.($this->translate('My ').$rwEnt["entTitle{$this->local}Mul"])
."</a>\n";
}
$sqlSta = "SELECT *
FROM stbl_status
LEFT OUTER JOIN stbl_entity ON entID=staEntityID
WHERE staEntityID='".$rw["pagEntityID"]."' AND staFlagDeleted=0";
$rsSta = $this->oSQL->do_query($sqlSta);
while ($rwSta = $this->oSQL->fetch_array($rsSta)){
$staMenuItemClass = $rwSta['staMenuItemClass'] ? $rwSta['staMenuItemClass'] : 'fa-circle-o';
$customSubMenu_sta = call_user_func_array(array($this, 'menuItem'), array($rw, $rwSta));
$strRet .= "<li id='".$rw["pagID"]."_".$rwSta["staID"]."'><a{$target} href='"
.$rw["pagFile"]."?{$entPrefix}_staID={$rwSta["staID"]}'>"
.'<i class="fa '.$staMenuItemClass.'"></i>'
.($rwSta["staTitle{$this->local}Mul"] ? $rwSta["staTitle{$this->local}Mul"] : $rwSta["staTitle{$this->local}"])
.(preg_match('/^\<ul/i', ltrim($customSubMenu_sta))
? ' <i class="fa fa-angle-left pull-right"></i>'
: '')
.'</a>'
.$customSubMenu_sta
."\n";
}
}
$rw_old = $rw;
}
for ($i=$rw_old["iLevelInside"]; $i>1; $i--)
$strRet .= "</ul>\n\n";
$strRet .= '</ul>'."\n\n"; // /div.ei-menu
return $strRet;
}
/**
* This method is called __before__ each menu item <li> closure.
* You can add custom menu items/submenus in your own app overriding this method in the inherited class.
*
* @category Navigation
*
* @param string $rw - row info from stbl_page for current <li>
*
* @return string HTML with submenu structure
*/
public function menuItem($rw){ return ''; }
public function getCurrentUserInfo(){
$html = '';
$html .= '<div class="ei-current-user-info">';
$html .= '<span class="ui-helper-hidden-accessible"><input type="text"/></span>';
$html .= '<div class="ei-usrName">'.$this->arrUsrData['usrName'.$this->local].'</div>';
$html .= '<div class="ei-usrRoles">'.$this->translate('Roles:').'</div>';
$html .= '<ul class="ei-roles">';
foreach ($this->arrUsrData['roles'] as $ix => $roleTitle) {
$html .= "<li><span class=\"ei-rolTitle\">{$roleTitle}</span> <small>({$this->arrUsrData['roleIDs'][$ix]})</small></li>";
}
$html .= '</ul>';
$html .= '<div class="ei-logout"><a href="login.php">'.$this->translate('Logout').' <i class="fa fa-sign-out"> </i></a></div>';
$html .= '</div>';
return $html;
}
/**
* This function returns default icon menu class basng on page URI.
* @ignore
*/
private function getDefaultClass($title, $uri){
$prfx = 'fa-';
$allstr = $title.$uri;
$filename = pathinfo(parse_url($uri, PHP_URL_PATH),PATHINFO_FILENAME);
if(preg_match('/search/i', $allstr))
return $prfx.'search';
if(preg_match('/tools/i', $allstr))
return $prfx.'wrench';
if(preg_match('/(settings|setup)/i', $allstr))
return $prfx.'sliders';
if(preg_match('/users/i', $allstr))
return $prfx.'group';
if(preg_match('/about/i', $allstr))
return $prfx.'book';
if(preg_match('/^(rep|report)[\-\_]/i', $filename) || preg_match('/[\-\_]rep$/i', $filename))
return $prfx.'bar-chart';
if(preg_match('/^lst[\-\_]/i', $filename) || preg_match('/[\-\_](list|lst)$/i', $filename))
return $prfx.'table';
if(preg_match('/^frm[\-\_]/i', $filename) || preg_match('/[\-\_](form|frm)$/i', $filename))
return $prfx.'list-alt';
if(!$uri)