-
Notifications
You must be signed in to change notification settings - Fork 4
/
User.php
1244 lines (1059 loc) · 38.7 KB
/
User.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
namespace Sunlight;
use Kuria\Url\Url;
use Sunlight\Post\Post;
use Sunlight\Database\Database as DB;
use Sunlight\Image\ImageException;
use Sunlight\Image\ImageLoader;
use Sunlight\Image\ImageService;
use Sunlight\Image\ImageStorage;
use Sunlight\Image\ImageTransformer;
use Sunlight\Util\Arr;
use Sunlight\Util\Cookie;
use Sunlight\Util\Filesystem;
use Sunlight\Util\Form;
use Sunlight\Util\Html;
use Sunlight\Util\HtmlFilter;
use Sunlight\Util\Password;
use Sunlight\Util\Request;
use Sunlight\Util\StringGenerator;
use Sunlight\Util\StringHelper;
abstract class User
{
/** Max possible user level */
const MAX_LEVEL = 10001;
/** Max assignable user level */
const MAX_ASSIGNABLE_LEVEL = 9999;
/** Admin group ID */
const ADMIN_GROUP_ID = 1;
/** Guest group ID (anonymous users) */
const GUEST_GROUP_ID = 2;
/** Default registered user group ID */
const REGISTERED_GROUP_ID = 3;
/** Cookie name - persistent login key */
const COOKIE_PERSISTENT_LOGIN = 'sl_persistent_login';
/** Auth hash type - remember me */
const AUTH_PERSISTENT_LOGIN = 'persistent_login';
/** Auth hash type - session */
const AUTH_SESSION = 'session';
/** Auth hash type - mass email management */
const AUTH_MASSEMAIL = 'massemail';
/** Auth hash type - password reset */
const AUTH_PASSWORD_RESET = 'password_reset';
/** Auth hash type - email change */
const AUTH_EMAIL_CHANGE = 'email_change';
/** Login status - wrong username or password */
const LOGIN_FAILURE = 0;
/** Login status - successful */
const LOGIN_SUCCESS = 1;
/** Login status - user or group is blocked */
const LOGIN_BLOCKED = 2;
/** Login status - user account removed */
const LOGIN_REMOVED = 3;
/** Login status - attempt limit exceeded */
const LOGIN_ATTEMPTS_EXCEEDED = 4;
/** Login status - XSRF failure */
const LOGIN_XSRF_FAILURE = 5;
/** @var bool */
private static $initialized = false;
/** @var array */
private static $privilegeMap = [
'administration' => true,
'adminsettings' => true,
'adminplugins' => true,
'adminusers' => true,
'admingroups' => true,
'admincontent' => true,
'adminother' => true,
'adminpages' => true,
'adminsection' => true,
'admincategory' => true,
'adminbook' => true,
'adminseparator' => true,
'admingallery' => true,
'adminlink' => true,
'admingroup' => true,
'adminforum' => true,
'adminpluginpage' => true,
'adminart' => true,
'adminallart' => true,
'adminchangeartauthor' => true,
'adminpoll' => true,
'adminpollall' => true,
'adminsbox' => true,
'adminbox' => true,
'adminconfirm' => true,
'adminautoconfirm' => true,
'fileaccess' => true,
'fileglobalaccess' => true,
'fileadminaccess' => true,
'adminhcmphp' => true,
'adminbackup' => true,
'adminmassemail' => true,
'adminposts' => true,
'changeusername' => true,
'unlimitedpostaccess' => true,
'locktopics' => true,
'stickytopics' => true,
'movetopics' => true,
'postcomments' => true,
'artrate' => true,
'pollvote' => true,
'selfremove' => true,
'rawhtml' => true,
];
/** @var array|null data from user table (if logged in) */
static $data;
/** @var array data from group table */
static $group;
static function init(): void
{
if (self::$initialized) {
throw new \LogicException('Already initialized');
}
Extend::call('user.privileges', ['privileges' => &self::$privilegeMap]);
self::authenticate();
self::$initialized = true;
}
static function getPrivilegeMap(): array
{
return self::$privilegeMap;
}
private static function authenticate(): void
{
$success = false;
$isPersistentLogin = false;
$errorCode = null;
$userData = null;
do {
$loginDataExist = isset($_SESSION['user_id'], $_SESSION['user_auth']);
// check persistent login cookie if there are no login data
if (!$loginDataExist) {
// check cookie existence
if (Cookie::exists(self::COOKIE_PERSISTENT_LOGIN)) {
// cookie auth process
do {
// parse cookie
$cookie = explode('$', Cookie::get(self::COOKIE_PERSISTENT_LOGIN), 2);
if (count($cookie) !== 2) {
// invalid cookie format
$errorCode = 1;
break;
}
$cookie = [
'id' => (int) $cookie[0],
'hash' => $cookie[1],
];
// fetch user data
$userData = DB::queryRow('SELECT * FROM ' . DB::table('user') . ' WHERE id=' . DB::val($cookie['id']));
if ($userData === false) {
// user not found
$errorCode = 2;
break;
}
// check failed login attempt limit
if (!IpLog::check(IpLog::FAILED_LOGIN_ATTEMPT)) {
// limit exceeded
$errorCode = 3;
break;
}
$validHash = self::getAuthHash(self::AUTH_PERSISTENT_LOGIN, $userData['email'], $userData['password']);
if (!hash_equals($validHash, $cookie['hash'])) {
// invalid hash
IpLog::update(IpLog::FAILED_LOGIN_ATTEMPT);
$errorCode = 4;
break;
}
// all is well! use cookie data to login the user
self::login($cookie['id'], $userData['password'], $userData['email']);
$loginDataExist = true;
$isPersistentLogin = true;
} while (false);
// check result
if ($errorCode !== null) {
// cookie authorization has failed, remove the cookie
Cookie::remove(self::COOKIE_PERSISTENT_LOGIN);
break;
}
}
}
// check whether login data exist
if (!$loginDataExist) {
// no login data - user is not logged in
$errorCode = 5;
break;
}
// fetch user data
if (!$userData) {
$userData = DB::queryRow('SELECT * FROM ' . DB::table('user') . ' WHERE id=' . DB::val($_SESSION['user_id']));
if ($userData === false) {
// user not found
$errorCode = 6;
break;
}
}
// check user authentication hash
if ($_SESSION['user_auth'] !== self::getAuthHash(self::AUTH_SESSION, $userData['email'], $userData['password'])) {
// invalid hash
$errorCode = 7;
break;
}
// check user account's status
if ($userData['blocked']) {
// account is blocked
$errorCode = 8;
break;
}
// fetch group data
$groupData = DB::queryRow('SELECT * FROM ' . DB::table('user_group') . ' WHERE id=' . DB::val($userData['group_id']));
if ($groupData === false) {
// group data not found
$errorCode = 9;
break;
}
// check group status
if ($groupData['blocked']) {
// group is blocked
$errorCode = 10;
break;
}
// all is well! user is authenticated
$success = true;
} while (false);
// process login
if ($success) {
// increase level for superusers
if ($userData['levelshift']) {
++$groupData['level'];
}
// record activity time (max once per 30 seconds)
if (time() - $userData['activitytime'] > 30) {
DB::update('user', 'id=' . DB::val($userData['id']), [
'activitytime' => time(),
'ip' => Core::getClientIp(),
]);
}
// event
Extend::call('user.auth.success', [
'user' => &$userData,
'group' => &$groupData,
'persistent' => $isPersistentLogin,
]);
// set variables
self::$data = $userData;
self::$group = $groupData;
} else {
// guest
$groupData = DB::queryRow('SELECT * FROM ' . DB::table('user_group') . ' WHERE id=' . self::GUEST_GROUP_ID);
if ($groupData === false) {
throw new \RuntimeException(sprintf('Anonymous user group was not found (id=%s)', self::GUEST_GROUP_ID));
}
// event
Extend::call('user.auth.failure', ['error_code' => $errorCode]);
// log
if ($errorCode !== 5) {
Logger::debug('user', 'User auth failure', [
'error_code' => $errorCode,
'user_id' => is_array($userData) ? $userData['id'] : null,
]);
}
self::$group = $groupData;
}
}
static function isLoggedIn(): bool
{
return self::$data !== null;
}
static function getId(): int
{
return self::$data['id'] ?? -1;
}
/**
* See if user ID matches the current user
*/
static function equals(int $targetUserId): bool
{
return $targetUserId == self::getId();
}
/**
* Get user's privilege level
*/
static function getLevel(): int
{
return self::$group['level'];
}
/**
* See if a privilege has been granted
*/
static function hasPrivilege(string $name): bool
{
return isset(self::$privilegeMap[$name]) && self::$group[$name];
}
static function isSuperAdmin(): bool
{
return self::isLoggedIn() && self::$data['levelshift'] && self::$group['id'] == self::ADMIN_GROUP_ID;
}
/**
* Verify user's password
*/
static function checkPassword(string $plainPassword): bool
{
if (self::isLoggedIn()) {
return Password::load(self::$data['password'])->match($plainPassword);
}
return false;
}
/**
* See if the user can access another's content
*/
static function checkLevel(int $targetUserId, int $targetUserLevel): bool
{
return self::isLoggedIn() && (self::getLevel() > $targetUserLevel || self::equals($targetUserId));
}
/**
* See if the user can access content which may not be public or may require some privilege level
*
* @param bool $public content is public 1/0
* @param int|null $level minimal required level
*/
static function checkPublicAccess(bool $public, ?int $level = null): bool
{
return (self::isLoggedIn() || $public) && ($level === null || self::getLevel() >= $level);
}
/**
* Get user's home directory
*
* The directory may not exist!
*
* @param bool $getTopmost get topmost possible directory 1/0
* @throws \RuntimeException if user has no filesystem access
*/
static function getHomeDir(bool $getTopmost = false): string
{
if (!self::hasPrivilege('fileaccess')) {
throw new \RuntimeException('User has no filesystem access');
}
if (self::hasPrivilege('fileglobalaccess')) {
if ($getTopmost && self::hasPrivilege('fileadminaccess')) {
$homeDir = SL_ROOT;
} else {
$homeDir = SL_ROOT . 'upload/';
}
} else {
$subPath = 'home/' . self::getUsername() . '/';
Extend::call('user.home_dir', ['subpath' => &$subPath]);
$homeDir = SL_ROOT . 'upload/' . $subPath;
}
return $homeDir;
}
/**
* Normalize a directory path using the user's privileges
*
* @return string path with a "/" at the end
*/
static function normalizeDir(?string $dirPath): string
{
if (
$dirPath !== null
&& $dirPath !== ''
&& ($dirPath = self::checkPath($dirPath, false, true)) !== false
&& is_dir($dirPath)
) {
return $dirPath;
}
return self::getHomeDir();
}
/**
* Check if the user can access the given path
*
* @param string $path the patch to check
* @param bool $isFile treat path as a file path
* @param bool $getPath return the normalized path if successful 1/0
* @return bool|string
*/
static function checkPath(string $path, bool $isFile, bool $getPath = false)
{
if (self::hasPrivilege('fileaccess')) {
$path = Filesystem::resolvePath($path, $isFile, self::getHomeDir(true));
if ($path !== null && (!$isFile || self::checkFilename($path))) {
return $getPath ? $path : true;
}
}
return false;
}
/**
* Move a file uploaded by the user
*/
static function moveUploadedFile(string $path, string $newPath): bool
{
$handled = false;
Extend::call('user.move_uploaded_file', [
'path' => $path,
'new_path' => $newPath,
'handled' => &$handled,
]);
return $handled || move_uploaded_file($path, $newPath);
}
/**
* See if the user can access the given file name
*
* Only file name is checked, not the path! {@see User::checkPath()}
*/
static function checkFilename(string $filename): bool
{
return
self::hasPrivilege('fileaccess')
&& (
self::hasPrivilege('fileadminaccess')
|| Filesystem::isSafeFile($filename) && Filesystem::isAllowedExtension($filename)
);
}
/**
* Filter user's content based on privileges
*
* @param string $content the content
* @param bool $isHtml indicate HTML content 1/0
* @param bool $hasHcm the content can contain HCM modules 1/0
*/
static function filterContent(string $content, bool $isHtml = true, bool $hasHcm = true): string
{
if ($isHtml && !self::hasPrivilege('rawhtml')) {
$content = HtmlFilter::sanitize($content);
}
Extend::call('user.filter_content', [
'content' => &$content,
'is_html' => $isHtml,
'has_hcm' => $hasHcm,
]);
if ($hasHcm) {
if (!$isHtml) {
throw new \LogicException('Content that supports HCM modules is always HTML');
}
$content = Hcm::filter($content);
}
return $content;
}
/**
* Get current user's username
*/
static function getUsername(): string
{
if (!self::isLoggedIn()) {
return '';
}
return self::$data['username'];
}
/**
* Get current user's display name
*/
static function getDisplayName(): string
{
if (!self::isLoggedIn()) {
return '';
}
return self::$data['publicname'] ?? self::$data['username'];
}
/**
* Normalize username
*
* May return an empty string.
*/
static function normalizeUsername(string $username): string
{
return StringHelper::slugify($username, ['lower' => false, 'max_len' => 24]);
}
/**
* Normalize display name
*
* May return an empty string.
*/
static function normalizePublicname(string $publicname): string
{
return Html::cut(_e(StringHelper::trimExtraWhitespace($publicname)), 24);
}
/**
* See if the given name is available (not already in use by another username or display name)
*/
static function isNameAvailable(string $name, ?int $ignoredUserId = null): bool
{
$where = '(username=' . DB::val($name) . ' OR publicname=' . DB::val($name) . ')';
if ($ignoredUserId !== null) {
$where .= ' AND id!=' . DB::val($ignoredUserId);
}
if (DB::count('user', $where) > 0) {
return false;
}
$result = true;
Extend::call('user.check_name_available', [
'name' => $name,
'ignored_user_id' => $ignoredUserId,
'result' => &$result,
]);
return $result;
}
/**
* See if the given e-mail address is available
*/
static function isEmailAvailable(string $email, ?int $ignoredUserId = null): bool
{
$where = 'email=' . DB::val($email);
if ($ignoredUserId !== null) {
$where .= ' AND id!=' . DB::val($ignoredUserId);
}
if (DB::count('user', $where) > 0) {
return false;
}
$result = true;
Extend::call('user.check_email_available', [
'email' => $email,
'ignored_user_id' => $ignoredUserId,
'result' => &$result,
]);
return $result;
}
/**
* Compose parts of SQL query to load user data
*
* @param string|null $joinUserIdColumn name of user ID column to use for joining or NULL (= don't join)
* @param string $prefix user data column prefix
* @param string $alias alias of the joined user table
* @param mixed $emptyValue column value that signifies "no user"
* @return array{columns: string[], column_list: string, joins: string, alias: string, prefix: string}
*/
static function createQuery(?string $joinUserIdColumn = null, string $prefix = 'user_', string $alias = 'u', $emptyValue = -1): array
{
$groupAlias = "{$alias}g";
// column array
$columns = [
"{$alias}.id" => "{$prefix}id",
"{$alias}.username" => "{$prefix}username",
"{$alias}.publicname" => "{$prefix}publicname",
"{$alias}.group_id" => "{$prefix}group_id",
"{$alias}.avatar" => "{$prefix}avatar",
"{$groupAlias}.title" => "{$prefix}group_title",
"{$groupAlias}.icon" => "{$prefix}group_icon",
"{$groupAlias}.level" => "{$prefix}group_level",
"{$groupAlias}.color" => "{$prefix}group_color",
];
// joins
$joins = [];
if ($joinUserIdColumn !== null) {
$joins[] = 'LEFT JOIN ' . DB::table('user') . " {$alias} ON({$joinUserIdColumn}" . DB::notEqual($emptyValue) . " AND {$joinUserIdColumn}={$alias}.id)";
}
$joins[] = 'LEFT JOIN ' . DB::table('user_group') . " {$groupAlias} ON({$groupAlias}.id={$alias}.group_id)";
// extend
Extend::call('user.query', [
'columns' => &$columns,
'joins' => &$joins,
'empty_value' => $emptyValue,
'prefix' => $prefix,
'alias' => $alias,
]);
// make column list
$columnList = '';
$isFirstColumn = true;
foreach ($columns as $columnName => $columnAlias) {
if (!$isFirstColumn) {
$columnList .= ',';
} else {
$isFirstColumn = false;
}
$columnList .= $columnName . ' ' . $columnAlias;
}
return [
'columns' => array_values($columns),
'column_list' => $columnList,
'joins' => implode(' ', $joins),
'alias' => $alias,
'prefix' => $prefix,
];
}
/**
* Delete an user
*/
static function delete(int $id): bool
{
// fetch user's data
$user = DB::queryRow('SELECT id,username,avatar FROM ' . DB::table('user') . ' WHERE id=' . DB::val($id));
if ($user === false) {
return false;
}
// extend event (check)
$allow = true;
$replacement = null;
Extend::call('user.delete.check', ['user' => $user, 'allow' => &$allow, 'replacement' => &$replacement]);
if (!$allow) {
return false;
}
// get a replacement user to assign existing content to
if ($replacement === null) {
$replacement = DB::queryRow('SELECT id FROM ' . DB::table('user') . ' WHERE group_id=' . DB::val(self::ADMIN_GROUP_ID) . ' AND levelshift=1 AND blocked=0 AND id!=' . DB::val($id) . ' ORDER BY registertime LIMIT 1');
if ($replacement === false) {
return false;
}
}
// extend event (before deletion)
Extend::call('user.delete.before', ['user' => $user, 'replacement' => $replacement]);
// delete database data
DB::delete('user', 'id=' . DB::val($id));
DB::query(
'DELETE ' . DB::table('pm') . ',post'
. ' FROM ' . DB::table('pm')
. ' LEFT JOIN ' . DB::table('post') . ' AS post ON (post.type=' . Post::PRIVATE_MSG . ' AND post.home=' . DB::table('pm') . '.id)'
. ' WHERE receiver=' . DB::val($id) . ' OR sender=' . DB::val($id)
);
DB::update('post', 'author=' . DB::val($id), [
'guest' => sprintf('%x', crc32((string) $id)),
'author' => -1,
], null);
DB::update('article', 'author=' . DB::val($id), ['author' => $replacement['id']], null);
DB::update('poll', 'author=' . DB::val($id), ['author' => $replacement['id']], null);
// delete avatar
if (isset($user['avatar'])) {
self::removeAvatar($user['avatar']);
}
// log
Logger::notice('user', sprintf('User "%s" has been deleted', $user['username']), ['user_id' => $id]);
// extend event (after deletion)
Extend::call('user.delete.after', ['user' => $user, 'replacement' => $replacement]);
return true;
}
/**
* Make user authentication hash
*
* @param string $type see User::AUTH_* constants
* @param string $email user's e-mail
* @param string $storedPassword user's password stored in the database
* @param string $salt additional string data to distinguish hashes
*/
static function getAuthHash(string $type, string $email, string $storedPassword, string $salt = ''): string
{
return hash_hmac('sha256', $type . '$' . $email . '$' . $storedPassword . '$' . $salt, Core::$secret);
}
/**
* Login a user
*/
static function login(int $id, string $storedPassword, string $email, bool $persistent = false, bool $regenerateSession = true): void
{
if ($regenerateSession) {
Session::regenerate();
}
$_SESSION['user_id'] = $id;
$_SESSION['user_auth'] = self::getAuthHash(self::AUTH_SESSION, $email, $storedPassword);
if ($persistent && !headers_sent()) {
$cookie_data = [];
$cookie_data[] = $id;
$cookie_data[] = self::getAuthHash(self::AUTH_PERSISTENT_LOGIN, $email, $storedPassword);
Cookie::set(self::COOKIE_PERSISTENT_LOGIN, implode('$', $cookie_data), ['expires' => time() + 31536000]);
}
}
/**
* Refresh login data
*
* @param array $userChangeset current changes made to the user data
*/
static function refreshLogin(array $userChangeset = [], bool $regenerateSession = true): void
{
self::login(
self::$data['id'],
$userChangeset['password'] ?? self::$data['password'],
$userChangeset['email'] ?? self::$data['email'],
Cookie::exists(self::COOKIE_PERSISTENT_LOGIN),
$regenerateSession
);
}
/**
* Render a login form
*
* @param bool $title render title 1/0
* @param bool $required indicate a required login due to insufficient privileges 1/0
* @param string|null $return_url URL to return to after a successful login
*/
static function renderLoginForm(bool $title = false, bool $required = false, ?string $return_url = null): string
{
$output = '';
// event
Extend::call('user.login.form', [
'title' => &$title,
'required' => &$required,
'return_url' => &$return_url,
'output' => &$output,
]);
if ($output !== '') {
return $output;
}
// title
if ($title) {
$title_text = _lang($required ? (self::isLoggedIn() ? 'global.accessdenied' : 'login.required.title') : 'login.title');
if (Core::$env === Core::ENV_ADMIN) {
$output .= '<h1>' . $title_text . "</h1>\n";
} else {
$GLOBALS['_index']->title = $title_text;
}
}
// text
if ($required) {
$output .= '<p>' . _lang('login.required.p') . "</p>\n";
}
// login result message
if (isset($_GET['login_form_result'])) {
$login_result = self::getLoginMessage(Request::get('login_form_result'));
if ($login_result !== null) {
$output .= $login_result;
}
}
// content
if (!self::isLoggedIn()) {
// return URL
if ($return_url === null) {
if (isset($_GET['login_form_return'])) {
$return_url = Request::get('login_form_return');
} else {
$return_url = Core::getCurrentUrl()->buildRelative();
}
}
// form URL
$form_url = Core::getCurrentUrl();
if ($form_url->has('login_form_result')) {
$form_url->remove('login_form_result');
}
// render form
$output .= Form::render(
[
'name' => 'login_form',
'action' => Router::path('system/script/login.php', ['query' => ['_return' => $return_url ?? '']]),
'form_append' => Form::input('hidden', 'login_form_url', $form_url->buildRelative()) . "\n",
],
[
['label' => _lang('login.username'), 'content' => Form::input('text', 'login_username', $_SESSION['login_form_username'] ?? null, ['class' => 'inputmedium', 'maxlength' => 191, 'autocomplete' => 'username', 'autofocus' => true])],
['label' => _lang('login.password'), 'content' => Form::input('password', 'login_password', null, ['class' => 'inputmedium', 'autocomplete' => 'current-password'])],
Form::getSubmitRow([
'text' => _lang('global.login'),
'append' => ' <label>' . Form::input('checkbox', 'login_persistent', '1', ['checked' => true]) . ' ' . _lang('login.persistent') . '</label>',
]),
]
);
if (isset($_SESSION['login_form_username'])) {
unset($_SESSION['login_form_username']);
}
// links
$links = [];
if (Settings::get('registration') && Core::$env === Core::ENV_WEB) {
$links['reg'] = ['url' => Router::module('reg'), 'text' => _lang('mod.reg')];
}
if (Settings::get('lostpass')) {
$links['lostpass'] = ['url' => Router::module('lostpass'), 'text' => _lang('mod.lostpass')];
}
Extend::call('user.login.links', ['links' => &$links]);
if (!empty($links)) {
$output .= "<ul class=\"login-form-links\">\n";
foreach ($links as $link_id => $link) {
$output .= '<li class="login-form-link-' . $link_id . '"><a href="' . _e($link['url']) . "\">{$link['text']}</a></li>\n";
}
$output .= "</ul>\n";
}
} else {
$output .= '<p>'
. _lang('login.ininfo')
. ' <em>' . self::getUsername() . '</em>'
. ' - <a href="' . _e(Xsrf::addToUrl(Router::path('system/script/logout.php'))) . '">' . _lang('usermenu.logout') . '</a>.'
. '</p>';
}
return $output;
}
/**
* Get login message for the given code
*
* @param int $code see User::LOGIN_* constants
*/
static function getLoginMessage(int $code): ?Message
{
switch ($code) {
case self::LOGIN_FAILURE:
return Message::warning(_lang('login.failure'));
case self::LOGIN_SUCCESS:
return Message::ok(_lang('login.success'));
case self::LOGIN_BLOCKED:
return Message::warning(_lang('login.blocked.message'));
case self::LOGIN_REMOVED:
return Message::ok(_lang('login.selfremove'));
case self::LOGIN_ATTEMPTS_EXCEEDED:
return Message::warning(_lang('login.attemptlimit', ['%minutes%' => _num(Settings::get('maxloginexpire') / 60)]));
case self::LOGIN_XSRF_FAILURE:
return Message::error(_lang('xsrf.msg'));
default:
return Extend::fetch('user.login.message', ['code' => $code]);
}
}
/**
* Handle a login request
*
* Returns a message code for {@see User::getLoginMessage()).
*/
static function submitLogin(string $username, string $plainPassword, bool $persistent = false): int
{
// already logged in?
if (self::isLoggedIn()) {
return self::LOGIN_FAILURE;
}
// XSRF check
if (!Xsrf::check()) {
return self::LOGIN_XSRF_FAILURE;
}
// login attempt limit check
if (!IpLog::check(IpLog::FAILED_LOGIN_ATTEMPT)) {
return self::LOGIN_ATTEMPTS_EXCEEDED;
}
// event
$extend_result = null;
Extend::call('user.login.before', [
'username' => $username,
'password' => $plainPassword,
'persistent' => $persistent,
'result' => &$extend_result,
]);
if ($extend_result !== null) {
return $extend_result;
}
// check username
if ($username === '') {
return self::LOGIN_FAILURE;
}
// load user
if (strpos($username, '@') !== false) {
$cond = 'u.email=' . DB::val($username);
} else {
$cond = 'u.username=' . DB::val($username) . ' OR u.publicname=' . DB::val($username);
}
$query = DB::queryRow('SELECT u.id,u.username,u.email,u.logincounter,u.password,u.blocked,g.blocked group_blocked FROM ' . DB::table('user') . ' u JOIN ' . DB::table('user_group') . ' g ON(u.group_id=g.id) WHERE ' . $cond);
if ($query === false) {
// user not found
return self::LOGIN_FAILURE;
}
// check password
$password = Password::load($query['password']);
if (!$password->match($plainPassword)) {
IpLog::update(IpLog::FAILED_LOGIN_ATTEMPT);
Logger::notice('security', sprintf('Failed login attempt for user "%s"', $query['username']), ['user_id' => $query['id']]);
return self::LOGIN_FAILURE;
}
// check blocked status
if ($query['blocked'] || $query['group_blocked']) {
return self::LOGIN_BLOCKED;
}
// prepare user data changeset
$changeset = [
'ip' => Core::getClientIp(),
'activitytime' => time(),
'logincounter' => $query['logincounter'] + 1,
];
if ($password->shouldUpdate()) {