-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
Users.php
1763 lines (1585 loc) · 65.9 KB
/
Users.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
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once 'include/logging.php';
require_once 'include/database/PearDatabase.php';
require_once 'include/utils/UserInfoUtil.php';
require_once 'data/CRMEntity.php';
require_once 'modules/Contacts/Contacts.php';
require_once 'data/Tracker.php';
require_once 'include/utils/CommonUtils.php';
require_once 'include/Webservices/Utils.php';
require_once 'modules/Users/UserTimeZonesArray.php';
require_once 'modules/Users/UserPrivilegesWriter.php';
require_once 'modules/Users/UserPrivileges.php';
include_once 'modules/Users/authTypes/TwoFactorAuth/autoload.php';
use \RobThree\Auth\TwoFactorAuth;
class Users extends CRMEntity {
// Stored fields
public $id;
public $authenticated = false;
public $twoFAauthenticated = false;
public $error_string;
public $is_admin;
public $deleted;
public $tab_name = array('vtiger_users', 'vtiger_attachments', 'vtiger_user2role', 'vtiger_asteriskextensions');
public $tab_name_index = array('vtiger_users'=>'id', 'vtiger_attachments'=>'attachmentsid', 'vtiger_user2role'=>'userid', 'vtiger_asteriskextensions'=>'userid');
public $moduleIcon = array('library' => 'standard', 'containerClass' => 'slds-icon_container slds-icon-standard-user', 'class' => 'slds-icon', 'icon'=>'user');
public $table_name = 'vtiger_users';
public $table_index = 'id';
// This is the list of fields that are in the lists.
public $list_link_field = 'last_name';
public $list_mode;
public $popup_type;
public $search_fields = array(
'Name' => array('vtiger_users' => 'last_name'),
'Email' => array('vtiger_users' => 'email1'),
'Email2' => array('vtiger_users' => 'email2'),
);
public $search_fields_name = array(
'Name' => 'last_name',
'Email' => 'email1',
'Email2' => 'email2',
);
public $module_name = 'Users';
public $user_preferences;
public $homeorder_array = array(
'HDB'=>'',
'ALVT'=>'',
'PLVT'=>'',
'QLTQ'=>'',
'CVLVT'=>'',
'HLT'=>'',
'GRT'=>'',
'OLTSO'=>'',
'ILTI'=>'',
'MNL'=>'',
'OLTPO'=>'',
'LTFAQ'=>'',
'UA'=>'',
'PA'=>'',
);
public $encodeFields = array('first_name', 'last_name', 'description');
public $sortby_fields = array('status', 'email1', 'email2', 'phone_work', 'is_admin', 'user_name', 'last_name');
// This is the list of fields that are in the lists.
public $list_fields = array(
'First Name' => array('vtiger_users' => 'first_name'),
'Last Name' => array('vtiger_users' => 'last_name'),
'Role Name' => array('vtiger_user2role' => 'roleid'),
'User Name' => array('vtiger_users' => 'user_name'),
'Status' => array('vtiger_users' => 'status'),
'Email' => array('vtiger_users' => 'email1'),
'Email2' => array('vtiger_users' => 'email2'),
'Admin' => array('vtiger_users' => 'is_admin'),
'Phone' => array('vtiger_users' => 'phone_work'),
);
public $list_fields_name = array(
'Last Name' => 'last_name',
'First Name' => 'first_name',
'Role Name' => 'roleid',
'User Name' => 'user_name',
'Status' => 'status',
'Email' => 'email1',
'Email2' => 'email2',
'Admin' => 'is_admin',
'Phone' => 'phone_work',
);
public $list_fields_names = array(
'Tools' => 'id',
'username' => 'user_name',
'Email' => 'email1',
'Admin' => 'is_admin',
'Email2' => 'email2',
'Status' => 'status',
);
public $popup_fields = array('last_name');
// For Alphabetical search
public $def_basicsearch_col = 'user_name';
// This is the list of fields that are in the lists.
public $default_order_by = 'user_name';
public $default_sort_order = 'ASC';
public $record_id;
public $DEFAULT_PASSWORD_CRYPT_TYPE;
// BLOWFISH before PHP5.3 MD5
/**
* @var UserPrivileges
*/
private $privileges;
public function __construct() {
global $log;
$log->debug('> Users');
$this->DEFAULT_PASSWORD_CRYPT_TYPE = (version_compare(PHP_VERSION, '5.3.0') >= 0) ? 'PHP5.3MD5' : 'MD5';
$this->column_fields = getColumnFields('Users');
$this->column_fields['currency_name'] = '';
$this->column_fields['currency_code'] = '';
$this->column_fields['currency_symbol'] = '';
$this->column_fields['conv_rate'] = '';
$log->debug('< Users');
}
/**
* Function to get sort order
* @return string sort order string either 'ASC' or 'DESC'
*/
public function getSortOrder() {
global $log, $adb;
$log->debug('> getSortOrder');
if (isset($_REQUEST['sorder'])) {
$sorder = $adb->sql_escape_string($_REQUEST['sorder']);
} else {
$sorder = (!empty($_SESSION['USERS_SORT_ORDER']) ? ($_SESSION['USERS_SORT_ORDER']) : ($this->default_sort_order));
}
$log->debug('< getSortOrder');
return $sorder;
}
/**
* Function to get order by
* @return string order by fieldname (eg: 'subject')
*/
public function getOrderBy() {
global $log, $adb;
$log->debug('> getOrderBy');
$use_default_order_by = '';
if (GlobalVariable::getVariable('Application_ListView_Default_Sorting', 0)) {
$use_default_order_by = $this->default_order_by;
}
if (isset($_REQUEST['order_by'])) {
$order_by = $adb->sql_escape_string($_REQUEST['order_by']);
} else {
$order_by = (!empty($_SESSION['USERS_ORDER_BY']) ? ($_SESSION['USERS_ORDER_BY']) : ($use_default_order_by));
}
$log->debug('< getOrderBy');
return $order_by;
}
/** Function to set the user preferences in the session
* @param string name
* @param string value
*/
public function setPreference($name, $value) {
if (!isset($this->user_preferences)) {
if (isset($_SESSION['USER_PREFERENCES'])) {
$this->user_preferences = $_SESSION['USER_PREFERENCES'];
} else {
$this->user_preferences = array();
}
}
if (!array_key_exists($name, $this->user_preferences) || $this->user_preferences[$name] != $value) {
global $log;
$log->debug('Saving To Preferences', [$name, $value]);
$this->user_preferences[$name] = $value;
$this->savePreferecesToDB();
}
coreBOS_Session::set($name, $value);
}
/** Function to save the user preferences to db
*
*/
public function savePreferecesToDB() {
global $adb;
$data = base64_encode(serialize($this->user_preferences));
$adb->pquery("UPDATE $this->table_name SET user_preferences=? where id=?", array($data, $this->id));
coreBOS_Session::set('USER_PREFERENCES', $this->user_preferences);
}
/** Function to load the user preferences from db
*
*/
public function loadPreferencesFromDB($value) {
if (isset($value) && !empty($value)) {
global $log;
$log->debug('LOADING :PREFERENCES SIZE ' . strlen($value));
$this->user_preferences = unserialize(base64_decode($value));
coreBOS_Session::merge($this->user_preferences);
coreBOS_Session::set('USER_PREFERENCES', $this->user_preferences);
$log->debug('Finished Loading');
}
}
/**
* Take an unencrypted username and password and return the encrypted password
* @return string encrypted password for storage in DB and comparison against DB password.
* @param string $user_name - Must be non null and at least 2 characters
* @param string $user_password - Must be non null and at least 1 character.
*/
public function encrypt_password($user_password, $crypt_type = '') {
// encrypt the password.
$salt = substr($this->column_fields['user_name'], 0, 2);
if ($crypt_type == '') {
// Try to get the crypt_type which is in database for the user
$crypt_type = $this->get_user_crypt_type();
}
// For more details on salt format look at: http://in.php.net/crypt
if ($crypt_type == 'MD5') {
$salt = '$1$' . $salt . '$';
} elseif ($crypt_type == 'BLOWFISH') {
$salt = '$2$' . $salt . '$';
} elseif ($crypt_type == 'PHP5.3MD5') {
//only change salt for php 5.3 or higher version for backward
//compactibility.
//crypt API is lot stricter in taking the value for salt.
$salt = '$1$' . str_pad($salt, 9, '0');
}
return crypt($user_password, $salt);
}
/** Function for authorization check */
public function authorization_check($validate, $authkey, $i) {
$validate = base64_decode($validate);
$authkey = base64_decode($authkey);
if (file_exists($validate) && $handle = fopen($validate, 'rb', true)) {
$buffer = fread($handle, filesize($validate));
if (substr_count($buffer, $authkey) < $i) {
return -1;
}
} else {
return -1;
}
}
/**
* Checks the User_AuthenticationType global variavle value for login type and forks off to the proper module
*
* @param string $user_password - The password of the user to authenticate
* @return boolean true if the user is authenticated, false otherwise
*/
public function doLogin($user_password) {
global $log, $adb;
$usr_name = $this->column_fields['user_name'];
$result = $adb->pquery('select id from vtiger_users where user_name=?', array($usr_name));
if ($result && $adb->num_rows($result)==1) {
$row = $adb->fetchByAssoc($result);
$userid = $row['id'];
} else {
return false;
}
$authType = GlobalVariable::getVariable('User_AuthenticationType', 'SQL', 'Users', $userid);
$sql_auth_users = GlobalVariable::getVariable('User_MandatoryAuthenticationSQL', 'admin', 'Users', $userid);
$sql_auth_users = explode(',', $sql_auth_users);
if (in_array($usr_name, $sql_auth_users)) {
$log->debug("$usr_name exists in sql_auth_users, so using SQL Authentication");
$authType = 'SQL';
}
switch (strtoupper($authType)) {
case 'LDAP':
$log->debug('Using LDAP authentication');
require_once 'modules/Users/authTypes/LDAP.php';
return (ldapAuthenticate($usr_name, $user_password) != null);
break;
case 'AD':
$log->debug('Using Active Directory authentication');
require_once 'modules/Users/authTypes/adLDAP.php';
$adldap = new adLDAP();
return $adldap->authenticate($usr_name, $user_password);
break;
default:
$log->debug('Using integrated/SQL authentication');
$query = "SELECT crypt_type FROM $this->table_name WHERE BINARY user_name=?";
$result = $adb->requirePsSingleResult($query, array($usr_name), false);
if (empty($result)) {
return false;
}
$crypt_type = $adb->query_result($result, 0, 'crypt_type');
$encrypted_password = $this->encrypt_password($user_password, $crypt_type);
$maxFailedLoginAttempts = GlobalVariable::getVariable('Application_MaxFailedLoginAttempts', 5);
$query = "SELECT * from $this->table_name where user_name=? AND user_password=?";
$params = array($usr_name, $encrypted_password);
$cnuser=$adb->getColumnNames($this->table_name);
if (in_array('failed_login_attempts', $cnuser)) {
$query.= ' AND COALESCE(failed_login_attempts,0)<?';
$params[] = $maxFailedLoginAttempts;
}
return $adb->requirePsSingleResult($query, $params, false);
break;
}
return false;
}
public static function send2FACode($code, $userid) {
global $adb;
$msg = sprintf(getTranslatedString('2FA_ACCESSCODE', 'Users'), $code);
$SendCodeMethod = strtoupper(GlobalVariable::getVariable('User_2FAAuthentication_SendMethod', 'EMAIL', 'Users', $userid));
if (!vtlib_isModuleActive('SMSNotifier') && $SendCodeMethod=='SMS') {
$SendCodeMethod = 'EMAIL';
}
switch ($SendCodeMethod) {
case 'SMS':
require_once 'modules/SMSNotifier/SMSNotifier.php';
$rs = $adb->pquery('select coalesce(phone_work,phone_mobile) as phone from vtiger_users where userid=?', array($userid));
if ($rs && $adb->num_rows($rs)>0) {
$phone = $adb->query_result($rs, 0, 0);
if (!empty($phone)) {
SMSNotifier::sendsms($msg, $phone, $userid, $userid, 'Users');
}
}
break;
case 'MOBILE':
break;
case 'EMAIL':
default:
require_once 'modules/Emails/mail.php';
require_once 'modules/Emails/Emails.php';
$HELPDESK_SUPPORT_EMAIL_ID = GlobalVariable::getVariable('HelpDesk_Support_EMail', 'support@your_support_domain.tld', 'HelpDesk', $userid);
$HELPDESK_SUPPORT_NAME = GlobalVariable::getVariable('HelpDesk_Support_Name', 'your-support name', 'HelpDesk', $userid);
$mailto = getUserEmail($userid);
if ($mailto!='') {
send_mail('Emails', $mailto, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $msg, $msg);
}
break;
}
}
/**
* Load a user based on the user_name in $this
* @return mixed Users if load was successul and null if load failed
*/
public function load_user($user_password) {
global $log, $adb;
$usr_name = $this->column_fields['user_name'];
if (!empty($_POST['twofauserauth'])) {
$this->authenticated = false;
$this->twoFAauthenticated = false;
// csrf check
// Get the fields for the user
$query = "SELECT * from $this->table_name where user_name='$usr_name'";
$result = $adb->requireSingleResult($query, false);
$row = $adb->fetchByAssoc($result);
if ($row['id']!=$_POST['twofauserauth']) {
return null;
}
// validate 2fa
$coreBOSWebApp = GlobalVariable::getVariable('Application_UI_Name', 'coreBOS').'-'.getUserName($row['id']);
$tfa = new TwoFactorAuth($coreBOSWebApp);
$twofasecret = coreBOS_Settings::getSetting('coreBOS_2FA_Secret_'.$row['id'], false);
if ($twofasecret === false || $tfa->verifyCode($twofasecret, $_POST['user_2facode']) === false) {
return null;
}
$this->column_fields = $row;
$this->id = $row['id'];
$this->authenticated = true;
$this->twoFAauthenticated = true;
return $this;
}
$maxFailedLoginAttempts = GlobalVariable::getVariable('Application_MaxFailedLoginAttempts', 5, 'Users');
if (isset($_SESSION['loginattempts'])) {
coreBOS_Session::set('loginattempts', $_SESSION['loginattempts'] + 1);
} else {
coreBOS_Session::set('loginattempts', 1);
}
if ($_SESSION['loginattempts'] > $maxFailedLoginAttempts) {
$log->warn('SECURITY: ' . $usr_name . ' has attempted to login ' . $_SESSION['loginattempts'] . ' times.');
}
$log->debug("Starting user load for $usr_name");
if (!isset($this->column_fields['user_name']) || $this->column_fields['user_name'] == '' || !isset($user_password) || $user_password == '') {
return null;
}
$authCheck = false;
$authCheck = $this->doLogin($user_password);
if (!$authCheck) {
$log->warn("User authentication for $usr_name failed");
return null;
}
// Get the fields for the user
$query = "SELECT * from $this->table_name where user_name='$usr_name'";
$result = $adb->requireSingleResult($query, false);
$row = $adb->fetchByAssoc($result);
$this->column_fields = $row;
$this->id = $row['id'];
$this->loadPreferencesFromDB($row['user_preferences']);
// Make sure user is logging in from authorized IPs
$UserLoginIPs = GlobalVariable::getVariable('Application_UserLoginIPs', '', 'Users', $this->id);
if ($UserLoginIPs != '') {
$user_ip_addresses = explode(',', $UserLoginIPs);
$the_ip = Vtiger_Request::get_ip();
if (!in_array($the_ip, $user_ip_addresses)) {
$row['status'] = 'Inactive';
$this->authenticated = false;
coreBOS_Session::set('login_error', getTranslatedString('ERR_INVALID_USERIPLOGIN', 'Users'));
$mailsubject = "[Security Alert]: User login attempt rejected for login: $usr_name from external IP: $the_ip";
$log->warn($mailsubject);
// Send email with authentification error.
$mailto = GlobalVariable::getVariable('Debug_Send_UserLoginIPAuth_Error', '', 'Users');
if ($mailto != '') {
require_once 'modules/Emails/mail.php';
require_once 'modules/Emails/Emails.php';
$HELPDESK_SUPPORT_EMAIL_ID = GlobalVariable::getVariable('HelpDesk_Support_EMail', 'support@your_support_domain.tld', 'HelpDesk');
$HELPDESK_SUPPORT_NAME = GlobalVariable::getVariable('HelpDesk_Support_Name', 'your-support name', 'HelpDesk');
$mailcontent = $mailsubject. "\n";
send_mail('Emails', $mailto, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $mailsubject, $mailcontent);
}
}
}
// Make sure admin is logging in from authorized IPs
if ($row['is_admin'] == 'on' || $row['is_admin'] == '1') {
$AdminLoginIPs = GlobalVariable::getVariable('Application_AdminLoginIPs', '', 'Users', $this->id);
if ($AdminLoginIPs != '') {
$admin_ip_addresses = explode(',', $AdminLoginIPs);
$the_ip = Vtiger_Request::get_ip();
if (!in_array($the_ip, $admin_ip_addresses)) {
$row['status'] = 'Inactive';
$this->authenticated = false;
coreBOS_Session::set('login_error', getTranslatedString('ERR_INVALID_ADMINIPLOGIN', 'Users'));
$mailsubject = "[Security Alert]: Admin login attempt rejected for login: $usr_name from external IP: $the_ip";
$log->warn($mailsubject);
// Send email with authentification error.
$mailto = GlobalVariable::getVariable('Debug_Send_AdminLoginIPAuth_Error', '', 'Users');
if ($mailto != '') {
require_once 'modules/Emails/mail.php';
require_once 'modules/Emails/Emails.php';
$HELPDESK_SUPPORT_EMAIL_ID = GlobalVariable::getVariable('HelpDesk_Support_EMail', 'support@your_support_domain.tld', 'HelpDesk');
$HELPDESK_SUPPORT_NAME = GlobalVariable::getVariable('HelpDesk_Support_Name', 'your-support name', 'HelpDesk');
$mailcontent = $mailsubject. "\n";
send_mail('Emails', $mailto, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $mailsubject, $mailcontent);
}
}
}
}
if ($row['status'] != 'Inactive') {
$this->authenticated = true;
}
coreBOS_Session::delete('loginattempts');
return $this;
}
/**
* Get crypt type to use for password for the user.
*/
public function get_user_crypt_type() {
global $adb;
$crypt_res = null;
$crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
// For backward compatability, we need to make sure to handle this case.
$table_cols = $adb->getColumnNames('vtiger_users');
if (!in_array('crypt_type', $table_cols)) {
return $crypt_type;
}
if (isset($this->id)) {
// Get the type of crypt used on password before actual comparision
$qcrypt_sql = "SELECT crypt_type from $this->table_name where id=?";
$crypt_res = $adb->pquery($qcrypt_sql, array($this->id), true);
} elseif (isset($this->column_fields['user_name'])) {
$qcrypt_sql = "SELECT crypt_type from $this->table_name where user_name=?";
$crypt_res = $adb->pquery($qcrypt_sql, array($this->column_fields['user_name']));
} else {
$crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
}
if ($crypt_res && $adb->num_rows($crypt_res)) {
$crypt_row = $adb->fetchByAssoc($crypt_res);
$crypt_type = $crypt_row['crypt_type'];
}
return $crypt_type;
}
/**
* Verify that the current password is correct and write the new password to the database
* @param string $user name - Must be non null and at least 1 character
* @param string $user_password - Must be non null and at least 1 character
* @param string $new_password - Must be non null and at least 1 character
* @return boolean If passwords pass verification and query succeeds, return true, else return false
*/
public function change_password($user_password, $new_password, $dieOnError = true) {
global $current_user, $log, $adb;
$usr_name = $this->column_fields['user_name'];
$log->debug("Starting password change for $usr_name");
if (!isset($new_password) || $new_password == '') {
$this->error_string = getTranslatedString('ERR_PASSWORD_CHANGE_FAILED_1', 'Users').$usr_name.getTranslatedString('ERR_PASSWORD_CHANGE_FAILED_2', 'Users');
return false;
}
//set new password
$crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
$encrypted_new_password = $this->encrypt_password($new_password, $crypt_type);
$passhistory = $adb->pquery(
'select 1 from password_history where crmid=? and crmtype=? and pass=?',
array($this->id, 'U', $encrypted_new_password)
);
if (!$passhistory || $adb->num_rows($passhistory) > 0) {
$this->error_string = getTranslatedString('ERR_PASSWORD_REPEATED', 'Users');
return false;
}
$adb->pquery(
'insert into password_history values (?,?,?)',
array($this->id, 'U', $encrypted_new_password)
);
if (GlobalVariable::getVariable('Application_SendUserPasswordByEmail', 0, 'Users')) {
require_once 'modules/Emails/Emails.php';
$context = array(
'$user_name$'=> $usr_name,
'$user_password$'=> $new_password
);
Emails::sendEmailTemplate('Password Change Template', $context, 'Users', $this->column_fields['email1'], $this->id);
}
$sql = "UPDATE $this->table_name SET failed_login_attempts=0 where id=?";
$adb->pquery($sql, array($this->id));
// Set change password at next login to 0 if resetting your own password
if (!empty($current_user) && $current_user->id == $this->id) {
$change_password_next_login = 0;
} else {
$change_password_next_login = 1;
}
$cnuser=$adb->getColumnNames($this->table_name);
if (!in_array('change_password', $cnuser)) {
$adb->query('ALTER TABLE `vtiger_users` ADD `change_password` boolean NOT NULL DEFAULT 0');
}
if (!in_array('last_password_reset_date', $cnuser)) {
$adb->query('ALTER TABLE `vtiger_users` ADD `last_password_reset_date` date DEFAULT NULL');
}
$query = "UPDATE $this->table_name
SET user_password=?, confirm_password=?, crypt_type=?, change_password=?, last_password_reset_date=now(), failed_login_attempts=0
where id=?";
$adb->pquery($query, array($encrypted_new_password, $encrypted_new_password, $crypt_type, $change_password_next_login, $this->id));
$this->createAccessKey();
require_once 'modules/Users/UserPrivilegesWriter.php';
UserPrivilegesWriter::setUserPrivileges($this->id);
return true;
}
public function mustChangePassword() {
global $adb;
if (empty($this->id)) {
return false;
}
$cnuser=$adb->getColumnNames('vtiger_users');
if (!in_array('change_password', $cnuser)) {
$adb->query('ALTER TABLE `vtiger_users` ADD `change_password` boolean NOT NULL DEFAULT 0');
}
$cprs = $adb->pquery('select change_password from vtiger_users where id=?', array($this->id));
return $adb->query_result($cprs, 0, 0);
}
public function de_cryption($data) {
require_once 'include/utils/encryption.php';
$decrypted_password = '';
$de_crypt = new Encryption();
if (isset($data)) {
$decrypted_password = $de_crypt->decrypt($data);
}
return $decrypted_password;
}
public function changepassword($newpassword) {
require_once 'include/utils/encryption.php';
$en_crypt = new Encryption();
if (isset($newpassword)) {
$encrypted_password = $en_crypt->encrypt($newpassword);
}
return $encrypted_password;
}
public function verifyPassword($password) {
global $adb;
$result = $adb->pquery("SELECT user_name,user_password,crypt_type FROM {$this->table_name} WHERE id=?", array($this->id));
$row = $adb->fetchByAssoc($result);
$encryptedPassword = $this->encrypt_password($password, $row['crypt_type']);
return $encryptedPassword == $row['user_password'];
}
public function is_authenticated() {
return $this->authenticated;
}
public function is_twofaauthenticated() {
$do2FA = GlobalVariable::getVariable('User_2FAAuthentication', 0, 'Users', (empty($this->id) ? Users::getActiveAdminId() : $this->id));
if ($do2FA) {
return $this->twoFAauthenticated;
} else {
return true;
}
}
/** gives the user id for the specified user name
* @param string user name
* @return integer user id
*/
public function retrieve_user_id($user_name) {
global $adb;
$query = 'SELECT id from vtiger_users where user_name=? AND deleted=0';
$result = $adb->pquery($query, array($user_name));
if ($result && $adb->num_rows($result) > 0) {
$userid = $adb->query_result($result, 0, 'id');
} else {
$userid = 0;
}
return $userid;
}
/** check if given number is a valid and active user ID
* @param integer $userid
* @return boolean
*/
public static function is_ActiveUserID($userid) {
global $adb;
if (empty($userid) || !is_numeric($userid)) {
return false;
}
$query = "SELECT 1 from vtiger_users where status='Active' AND id=? AND deleted=0";
$result = $adb->pquery($query, array($userid));
return ($result && $adb->num_rows($result) > 0);
}
/**
* @return boolean user name exists already or not
*/
public function verify_data() {
global $mod_strings, $log, $adb;
$usr_name = $this->column_fields['user_name'];
$query = 'SELECT user_name from vtiger_users where user_name=? AND id<>? AND deleted=0';
$result = $adb->pquery($query, array($usr_name, $this->id), true, 'Error selecting possible duplicate users: ');
$dup_users = $adb->fetchByAssoc($result);
$query = "SELECT user_name from vtiger_users where is_admin = 'on' AND deleted=0";
$result = $adb->pquery($query, array(), true, 'Error selecting possible duplicate users: ');
$last_admin = $adb->fetchByAssoc($result);
$log->debug('last admin length: ' . count($last_admin));
$log->debug($last_admin['user_name'] . ' == ' . $usr_name);
$verified = true;
if ($dup_users != null) {
$this->error_string .= $mod_strings['ERR_USER_NAME_EXISTS_1'] . $usr_name . '' . $mod_strings['ERR_USER_NAME_EXISTS_2'];
$verified = false;
}
if (!isset($_REQUEST['is_admin']) && count($last_admin) == 1 && $last_admin['user_name'] == $usr_name) {
$log->debug('last admin length: ' . count($last_admin));
$this->error_string .= $mod_strings['ERR_LAST_ADMIN_1'] . $usr_name . $mod_strings['ERR_LAST_ADMIN_2'];
$verified = false;
}
return $verified;
}
/** Function to return the column name array */
public function getColumnNames_User() {
return array('FIRSTNAME', 'LASTNAME', 'USERNAME', 'SECONDARYEMAIL', 'TITLE', 'OFFICEPHONE', 'DEPARTMENT', 'MOBILE', 'OTHERPHONE', 'FAX', 'EMAIL',
'HOMEPHONE', 'OTHEREMAIL', 'PRIMARYADDRESS', 'CITY', 'STATE', 'POSTALCODE', 'COUNTRY');
}
public function fill_in_additional_list_fields() {
$this->fill_in_additional_detail_fields();
}
public function fill_in_additional_detail_fields() {
global $log, $adb;
$query = 'SELECT u1.first_name, u1.last_name from vtiger_users u1, vtiger_users u2 where u1.id=u2.reports_to_id AND u2.id=? and u1.deleted=0';
$result = $adb->pquery($query, array($this->id), true, 'Error filling in additional detail vtiger_fields');
$row = $adb->fetchByAssoc($result);
$log->debug('< fill_in_additional_detail_fields '.$row);
if ($row != null) {
$this->reports_to_name = stripslashes(getFullNameFromArray('Users', $row));
} else {
$this->reports_to_name = '';
}
}
/** Function to get the current user information from the user_privileges file
* @param integer user id
* @return object user object with info in $this->column_fields
*/
public function retrieveCurrentUserInfoFromFile($userid) {
global $adb, $site_URL;
$this->id = $userid;
$userprivs = $this->getPrivileges();
$user_info = $userprivs->getUserInfo();
foreach ($this->column_fields as $field => $value_iter) {
if (isset($user_info[$field])) {
$this->$field = $user_info[$field];
$this->column_fields[$field] = $user_info[$field];
}
}
$imageurl = '';
$image_name = empty($this->column_fields['imagename']) ? '' : $this->column_fields['imagename'];
if ($image_name != '') {
$sql = "select vtiger_attachments.*
from vtiger_attachments
inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid
where vtiger_crmentity.setype='Users Attachment' and vtiger_attachments.name = ?";
$image_res = $adb->pquery($sql, array(str_replace(' ', '_', decode_html($image_name))));
if ($adb->num_rows($image_res)>0) {
$image_id = $adb->query_result($image_res, 0, 'attachmentsid');
$image_path = $adb->query_result($image_res, 0, 'path');
$image_name = decode_html($adb->query_result($image_res, 0, 'name'));
$imageurl = array(
'name' => $image_name,
'path' => $image_path . $image_id . '_' . urlencode($image_name),
'fullpath' => $site_URL.'/'.$image_path . $image_id . '_' . urlencode($image_name),
'type' => $adb->query_result($image_res, 0, 'type'),
'id' => $image_id,
);
}
}
$this->column_fields['imagenameimageinfo'] = $imageurl;
return $this;
}
/** Function to save the user information into the database
* @param string module name
*/
public function saveentity($module, $fileid = '') {
global $adb;
$insertion_mode = $this->mode;
if (empty($this->column_fields['time_zone'])) {
$dbDefaultTimeZone = DateTimeField::getDBTimeZone();
$this->column_fields['time_zone'] = $dbDefaultTimeZone;
$this->time_zone = $dbDefaultTimeZone;
}
if (empty($this->column_fields['currency_id'])) {
$this->column_fields['currency_id'] = CurrencyField::getDBCurrencyId();
}
if (empty($this->column_fields['date_format'])) {
$this->column_fields['date_format'] = 'yyyy-mm-dd';
}
$adb->println("TRANS saveentity starts $module");
$adb->startTransaction();
foreach ($this->tab_name as $table_name) {
if ($table_name == 'vtiger_attachments') {
$this->insertIntoAttachment($this->id, $module, $fileid);
} else {
$this->insertIntoEntityTable($table_name, $module, $fileid);
}
}
require_once 'modules/Users/UserPrivilegesWriter.php';
UserPrivilegesWriter::setUserPrivileges($this->id);
coreBOS_Session::delete('next_reminder_interval');
coreBOS_Session::delete('next_reminder_time');
if ($insertion_mode != 'edit') {
$this->createAccessKey();
}
$adb->completeTransaction();
$adb->println('TRANS saveentity ends');
}
public function createAccessKey() {
global $log, $adb;
$log->debug('>< createAccessKey');
$adb->pquery('update vtiger_users set accesskey=? where id=?', array(vtws_generateRandomAccessKey(16), $this->id));
}
/** Function to insert values in the specifed table for the specified module
* @param string table name
* @param string module
*/
public function insertIntoEntityTable($table_name, $module, $fileid = '') {
global $log, $app_strings, $adb;
$log->debug('> insertIntoEntityTable '.$table_name.','.$module);
global $adb, $current_user;
$insertion_mode = $this->mode;
//Checkin whether an entry is already is present in the vtiger_table to update
if ($insertion_mode == 'edit') {
$check_query = 'select * from ' . $table_name . ' where ' . $this->tab_name_index[$table_name] . '=?';
$check_result = $adb->pquery($check_query, array($this->id));
$num_rows = $adb->num_rows($check_result);
if ($num_rows <= 0) {
$insertion_mode = '';
}
}
// We will set the crypt_type based on the insertion_mode
$crypt_type = '';
if ($insertion_mode == 'edit') {
$update = '';
$update_params = array();
$tabid = getTabid($module);
$sql = 'select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3) and vtiger_field.presence in (0,2)';
$params = array($tabid, $table_name);
} else {
$column = $this->tab_name_index[$table_name];
if ($column == 'id' && $table_name == 'vtiger_users') {
$currentuser_id = $adb->getUniqueID('vtiger_users');
$this->id = $currentuser_id;
}
$qparams = array($this->id);
$tabid = getTabid($module);
$sql = 'select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,4,5) and vtiger_field.presence in (0,2)';
$params = array($tabid, $table_name);
$crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
}
$result = $adb->pquery($sql, $params);
$noofrows = $adb->num_rows($result);
for ($i = 0; $i < $noofrows; $i++) {
$fieldname = $adb->query_result($result, $i, 'fieldname');
$columname = $adb->query_result($result, $i, 'columnname');
$uitype = $adb->query_result($result, $i, 'uitype');
$typeofdata = $adb->query_result($result, $i, 'typeofdata');
$typeofdata_array = explode('~', $typeofdata);
$datatype = $typeofdata_array[0];
if (isset($this->column_fields[$fieldname])) {
if ($uitype == 56) {
if ($this->column_fields[$fieldname] === 'on' || $this->column_fields[$fieldname] == 1) {
$fldvalue = 1;
} else {
$fldvalue = 0;
}
} elseif ($uitype == 15) {
if ($this->column_fields[$fieldname] == $app_strings['LBL_NOT_ACCESSIBLE']) {
//If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
$sql = "select $columname from $table_name where " . $this->tab_name_index[$table_name] . '=?';
$res = $adb->pquery($sql, array($this->id));
$pick_val = $adb->query_result($res, 0, $columname);
$fldvalue = $pick_val;
} else {
$fldvalue = $this->column_fields[$fieldname];
}
} elseif ($uitype == 5 || $uitype == 6 || $uitype == 23) {
if (isset($current_user->date_format)) {
$fldvalue = getValidDBInsertDateValue($this->column_fields[$fieldname]);
} else {
$fldvalue = $this->column_fields[$fieldname];
}
} elseif ($uitype == 33) {
if (is_array($this->column_fields[$fieldname])) {
$field_list = implode(Field_Metadata::MULTIPICKLIST_SEPARATOR, $this->column_fields[$fieldname]);
} else {
$field_list = $this->column_fields[$fieldname];
}
$fldvalue = $field_list;
} elseif ($uitype == 99) {
$fldvalue = $this->encrypt_password($this->column_fields[$fieldname], $crypt_type);
} else {
$fldvalue = $this->column_fields[$fieldname];
$fldvalue = stripslashes($fldvalue);
}
} else {
$fldvalue = '';
}
if ($uitype == 31) {
$themeList = get_themes();
if (!in_array($fldvalue, $themeList) || $fldvalue == '') {
global $default_theme;
if (!empty($default_theme) && in_array($default_theme, $themeList)) {
$fldvalue = $default_theme;
} else {
$fldvalue = $themeList[0];
}
}
if ($current_user->id == $this->id) {
coreBOS_Session::set('vtiger_authenticated_user_theme', $fldvalue);
}
} elseif ($uitype == 32) {
$languageList = Vtiger_Language::getAll();
$languageList = array_keys($languageList);
if (!in_array($fldvalue, $languageList) || $fldvalue == '') {
global $default_language;
if (!empty($default_language) && in_array($default_language, $languageList)) {
$fldvalue = $default_language;
} else {
$fldvalue = $languageList[0];
}
}
if ($current_user->id == $this->id) {
coreBOS_Session::set('authenticated_user_language', $fldvalue);
}
}
if ($fldvalue == '') {
$fldvalue = $this->get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
}
if ($columname == 'is_admin' && !is_admin($current_user) && $insertion_mode == 'edit') {
// only admin users can change admin field > we force the same value that is currently set in database
$rs = $adb->pquery('select is_admin from vtiger_users where id=?', array($this->id));
$fldvalue = $adb->query_result($rs, 0, 0);
}
if ($insertion_mode == 'edit') {
if ($i == 0) {
$update = $columname . '=?';
} else {
$update .= ', ' . $columname . '=?';
}
$update_params[] = $fldvalue;
} else {
$column .= ', ' . $columname;
$qparams[] = $fldvalue;
}
}
if ($insertion_mode == 'edit') {
// If update is empty the the query fails
if (trim($update) != '') {
$sql1 = "update $table_name set $update where " . $this->tab_name_index[$table_name] . '=?';
$update_params[] = $this->id;
$adb->pquery($sql1, $update_params);
}
} else {
// Set the crypt_type being used, to override the DB default constraint as it is not in vtiger_field
if ($table_name == 'vtiger_users' && strpos('crypt_type', $column) === false) {
$column .= ', crypt_type';
$qparams[] = $crypt_type;
}
if ($table_name == 'vtiger_users') {
$sql1 = "insert into $table_name ($column, date_entered) values(" . generateQuestionMarks($qparams) . ',NOW())';
} else {
$sql1 = "insert into $table_name ($column) values(" . generateQuestionMarks($qparams) . ')';
}
$adb->pquery($sql1, $qparams);
}
}
/** Function to insert values into the attachment table
* @param integer entity id
* @param string module
*/
public function insertIntoAttachment($id, $module, $direct_import = false) {
global $log;
$log->debug("> insertIntoAttachment $id,$module");
foreach ($_FILES as $fileindex => $files) {
if ($files['name'] != '' && $files['size'] > 0) {
$files['original_name'] = vtlib_purify($_REQUEST[$fileindex . '_hidden']);
$this->uploadAndSaveFile($id, $module, $files);
}
}
$log->debug('< insertIntoAttachment');
}
/** Function to retrieve the user information of the given user ID which will be loaded into the $this->column_fields array
* @param integer record ID
* @param string module
*/
public function retrieve_entity_info($record, $module, $deleted = false, $from_wf = false, $throwexception = false) {
global $adb, $log;