This repository has been archived by the owner on Dec 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Sql.php
1658 lines (1404 loc) · 64.3 KB
/
Sql.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
/**
* Tine 2.0
*
* @package Tinebase
* @subpackage User
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @copyright Copyright (c) 2007-2019 Metaways Infosystems GmbH (http://www.metaways.de)
* @author Lars Kneschke <l.kneschke@metaways.de>
*
* @todo extend Tinebase_Application_Backend_Sql and replace some functions
*/
/**
* sql implementation of the SQL users interface
*
* @package Tinebase
* @subpackage User
*/
class Tinebase_User_Sql extends Tinebase_User_Abstract
{
use Tinebase_Controller_Record_ModlogTrait;
/**
* Model name
*
* @var string
*
* @todo perhaps we can remove that and build model name from name of the class (replace 'Controller' with 'Model')
*/
protected $_modelName = 'Tinebase_Model_FullUser';
/**
* row name mapping
*
* @var array
*/
protected $rowNameMapping = array(
'accountId' => 'id',
'accountDisplayName' => 'display_name',
'accountFullName' => 'full_name',
'accountFirstName' => 'first_name',
'accountLastName' => 'last_name',
'accountLoginName' => 'login_name',
'accountLastLogin' => 'last_login',
'accountLastLoginfrom' => 'last_login_from',
'accountLastPasswordChange' => 'last_password_change',
'password_must_change' => 'password_must_change',
'accountStatus' => 'status',
'accountExpires' => 'expires_at',
'accountPrimaryGroup' => 'primary_group_id',
'accountEmailAddress' => 'email',
'accountHomeDirectory' => 'home_dir',
'accountLoginShell' => 'login_shell',
'lastLoginFailure' => 'last_login_failure_at',
'loginFailures' => 'login_failures',
'openid' => 'openid',
'visibility' => 'visibility',
'contactId' => 'contact_id',
'xprops' => 'xprops',
'creation_time' => 'creation_time',
);
/**
* copy of Tinebase_Core::get('dbAdapter')
*
* @var Zend_Db_Adapter_Abstract
*/
protected $_db;
/**
* sql user plugins
*
* @var array
*/
protected $_sqlPlugins = array();
/**
* Table name without prefix
*
* @var string
*/
protected $_tableName = 'accounts';
/**
* @var Tinebase_Backend_Sql_Command_Interface
*/
protected $_dbCommand;
/**
* the constructor
*
* @param array $options Options used in connecting, binding, etc.
*/
public function __construct(array $_options = array())
{
parent::__construct($_options);
$this->_db = Tinebase_Core::getDb();
$this->_dbCommand = Tinebase_Backend_Sql_Command::factory($this->_db);
}
/**
* registerPlugin
*
* @param Tinebase_User_Plugin_Interface $plugin
*/
public function registerPlugin(Tinebase_User_Plugin_Interface $plugin)
{
parent::registerPlugin($plugin);
if ($plugin instanceof Tinebase_User_Plugin_SqlInterface) {
$className = get_class($plugin);
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
. " Registering " . $className . ' SQL plugin.');
$this->_sqlPlugins[$className] = $plugin;
}
}
public function removePlugin($plugin)
{
$result = parent::removePlugin($plugin);
$className = is_object($plugin) ? get_class($plugin) : $plugin;
if (isset($this->_sqlPlugins[$className]) && $this->_sqlPlugins[$className] instanceof Tinebase_User_Plugin_SqlInterface) {
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
. " Removing " . $className . ' SQL plugin.');
$result = $this->_sqlPlugins[$className];
unset($this->_sqlPlugins[$className]);
}
return $result;
}
/**
* @param $classname
* @return Tinebase_User_Plugin_SqlInterface
*/
public function getSqlPlugin($classname)
{
return $this->_sqlPlugins[$classname];
}
/**
* @return array
*/
public function getSqlPluginNames()
{
return array_keys($this->_sqlPlugins);
}
/**
* unregisterAllPlugins
*/
public function unregisterAllPlugins()
{
parent::unregisterAllPlugins();
$this->_sqlPlugins = array();
}
/**
* get list of users
*
* @param string $_filter
* @param string $_sort
* @param string $_dir
* @param int $_start
* @param int $_limit
* @param string $_accountClass the type of subclass for the Tinebase_Record_RecordSet to return
* @return Tinebase_Record_RecordSet with record class Tinebase_Model_User
*/
public function getUsers($_filter = NULL, $_sort = NULL, $_dir = 'ASC', $_start = NULL, $_limit = NULL, $_accountClass = 'Tinebase_Model_User')
{
$select = $this->_getUserSelectObject()
->limit($_limit, $_start);
if ($_sort !== NULL && isset($this->rowNameMapping[$_sort])) {
$select->order($this->_db->table_prefix . $this->_tableName . '.' . $this->rowNameMapping[$_sort] . ' ' . $_dir);
}
if (!empty($_filter)) {
$whereStatement = array();
$defaultValues = array(
$this->rowNameMapping['accountLastName'],
$this->rowNameMapping['accountFirstName'],
$this->rowNameMapping['accountLoginName']
);
// prepare for case insensitive search
foreach ($defaultValues as $defaultValue) {
$whereStatement[] = $this->_dbCommand->prepareForILike($this->_db->quoteIdentifier($defaultValue)) . ' LIKE ' . $this->_dbCommand->prepareForILike('?');
}
$select->where('(' . implode(' OR ', $whereStatement) . ')', '%' . $_filter . '%');
}
// @todo still needed?? either we use contacts from addressboook or full users now
// return only active users, when searching for simple users
if ($_accountClass == 'Tinebase_Model_User') {
$select->where($this->_db->quoteInto($this->_db->quoteIdentifier('status') . ' = ?', 'enabled'));
}
$select->where($this->_db->quoteIdentifier($this->_db->table_prefix . $this->_tableName . '.' . 'is_deleted') . ' = 0');
$stmt = $select->query();
$rows = $stmt->fetchAll(Zend_Db::FETCH_ASSOC);
$result = new Tinebase_Record_RecordSet($_accountClass, $rows, TRUE);
return $result;
}
/**
* get total count of users
*
* @param string $_filter
* @return int
*/
public function getUsersCount($_filter = null)
{
$select = $this->_db->select()
->from(SQL_TABLE_PREFIX . 'accounts', array('count' => 'COUNT(' . $this->_db->quoteIdentifier('id') . ')'));
if (!empty($_filter)) {
$whereStatement = array();
$defaultValues = array(
$this->rowNameMapping['accountLastName'],
$this->rowNameMapping['accountFirstName'],
$this->rowNameMapping['accountLoginName']
);
// prepare for case insensitive search
foreach ($defaultValues as $defaultValue) {
$whereStatement[] = $this->_dbCommand->prepareForILike($this->_db->quoteIdentifier($defaultValue)) . ' LIKE ' . $this->_dbCommand->prepareForILike('?');
}
$select->where('(' . implode(' OR ', $whereStatement) . ')', '%' . $_filter . '%');
}
$select->where($this->_db->table_prefix . $this->_tableName . '.' . $this->_db->quoteIdentifier('is_deleted') . ' = 0');
$stmt = $select->query();
$rows = $stmt->fetchAll(Zend_Db::FETCH_COLUMN);
return $rows[0];
}
/**
* get user by property
*
* @param string $_property the key to filter
* @param string $_value the value to search for
* @param string $_accountClass type of model to return
*
* @return Tinebase_Model_User the user object
*/
public function getUserByProperty($_property, $_value, $_accountClass = 'Tinebase_Model_User')
{
$user = $this->getUserByPropertyFromSqlBackend($_property, $_value, $_accountClass);
// append data from plugins
foreach ($this->_sqlPlugins as $plugin) {
try {
if ($plugin instanceof Tinebase_User_Plugin_LdapInterface) {
throw new Tinebase_Exception_InvalidArgument('LDAP plugin ' . get_class($plugin)
. ' should not be registered as sql plugin');
}
$this->_inspectCRUD($plugin, $user, null, 'inspectGetUserByProperty');
} catch (Tinebase_Exception_NotFound $tenf) {
// do nothing
} catch (Exception $e) {
if (Tinebase_Core::isLogLevel(Zend_Log::CRIT)) Tinebase_Core::getLogger()->crit(__METHOD__ . '::' . __LINE__
. ' User sql plugin "' . get_class($plugin) . '" failure');
Tinebase_Exception::log($e);
}
}
if ($this instanceof Tinebase_User_Interface_SyncAble) {
try {
$syncUser = $this->getUserByPropertyFromSyncBackend('accountId', $user, $_accountClass);
if (!empty($syncUser->emailUser)) {
$user->emailUser = $syncUser->emailUser;
}
if (!empty($syncUser->imapUser)) {
$user->imapUser = $syncUser->imapUser;
}
if (!empty($syncUser->smtpUser)) {
$user->smtpUser = $syncUser->smtpUser;
}
if (!empty($syncUser->sambaSAM)) {
$user->sambaSAM = $syncUser->sambaSAM;
}
} catch (Tinebase_Exception_NotFound $tenf) {
if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) Tinebase_Core::getLogger()->warn(
__METHOD__ . '::' . __LINE__ . ' user not found in sync backend: ' . $user->getId());
}
}
if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($user->toArray(), true));
return $user;
}
/**
* get user by property
*
* @param string $_property the key to filter
* @param string $_value the value to search for
* @param string $_accountClass type of model to return
*
* @return Tinebase_Model_User|Tinebase_Model_FullUser the user object
* @throws Tinebase_Exception_NotFound
* @throws Tinebase_Exception_Record_Validation
* @throws Tinebase_Exception_InvalidArgument
*/
public function getUserByPropertyFromSqlBackend($_property, $_value, $_accountClass = 'Tinebase_Model_User')
{
if(!(isset($this->rowNameMapping[$_property]) || array_key_exists($_property, $this->rowNameMapping))) {
throw new Tinebase_Exception_InvalidArgument("invalid property $_property requested");
}
switch($_property) {
case 'accountId':
$value = Tinebase_Model_User::convertUserIdToInt($_value);
break;
default:
$value = $_value;
break;
}
$select = $this->_getUserSelectObject()
->where($this->_db->quoteInto($this->_db->quoteIdentifier( SQL_TABLE_PREFIX . 'accounts.' . $this->rowNameMapping[$_property]) . ' = ?', $value));
if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $select);
$stmt = $select->query();
$row = $stmt->fetch(Zend_Db::FETCH_ASSOC);
if ($row === false) {
throw new Tinebase_Exception_NotFound('User with ' . $_property . ' = ' . $value . ' not found.');
}
if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($row, true));
try {
$account = new $_accountClass(NULL, TRUE);
$account->setFromArray($row);
} catch (Tinebase_Exception_Record_Validation $e) {
$validation_errors = $account->getValidationErrors();
Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' ' . $e->getMessage() . "\n" .
"Tinebase_Model_User::validation_errors: \n" .
print_r($validation_errors,true));
throw ($e);
}
return $account;
}
/**
* get users by primary group
*
* @param string $groupId
* @return Tinebase_Record_RecordSet of Tinebase_Model_FullUser
*/
public function getUsersByPrimaryGroup($groupId)
{
$select = $this->_getUserSelectObject()
->where($this->_db->quoteInto($this->_db->quoteIdentifier(SQL_TABLE_PREFIX . 'accounts.primary_group_id') . ' = ?', $groupId));
$stmt = $select->query();
$data = (array) $stmt->fetchAll(Zend_Db::FETCH_ASSOC);
$result = new Tinebase_Record_RecordSet('Tinebase_Model_FullUser', $data, true);
return $result;
}
/**
* get full user by id
*
* @param int $_accountId
* @return Tinebase_Model_FullUser full user
*/
public function getFullUserById($_accountId)
{
return $this->getUserById($_accountId, 'Tinebase_Model_FullUser');
}
/**
* get user select
*
* @return Zend_Db_Select
*/
protected function _getUserSelectObject()
{
$interval = $this->_dbCommand->getDynamicInterval(
'SECOND',
'1',
'CASE WHEN ' . $this->_db->quoteIdentifier($this->rowNameMapping['loginFailures'])
. ' > 5 THEN 60 ELSE POWER(2, ' . $this->_db->quoteIdentifier($this->rowNameMapping['loginFailures']) . ') END');
$statusSQL = 'CASE WHEN ' . $this->_db->quoteIdentifier($this->rowNameMapping['accountStatus']) . ' = ' . $this->_db->quote('enabled') . ' THEN ('
. 'CASE WHEN '.$this->_dbCommand->setDate('NOW()') .' > ' . $this->_db->quoteIdentifier($this->rowNameMapping['accountExpires'])
. ' THEN ' . $this->_db->quote('expired')
. ' WHEN ( ' . $this->_db->quoteIdentifier($this->rowNameMapping['loginFailures']) . ' > 0 AND '
. $this->_db->quoteIdentifier($this->rowNameMapping['lastLoginFailure']) . ' + ' . $interval . ' > NOW()) THEN ' . $this->_db->quote('blocked')
. ' ELSE ' . $this->_db->quote('enabled') . ' END)'
. ' WHEN ' . $this->_db->quoteIdentifier($this->rowNameMapping['accountStatus']) . ' = ' . $this->_db->quote('expired')
. ' THEN ' . $this->_db->quote('expired')
. ' ELSE ' . $this->_db->quote('disabled') . ' END';
$fields = array(
'accountId' => $this->rowNameMapping['accountId'],
'accountLoginName' => $this->rowNameMapping['accountLoginName'],
'accountLastLogin' => $this->rowNameMapping['accountLastLogin'],
'accountLastLoginfrom' => $this->rowNameMapping['accountLastLoginfrom'],
'accountLastPasswordChange' => $this->rowNameMapping['accountLastPasswordChange'],
'password_must_change' => $this->rowNameMapping['password_must_change'],
'accountStatus' => $statusSQL,
'accountExpires' => $this->rowNameMapping['accountExpires'],
'accountPrimaryGroup' => $this->rowNameMapping['accountPrimaryGroup'],
'accountHomeDirectory' => $this->rowNameMapping['accountHomeDirectory'],
'accountLoginShell' => $this->rowNameMapping['accountLoginShell'],
'accountDisplayName' => $this->rowNameMapping['accountDisplayName'],
'accountFullName' => $this->rowNameMapping['accountFullName'],
'accountFirstName' => $this->rowNameMapping['accountFirstName'],
'accountLastName' => $this->rowNameMapping['accountLastName'],
'accountEmailAddress' => $this->rowNameMapping['accountEmailAddress'],
'lastLoginFailure' => $this->rowNameMapping['lastLoginFailure'],
'loginFailures' => $this->rowNameMapping['loginFailures'],
'contact_id',
'openid',
'visibility',
'NOW()', // only needed for debugging
);
// modlog fields have been added later
if ($this->_userTableHasModlogFields()) {
$fields = array_merge($fields, array(
'created_by',
'creation_time',
'last_modified_by',
'last_modified_time',
'is_deleted',
'deleted_time',
'deleted_by',
'seq',
));
}
// remove this in 2018.11 as an upgrade to 2017.11 creates the field
if ($this->_userHasXpropsField()) {
$fields[] = 'xprops';
}
$schema = Tinebase_Db_Table::getTableDescriptionFromCache($this->_db->table_prefix . $this->_tableName, $this->_db);
foreach ($fields as $index => $field) {
// status contains $statusSQL
if (! isset($schema[$field]) && $index !== 'accountStatus') {
unset($fields[$index]);
}
}
$select = $this->_db->select()
->from(SQL_TABLE_PREFIX . 'accounts', $fields)
->joinLeft(
SQL_TABLE_PREFIX . 'addressbook',
$this->_db->quoteIdentifier(SQL_TABLE_PREFIX . 'accounts.contact_id') . ' = '
. $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . 'addressbook.id'),
array(
'container_id' => 'container_id'
)
);
return $select;
}
/**
* set the password for given account
*
* @param string $_userId
* @param string $_password
* @param bool $_encrypt encrypt password
* @param bool $_mustChange
* @throws Tinebase_Exception_NotFound
*/
public function setPassword($_userId, $_password, $_encrypt = TRUE, $_mustChange = null)
{
$userId = $_userId instanceof Tinebase_Model_User ? $_userId->getId() : $_userId;
$user = $_userId instanceof Tinebase_Model_FullUser ? $_userId : $this->getFullUserById($userId);
$this->checkPasswordPolicy($_password, $user);
$accountData = $this->_updatePasswordProperty($userId, $_password, 'password', $_encrypt, $_mustChange);
$this->_setPluginsPassword($user, $_password, $_encrypt);
$accountData['id'] = $userId;
$oldPassword = new Tinebase_Model_UserPassword(array('id' => $userId), true);
$newPassword = new Tinebase_Model_UserPassword($accountData, true);
$this->_writeModLog($newPassword, $oldPassword);
}
/**
* @param $_userId
* @param $_password
* @param string $_property
* @param boolean $_encrypt
* @param boolean|null $_mustChange user needs to change pw next time
* @return array $accountData
* @throws Tinebase_Exception_NotFound
*/
protected function _updatePasswordProperty($_userId, $_password, $_property = 'password', $_encrypt = true, $_mustChange = null)
{
$accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . $this->_tableName));
$accountData = array();
$accountData[$_property] = ($_encrypt) ? Hash_Password::generate('SSHA256', $_password) : $_password;
if ($_property === 'password') {
if (Tinebase_Auth_NtlmV2::isEnabled()) {
$accountData['ntlmv2hash'] = Tinebase_Auth_CredentialCache::encryptData(
Tinebase_Auth_NtlmV2::getPwdHash($_password),
Tinebase_Config::getInstance()->{Tinebase_Config::PASSWORD_NTLMV2_ENCRYPTION_KEY});
}
$accountData['last_password_change'] = Tinebase_DateTime::now()->get(Tinebase_Record_Abstract::ISO8601LONG);
$accountData['password_must_change'] = $_mustChange ? 1 : 0;
}
$where = array(
$accountsTable->getAdapter()->quoteInto($accountsTable->getAdapter()->quoteIdentifier('id') . ' = ?', $_userId)
);
$result = $accountsTable->update($accountData, $where);
if ($result != 1) {
throw new Tinebase_Exception_NotFound('Unable to update password! account not found in authentication backend.');
}
return $accountData;
}
public function updateNtlmV2Hash($_userId, $_password)
{
if (Tinebase_Auth_NtlmV2::isEnabled()) {
$accountData = ['ntlmv2hash' => Tinebase_Auth_CredentialCache::encryptData(
Tinebase_Auth_NtlmV2::getPwdHash($_password),
Tinebase_Config::getInstance()->{Tinebase_Config::PASSWORD_NTLMV2_ENCRYPTION_KEY})];
$accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . $this->_tableName));
$where = array(
$accountsTable->getAdapter()->quoteInto($accountsTable->getAdapter()->quoteIdentifier('id') . ' = ?', $_userId)
);
$result = $accountsTable->update($accountData, $where);
if ($result != 1) {
if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) Tinebase_Core::getLogger()->warn(__METHOD__ . '::'
. __LINE__ . ' update did not work!');
}
}
}
/**
* set password in plugins
*
* @param Tinebase_Model_User $user
* @param string $password
* @param bool $encrypt encrypt password
* @throws Tinebase_Exception_Backend
*/
protected function _setPluginsPassword(Tinebase_Model_User $user, $password, $encrypt = TRUE)
{
foreach ($this->_sqlPlugins as $plugin) {
try {
$userId = $this->_getPluginUserId($plugin, $user);
$plugin->inspectSetPassword($userId, $password, $encrypt);
} catch (Exception $e) {
Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' Could not change plugin password: ' . $e);
throw new Tinebase_Exception_Backend($e->getMessage());
}
}
}
/**
* @param object $plugin
* @param object $user
* @return string
*/
protected function _getPluginUserId($plugin, $user)
{
return Tinebase_EmailUser::isEmailUserPlugin($plugin) && Tinebase_Config::getInstance()->{Tinebase_Config::EMAIL_USER_ID_IN_XPROPS}
? $user->getEmailUserId()
: $user->getId();
}
/**
* ensure password policy
*
* @param string $password
* @param Tinebase_Model_FullUser $user
* @throws Tinebase_Exception_PasswordPolicyViolation
*/
public function checkPasswordPolicy($password, Tinebase_Model_FullUser $user)
{
if (! Tinebase_Config::getInstance()->get(Tinebase_Config::USER_PASSWORD_POLICY)->{Tinebase_Config::PASSWORD_POLICY_ACTIVE}) {
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
. ' No password policy enabled');
return;
}
$policy = array(
Tinebase_Config::PASSWORD_POLICY_ONLYASCII => '/[^\x00-\x7F]/',
Tinebase_Config::PASSWORD_POLICY_MIN_LENGTH => null,
Tinebase_Config::PASSWORD_POLICY_MIN_WORD_CHARS => '/[\W]*/',
Tinebase_Config::PASSWORD_POLICY_MIN_UPPERCASE_CHARS => '/[^A-Z]*/',
Tinebase_Config::PASSWORD_POLICY_MIN_SPECIAL_CHARS => '/[\w]*/',
Tinebase_Config::PASSWORD_POLICY_MIN_NUMBERS => '/[^0-9]*/',
Tinebase_Config::PASSWORD_POLICY_FORBID_USERNAME => $user->accountLoginName,
);
$failedTests = array();
foreach ($policy as $key => $regex) {
$result = $this->_testPolicy($password, $key, $regex);
if ($result !== true) {
$failedTests[$key] = $result;
}
}
if (! empty($failedTests)) {
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
. ' ' . print_r($failedTests, true));
$translation = Tinebase_Translation::getTranslation();
$msg = $translation->_('Password failed to match the following policy requirements: ');
foreach($failedTests as $key => $result) {
$msg .= "\n- " . $result;
}
throw new Tinebase_Exception_PasswordPolicyViolation($msg);
}
}
/**
* test password policy
*
* @param string $password
* @param string $configKey
* @param string $regex
* @return mixed
*/
protected function _testPolicy($password, $configKey, $regex = null)
{
$result = true;
$configValue = Tinebase_Config::getInstance()->get(Tinebase_Config::USER_PASSWORD_POLICY)->{$configKey};
$translation = Tinebase_Translation::getTranslation();
$configDefinition = Tinebase_Config::getInstance()->getDefinition(Tinebase_Config::USER_PASSWORD_POLICY);
$description = $translation->translate($configDefinition['content'][$configKey]['description']);
$description = preg_replace("/\.$/", "", $description);
switch ($configKey) {
case Tinebase_Config::PASSWORD_POLICY_ONLYASCII:
if ($configValue && $regex !== null) {
$nonAsciiFound = preg_match($regex, $password, $matches);
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(
__METHOD__ . '::' . __LINE__ . ' ' . print_r($matches, true));
$result = ($nonAsciiFound) ? $description : true;
}
break;
case Tinebase_Config::PASSWORD_POLICY_FORBID_USERNAME:
if ($configValue) {
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(
__METHOD__ . '::' . __LINE__ . ' Testing if password is part of username "' . $regex . '"');
if (! empty($password)) {
$result = preg_match('/' . preg_quote($password, '/') . '/i', $regex) ?
$description :
true;
}
}
break;
default:
// check min length restriction
$minLength = $configValue;
if ($minLength > 0) {
$reduced = ($regex) ? preg_replace($regex, '', $password) : $password;
$charCount = strlen(utf8_decode($reduced));
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
. ' Found ' . $charCount . '/' . $minLength . ' chars for ' . $configKey /*. ': ' . $reduced */);
if ($charCount < $minLength) {
$result = $description . ': ' . $minLength;
}
}
break;
}
return $result;
}
/**
* set the status of the user
*
* @param mixed $_accountId
* @param string $_status
* @return integer
* @throws Tinebase_Exception_InvalidArgument
*/
public function setStatus($_accountId, $_status)
{
if ($this instanceof Tinebase_User_Interface_SyncAble) {
$this->setStatusInSyncBackend($_accountId, $_status);
}
$accountId = Tinebase_Model_User::convertUserIdToInt($_accountId);
switch($_status) {
case Tinebase_Model_User::ACCOUNT_STATUS_ENABLED:
$accountData[$this->rowNameMapping['loginFailures']] = 0;
$accountData[$this->rowNameMapping['accountExpires']] = null;
$accountData['status'] = $_status;
break;
case Tinebase_Model_User::ACCOUNT_STATUS_DISABLED:
$accountData['status'] = $_status;
break;
case Tinebase_Model_User::ACCOUNT_STATUS_EXPIRED:
$expiryDate = Tinebase_DateTime::now()->subSecond(1);
$accountData['expires_at'] = $expiryDate->toString();
if ($this instanceof Tinebase_User_Interface_SyncAble) {
$this->setExpiryDateInSyncBackend($_accountId, $expiryDate);
}
break;
default:
throw new Tinebase_Exception_InvalidArgument('$_status can be only enabled, disabled or expired');
break;
}
$accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'accounts'));
$where = array(
$this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $accountId)
);
if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->INFO(__METHOD__ . ' ' . __LINE__
. ' ' . $_status . ' user with id ' . $accountId);
$result = $accountsTable->update($accountData, $where);
$oldUser = new Tinebase_Model_FullUser(array('accountId' => $accountId), true);
$newUser = new Tinebase_Model_FullUser(array('accountId' => $accountId, 'accountStatus' => $_status), true);
$this->_writeModLog($newUser, $oldUser);
return $result;
}
/**
* sets/unsets expiry date
*
* @param mixed $_accountId
* @param Tinebase_DateTime $_expiryDate set to NULL to disable expirydate
*/
public function setExpiryDate($_accountId, $_expiryDate)
{
if ($this instanceof Tinebase_User_Interface_SyncAble) {
$this->setExpiryDateInSyncBackend($_accountId, $_expiryDate);
}
$accountId = Tinebase_Model_User::convertUserIdToInt($_accountId);
if($_expiryDate instanceof DateTime) {
$accountData['expires_at'] = $_expiryDate->get(Tinebase_Record_Abstract::ISO8601LONG);
} else {
$accountData['expires_at'] = NULL;
}
$accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'accounts'));
$where = array(
$this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $accountId)
);
$result = $accountsTable->update($accountData, $where);
$oldUser = new Tinebase_Model_FullUser(array('accountId' => $accountId), true);
$newUser = new Tinebase_Model_FullUser(array('accountId' => $accountId, 'accountExpires' => $accountData['expires_at']), true);
$this->_writeModLog($newUser, $oldUser);
return $result;
}
/**
* set last login failure in accounts table
*
* @param string $_loginName
* @return Tinebase_Model_FullUser|null user if found
* @see Tinebase/User/Tinebase_User_Interface::setLastLoginFailure()
*/
public function setLastLoginFailure($_loginName)
{
try {
$user = $this->getUserByPropertyFromSqlBackend('accountLoginName', $_loginName, 'Tinebase_Model_FullUser');
} catch (Tinebase_Exception_NotFound $tenf) {
// nothing todo => is no existing user
return null;
}
$values = array(
'last_login_failure_at' => Tinebase_DateTime::now()->get(Tinebase_Record_Abstract::ISO8601LONG),
'login_failures' => new Zend_Db_Expr($this->_db->quoteIdentifier('login_failures') . ' + 1')
);
$where = array(
$this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $user->getId())
);
$this->_db->update(SQL_TABLE_PREFIX . 'accounts', $values, $where);
return $user;
}
/**
* update the lastlogin time of user
*
* @param int $_accountId
* @param string $_ipAddress
* @return integer
*/
public function setLoginTime($_accountId, $_ipAddress)
{
$accountId = Tinebase_Model_User::convertUserIdToInt($_accountId);
$accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'accounts'));
$accountData['last_login_from'] = $_ipAddress;
$accountData['last_login'] = Tinebase_DateTime::now()->get(Tinebase_Record_Abstract::ISO8601LONG);
$accountData['login_failures'] = 0;
$where = array(
$this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $accountId)
);
$result = $accountsTable->update($accountData, $where);
return $result;
}
/**
* update contact data(first name, last name, ...) of user
*
* @param Addressbook_Model_Contact $contact
*/
public function updateContact(Addressbook_Model_Contact $_contact)
{
if ($this instanceof Tinebase_User_Interface_SyncAble) {
$this->updateContactInSyncBackend($_contact);
}
return $this->updateContactInSqlBackend($_contact);
}
/**
* update contact data(first name, last name, ...) of user in local sql storage
*
* @param Addressbook_Model_Contact $_contact
* @return integer
* @throws Exception
* @throws Tinebase_Exception_SystemGeneric
*/
public function updateContactInSqlBackend(Addressbook_Model_Contact $_contact)
{
$contactId = $_contact->getId();
// prevent changing of email if it does not match configured domains
Tinebase_EmailUser::checkDomain($_contact->email, true);
$oldUser = $this->getUserByProperty('contactId', $contactId, 'Tinebase_Model_FullUser');
$accountData = array(
$this->rowNameMapping['accountDisplayName'] => $_contact->n_fileas,
$this->rowNameMapping['accountFullName'] => $_contact->n_fn,
$this->rowNameMapping['accountFirstName'] => $_contact->n_given,
$this->rowNameMapping['accountLastName'] => $_contact->n_family,
$this->rowNameMapping['accountEmailAddress'] => $_contact->email
);
try {
$accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'accounts'));
$where = array(
$this->_db->quoteInto($this->_db->quoteIdentifier('contact_id') . ' = ?', $contactId)
);
$result = $accountsTable->update($accountData, $where);
$newUser = $this->getUserByPropertyFromSqlBackend('contactId', $contactId, 'Tinebase_Model_FullUser');
$this->_writeModLog($newUser, $oldUser);
return $result;
} catch (Exception $e) {
Tinebase_TransactionManager::getInstance()->rollBack();
throw($e);
}
}
/**
* updates an user
*
* this function updates an user
*
* @param Tinebase_Model_FullUser $_user
* @return Tinebase_Model_FullUser
*/
public function updateUser(Tinebase_Model_FullUser $_user)
{
$visibility = $_user->visibility;
if ($this instanceof Tinebase_User_Interface_SyncAble) {
$this->updateUserInSyncBackend($_user);
}
$updatedUser = $this->updateUserInSqlBackend($_user);
$this->updatePluginUser($updatedUser, $_user);
$contactId = $updatedUser->contact_id;
if (!empty($visibility) && !empty($contactId) && $visibility != $updatedUser->visibility) {
$updatedUser->visibility = $visibility;
$updatedUser = $this->updateUserInSqlBackend($updatedUser);
$this->updatePluginUser($updatedUser, $_user);
}
if ($updatedUser->xprops() != $_user->xprops()) {
// update user xprops if necessary (plugin user with xprops might have been updated)
$updatedUser = $this->updateUserInSqlBackend($updatedUser);
}
return $updatedUser;
}
/**
* update data in plugins
*
* @param Tinebase_Model_FullUser $updatedUser
* @param Tinebase_Model_FullUser $newUserProperties
* @param boolean $skipEmailPlugins
*/
public function updatePluginUser($updatedUser, $newUserProperties, $skipEmailPlugins = false)
{
foreach ($this->_sqlPlugins as $plugin) {
if (! $skipEmailPlugins || ! Tinebase_EmailUser::isEmailUserPlugin($plugin)) {
$this->_inspectCRUD($plugin, $updatedUser, $newUserProperties, 'update');
}
}
}
/**
* @param $plugin
* @param $user
* @param $newUserProperties
* @param $method
*
* TODO support different imap/smtp xprops
*/
protected function _inspectCRUD($plugin, $user, $newUserProperties, $method)
{
if ($method !== 'inspectGetUserByProperty') {
$method = 'inspect' . ucfirst($method) . 'User';
}
// add email user xprops here if configured
if (Tinebase_EmailUser::isEmailUserPlugin($plugin) && Tinebase_Config::getInstance()->{Tinebase_Config::EMAIL_USER_ID_IN_XPROPS}) {
if ($method === 'inspectAddUser' && empty($user->accountEmailAddress)) {
// do not add plugin user if user has no email adress
return;
}
$pluginUser = clone($user);
Tinebase_EmailUser_XpropsFacade::setIdFromXprops($user, $pluginUser, $method !== 'inspectGetUserByProperty');
if ($newUserProperties) {
$updatePluginUser = clone($newUserProperties);
Tinebase_EmailUser_XpropsFacade::setIdFromXprops($user, $updatePluginUser);
$params = [$pluginUser, $updatePluginUser];
} else {
$params = [$pluginUser];
$updatePluginUser = null;
}
call_user_func_array([$plugin, $method], $params);
// return email user properties to $user