/
User.php
1183 lines (1013 loc) · 38.3 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
/*
* Made by Samerton
* https://github.com/NamelessMC/Nameless/
* NamelessMC version 2.0.0-pr12
*
* User class
*/
class User {
private DB $_db;
private $_data;
private array $_groups = [];
private array $_placeholders = [];
private string $_sessionName;
private string $_cookieName;
private bool $_isLoggedIn = false;
private string $_admSessionName;
private bool $_isAdmLoggedIn = false;
public function __construct(string $user = null, string $field = 'id') {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
$this->_admSessionName = Config::get('session/admin_name');
if (!$user) {
if (Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if ($this->find($user, $field)) {
$this->_isLoggedIn = true;
}
}
if (Session::exists($this->_admSessionName)) {
$user = Session::get($this->_admSessionName);
if ($user == $this->data()->id && $this->find($user, $field)) {
$this->_isAdmLoggedIn = true;
}
}
} else {
$this->find($user, $field);
}
}
/**
* Get this user's main group CSS styling
*
* @return string|bool Styling on success, false if they have no groups.
*/
public function getGroupClass() {
$groups = $this->_groups;
if (count($groups)) {
foreach ($groups as $group) {
return 'color:' . htmlspecialchars($group->group_username_color) . '; ' . htmlspecialchars($group->group_username_css);
}
}
return false;
}
/**
* Get the logged in user's IP address.
*
* @return string Their IP.
*/
public function getIP(): string {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
return $_SERVER['REMOTE_ADDR'];
}
/**
* Update a user's data in the database.
*
* @param array $fields Column names and values to update.
* @param int $id If not supplied, will use ID of logged in user.
*/
public function update(array $fields = array(), int $id = null): void {
if (!$id) {
$id = $this->data()->id;
}
if (!$this->_db->update('users', $id, $fields)) {
throw new Exception('There was a problem updating your details.');
}
}
/**
* Create a new user.
*
* @param array $fields Column names and values to insert to database.
*/
public function create(array $fields = array()): void {
if (!$this->_db->insert('users', $fields)) {
throw new Exception('There was a problem creating an account.');
}
}
/**
* Find a user by unique identifier (username, ID, email, etc).
* Loads instance variables for this class.
*
* @param string $value Unique identifier.
* @param string $field What column to check for their unique identifier in.
*
* @return bool True/false on success or failure respectfully.
*/
public function find(string $value = null, string $field = 'id'): bool {
if ($value) {
$data = $this->_db->get('users', array($field, '=', $value));
if ($data->count()) {
$this->_data = $data->first();
// Get user groups
$groups_query = $this->_db->query('SELECT nl2_groups.* FROM nl2_users_groups INNER JOIN nl2_groups ON group_id = nl2_groups.id WHERE user_id = ? AND deleted = 0 ORDER BY `order`;', array($this->_data->id));
if ($groups_query->count()) {
$groups_query = $groups_query->results();
foreach ($groups_query as $item) {
$this->_groups[$item->id] = $item;
}
} else {
// Get default group
// TODO: Use PRE_VALIDATED_DEFAULT ?
$default_group = $this->_db->query('SELECT * FROM nl2_groups WHERE default_group = 1', array())->first();
if ($default_group) {
$default_group_id = $default_group->id;
} else {
$default_group_id = 1; // default to 1
$default_group = $this->_db->query('SELECT * FROM nl2_groups WHERE id = 1', array())->first();
}
$this->addGroup($default_group_id, 0, $default_group);
}
// Get their placeholders only if they have a valid uuid
if ($this->_data->uuid != null && $this->_data->uuid != 'none') {
$placeholders = Placeholders::getInstance()->loadUserPlaceholders($this->_data->uuid);
if (count($placeholders)) {
$this->_placeholders = $placeholders;
}
}
return true;
}
}
return false;
}
/**
* Get a user's username from their ID.
*
* @param int $id Their ID.
*
* @return string|bool Their username, false on failure.
*/
public function idToName(int $id = null) {
if ($id) {
$data = $this->_db->get('users', array('id', '=', $id));
if ($data->count()) {
$results = $data->results();
return $results[0]->username;
}
}
return false;
}
/**
* Get a user's nickname from their ID.
*
* @param int $id Their ID.
*
* @return string|bool Their nickname, false on failure.
*/
public function idToNickname(int $id = null) {
if ($id) {
$data = $this->_db->get('users', array('id', '=', $id));
if ($data->count()) {
$results = $data->results();
return $results[0]->nickname;
}
}
return false;
}
private function _commonLogin(?string $username, ?string $password, bool $remember, string $method, bool $is_admin): bool {
$sessionName = $is_admin ? $this->_admSessionName : $this->_sessionName;
if (!$username && !$password && $this->exists()) {
Session::put($sessionName, $this->data()->id);
if (!$is_admin) {
$this->_isLoggedIn = true;
}
} else if ($this->checkCredentials($username, $password, $method) === true) {
// Valid credentials
Session::put($sessionName, $this->data()->id);
if ($remember) {
$hash = Hash::unique();
$table = $is_admin ? 'users_admin_session' : 'users_session';
$hashCheck = $this->_db->get($table, array('user_id', '=', $this->data()->id));
if (!$hashCheck->count()) {
$this->_db->insert($table, array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
$expiry = $is_admin ? 3600 : Config::get('remember/cookie_expiry');
$cookieName = $is_admin ? ($this->_cookieName . '_adm') : $this->_cookieName;
Cookie::put($cookieName, $hash, $expiry, Util::isConnectionSSL(), true);
}
return true;
}
return false;
}
/**
* Log the user in.
*
* @param string $username Their username (or email, depending on $method).
* @param string $password Their password.
* @param bool $remember Whether to keep them logged in or not.
* @param string| $method What column to check for their details in. Can be either `username` or `email`.
*
* @return bool True/false on success or failure respectfully.
*/
public function login(?string $username = null, ?string $password = null, bool $remember = false, string $method = 'email'): bool {
return $this->_commonLogin($username, $password, $remember, $method, false);
}
/**
* Handle StaffCP logins.
*
* @param string $username Their username (or email, depending on $method).
* @param string $password Their password.
* @param string $method What column to check for their details in. Can be either `username` or `email`.
*
* @return bool True/false on success or failure respectfully.
*/
public function adminLogin(?string $username = null, ?string $password = null, string $method = 'email'): bool {
return $this->_commonLogin($username, $password, true, $method, true);
}
/**
* Check whether given credentials are valid.
*
* @param string $username Username (or email) to check.
* @param string $password Password entered by user.
* @param string $method Column to search for user with. Can be `email` or `username`.
*
* @return bool True if correct, false otherwise.
*/
public function checkCredentials(string $username, string $password, string $method = 'email'): bool {
$user = $this->find($username, $method);
if ($user) {
switch ($this->data()->pass_method) {
case 'wordpress':
// phpass
$phpass = new PasswordHash(8, FALSE);
return ($phpass->checkPassword($password, $this->data()->password));
case 'sha256':
$exploded = explode('$', $this->data()->password);
$salt = $exploded[0];
$pass = $exploded[1];
return ($salt . hash('sha256', hash('sha256', $password) . $salt) == $salt . $pass);
case 'pbkdf2':
$exploded = explode('$', $this->data()->password);
$iterations = $exploded[0];
$salt = $exploded[1];
$pass = $exploded[2];
$hashed = hash_pbkdf2('sha256', $password, $salt, $iterations, 64, true);
return ($hashed == hex2bin($pass));
case 'modernbb':
case 'sha1':
return (sha1($password) == $this->data()->password);
default:
// Default to bcrypt
return (password_verify($password, $this->data()->password));
}
}
return false;
}
/**
* Get user's display name.
*
* @param bool|null $username If true, will use their username. If false, will use their nickname.
* @return string Their display name.
*/
public function getDisplayName(bool $username = false): string {
if ($username) {
return Output::getClean($this->_data->username);
}
return Output::getClean($this->_data->nickname);
}
/**
* Build this user's profile link.
*
* @return string Compiled profile URL.
*/
public function getProfileURL(): string {
return Output::getClean(URL::build("/profile/" . $this->data()->username));
}
/**
* Get all of a user's groups. We can return their ID only or their HTML display code.
*
* @param mixed $html If not null, will use group_html column instead of ID.
* @return array Array of all their group's IDs or HTML.
*/
public function getAllGroups($html = null): array {
$groups = array();
if (count($this->_groups)) {
foreach ($this->_groups as $group) {
if (is_null($html)) {
$groups[] = $group->id;
} else {
$groups[] = $group->group_html;
}
}
}
return $groups;
}
/**
* Get all of a user's groups id.
*
* @param bool $login_check If true, will first check if this user is logged in or not. Set to "false" for API usage.
*
* @return array Array of all their group IDs.
*/
public function getAllGroupIds(bool $login_check = true): array {
if ($login_check) {
if (!$this->isLoggedIn()) {
return array(0);
}
}
$groups = array();
if (count($this->_groups)) {
foreach ($this->_groups as $group) {
$groups[$group->id] = $group->id;
}
}
return $groups;
}
/**
* Get this user's signature.
*
* @return string Their signature.
*/
public function getSignature(): string {
if (empty($this->data()->signature)) {
return '';
}
return $this->data()->signature;
}
/**
* Get this user's avatar.
*
* @param int $size Size of image to render in pixels.
* @param bool $full Whether to use full site URL or not, for external loading - ie discord webhooks.
*
* @return string URL to their avatar image.
*/
public function getAvatar(int $size = 128, bool $full = false): string {
// If custom avatars are enabled, first check if they have gravatar enabled, and then fallback to normal image
if (defined('CUSTOM_AVATARS')) {
if ($this->data()->gravatar) {
return "https://secure.gravatar.com/avatar/" . md5(strtolower(trim($this->data()->email))) . "?s=" . $size;
}
if ($this->data()->has_avatar) {
$exts = array('png', 'jpg', 'jpeg');
if ($this->hasPermission('usercp.gif_avatar')) {
$exts[] = 'gif';
}
foreach ($exts as $ext) {
if (file_exists(ROOT_PATH . "/uploads/avatars/" . $this->data()->id . "." . $ext)) {
return ($full ? rtrim(Util::getSelfURL(), '/') : '') . ((defined('CONFIG_PATH')) ? CONFIG_PATH . '/' : '/') . "uploads/avatars/" . $this->data()->id . "." . $ext . '?v=' . Output::getClean($this->data()->avatar_updated);
}
}
}
}
// Fallback to default avatar image if it is set and the avatar type is custom
if (defined('DEFAULT_AVATAR_TYPE') && DEFAULT_AVATAR_TYPE == 'custom') {
if (file_exists(ROOT_PATH . '/uploads/avatars/defaults/' . DEFAULT_AVATAR_IMAGE)) {
return ($full ? rtrim(Util::getSelfURL(), '/') : '') . ((defined('CONFIG_PATH')) ? CONFIG_PATH . '/' : '/') . 'uploads/avatars/defaults/' . DEFAULT_AVATAR_IMAGE;
}
}
// If all else fails, or custom avatars are disabled or default avatar type is 'minecraft', get their MC avatar
if ($this->data()->uuid != null && $this->data()->uuid != 'none') {
$uuid = $this->data()->uuid;
} else {
$uuid = $this->data()->username;
// Fallback to steve avatar if they have an invalid username
if (preg_match("#[^][_A-Za-z0-9]#", $uuid)) {
$uuid = 'Steve';
}
}
return AvatarSource::getAvatarFromUUID($uuid, $size);
}
/**
* If the user has infractions, list them all. Or else return false.
* Not used internally.
*
* @return array|bool Array of infractions if they have one or more, else false.
*/
public function hasInfraction() {
$data = $this->_db->get('infractions', array('punished', '=', $this->data()->id))->results();
if (empty($data)) {
return false;
}
$return = array();
$n = 0;
foreach ($data as $infraction) {
if ($infraction->acknowledged == '0') {
$return[$n]["id"] = $infraction->id;
$return[$n]["staff"] = $infraction->staff;
$return[$n]["reason"] = $infraction->reason;
$return[$n]["date"] = $infraction->infraction_date;
$n++;
}
}
return $return;
}
/**
* Does this user exist?
*
* @return bool Whether the user exists (has data) or not.
*/
public function exists(): bool {
return (!empty($this->_data));
}
/**
* Log the user out.
* Deletes their cookies, sessions and database session entry.
*/
public function logout(): void {
$this->_db->delete('users_session', array('user_id', '=', $this->data()->id));
Session::delete($this->_sessionName);
Cookie::delete($this->_cookieName);
}
/**
* Process logout if user is admin
*/
public function admLogout(): void {
$this->_db->delete('users_admin_session', array('user_id', '=', $this->data()->id));
Session::delete($this->_admSessionName);
Cookie::delete($this->_cookieName . '_adm');
}
/**
* Get the currently logged in user's data.
*
* @return object This user's data.
*/
public function data(): ?object {
return $this->_data;
}
/**
* Get the currently logged in user's groups.
*
* @return array Their groups.
*/
public function getGroups(): array {
return $this->_groups;
}
/**
* Get the currently logged in user's placeholders.
*
* @return array Their placeholders.
*/
public function getPlaceholders(): array {
return $this->_placeholders;
}
/**
* Get this user's placeholders to display on their profile.
*
* @return array Profile placeholders.
*/
public function getProfilePlaceholders(): array {
return array_filter($this->_placeholders, static function ($placeholder) {
return $placeholder->show_on_profile;
});
}
/**
* Get this user's placeholders to display on their forum posts.
*
* @return array Forum placeholders.
*/
public function getForumPlaceholders(): array {
return array_filter($this->_placeholders, static function ($placeholder) {
return $placeholder->show_on_forum;
});
}
/**
* Get this user's main group (with highest order).
*
* @return object|bool The group
*/
public function getMainGroup() {
if (count($this->_groups)) {
foreach ($this->_groups as $group) {
return $group;
}
}
return false;
}
/**
* Set a group to user and remove all other groups
*
* @param int $group_id ID of group to set as main group.
* @param int $expire Expiry in epoch time. If not supplied, group will never expire.
* @param array $group_data Load data from existing query.
*/
public function setGroup(int $group_id, int $expire = 0, array $group_data = null) {
if ($this->data()->id == 1) {
return false;
}
$this->_db->createQuery('DELETE FROM `nl2_users_groups` WHERE `user_id` = ?', array($this->data()->id));
$this->_db->createQuery(
'INSERT INTO `nl2_users_groups` (`user_id`, `group_id`, `received`, `expire`) VALUES (?, ?, ?, ?)',
array(
$this->data()->id,
$group_id,
date('U'),
$expire
)
);
$this->_groups = array();
if($group_data == null) {
$group_data = $this->_db->get('groups', array('id', '=', $group_id));
if ($group_data->count()) {
$this->_groups[$group_id] = $group_data->first();
}
} else {
$this->_groups[$group_id] = $group_data;
}
}
/**
* Add a group to this user.
*
* @param int $group_id ID of group to give.
* @param int $expire Expiry in epoch time. If not supplied, group will never expire.
* @param $group_data Load data from existing query.
*
* @return bool True on success, false if they already have it.
*/
public function addGroup(int $group_id, int $expire = 0, $group_data = null): bool {
if (array_key_exists($group_id, $this->_groups)) {
return false;
}
$this->_db->createQuery(
'INSERT INTO `nl2_users_groups` (`user_id`, `group_id`, `received`, `expire`) VALUES (?, ?, ?, ?)',
array(
$this->data()->id,
$group_id,
date('U'),
$expire
)
);
if($group_data == null) {
$group_data = $this->_db->get('groups', array('id', '=', $group_id));
if ($group_data->count()) {
$this->_groups[$group_id] = $group_data->first();
}
} else {
$this->_groups[$group_id] = $group_data;
}
return true;
}
/**
* Remove a group from the user.
*
* @param int $group_id ID of group to remove.
*
* @return bool Returns false if they did not have this group or the admin group is being removed from root user
*/
public function removeGroup(?int $group_id): bool {
if (!array_key_exists($group_id, $this->_groups)) {
return false;
}
if ($group_id == 2 && $this->data()->id == 1) {
return false;
}
$this->_db->createQuery(
'DELETE FROM `nl2_users_groups` WHERE `user_id` = ? AND `group_id` = ?',
array(
$this->data()->id,
$group_id
)
);
unset($this->_groups[$group_id]);
return true;
}
/**
* Removes all groups this user has.
*/
public function removeGroups(): void {
$where = 'WHERE `user_id` = ?';
if ($this->data()->id == 1) {
$where .= ' AND `group_id` <> 2';
}
$this->_db->createQuery('DELETE FROM `nl2_users_groups` ' . $where, array($this->data()->id));
$this->_groups = array();
}
/**
* Get if this user is currently logged in or not.
*
* @return bool Whether they're logged in.
*/
public function isLoggedIn(): bool {
return $this->_isLoggedIn;
}
/**
* Get if the current user is authenticated as an administrator.
*
* @return bool Whether they're logged in as admin.
*/
public function isAdmLoggedIn(): bool {
return $this->_isAdmLoggedIn;
}
/**
* Get if this user is active/validated or not.
*
* @return bool Whether this user has been validated/activated.
*/
public function isValidated(): bool {
return $this->data()->active;
}
/**
* Get a comma separated string of all users.
* For the new private message dropdown.
*
* @return string CSV list of user's usernames.
*/
public function listAllUsers(): string {
$data = $this->_db->get('users', array('id', '<>', '0'))->results();
$return = '';
foreach ($data as $item) {
$return .= '"' . $item->username . '",';
}
return rtrim($return, ',');
}
/**
* Return an ID from a username.
*
* @param string $username Username to get ID for.
*
* @return int|bool ID on success, false on failure.
*/
public function nameToId(string $username = null) {
if ($username) {
$data = $this->_db->get('users', array('username', '=', $username));
if ($data->count()) {
$results = $data->results();
return $results[0]->id;
}
}
return false;
}
/**
* Return an ID from an email.
*
* @param string $email Email to get ID for.
* @return int|bool ID on success, false on failure.
*/
public function emailToId(string $email = null) {
if ($email) {
$data = $this->_db->get('users', array('email', '=', $email));
if ($data->count()) {
$results = $data->results();
return $results[0]->id;
}
}
return false;
}
/**
* Get a list of PMs a user has access to.
*
* @param int $user_id ID of user to get PMs for.
* @return array|bool Array of PMs, false on failure.
*/
public function listPMs(int $user_id = null) {
if ($user_id) {
$return = array(); // Array to return containing info of PMs
// Get a list of PMs which the user is in
$data = $this->_db->get('private_messages_users', array('user_id', '=', $user_id));
if ($data->count()) {
$data = $data->results();
foreach ($data as $result) {
// Get a list of users who are in this conversation and return them as an array
$pms = $this->_db->get('private_messages_users', array('pm_id', '=', $result->pm_id))->results();
$users = array(); // Array containing users with permission
foreach ($pms as $pm) {
$users[] = $pm->user_id;
}
// Get the PM data
$pm = $this->_db->get('private_messages', array('id', '=', $result->pm_id))->results();
$pm = $pm[0];
$return[$pm->id]['id'] = $pm->id;
$return[$pm->id]['title'] = Output::getClean($pm->title);
$return[$pm->id]['created'] = $pm->created;
$return[$pm->id]['updated'] = $pm->last_reply_date;
$return[$pm->id]['user_updated'] = $pm->last_reply_user;
$return[$pm->id]['users'] = $users;
}
}
// Order the PMs by date updated - most recent first
usort(
$return,
function ($a, $b) {
return $b['updated'] - $a['updated'];
}
);
return $return;
}
return false;
}
/**
* Get a specific private message, and see if the user actually has permission to view it
*
* @param int $pm_id ID of PM to find.
* @param int $user_id ID of user to check permission for.
* @return array|bool Array of info about PM, false on failure.
*/
public function getPM(int $pm_id = null, int $user_id = null) {
if ($user_id && $pm_id) {
// Get the PM - is the user the author?
$data = $this->_db->get('private_messages', array('id', '=', $pm_id));
if ($data->count()) {
$data = $data->results();
$data = $data[0];
// Does the user have permission to view the PM?
$pms = $this->_db->get('private_messages_users', array('pm_id', '=', $pm_id))->results();
foreach ($pms as $pm) {
if ($pm->user_id == $user_id) {
$has_permission = true;
$pm_user_id = $pm->id;
break;
}
}
if (!isset($has_permission)) {
return false; // User doesn't have permission
}
// Set message to "read"
if ($pm->read == 0) {
$this->_db->update('private_messages_users', $pm_user_id, array(
'`read`' => 1
));
}
// User has permission, return the PM information
// Get a list of users in the conversation
if (!isset($pms)) {
$pms = $this->_db->get('private_messages_users', array('pm_id', '=', $pm_id))->results();
}
$users = array(); // Array to store users
foreach ($pms as $pm) {
$users[] = $pm->user_id;
}
return array($data, $users);
}
}
return false;
}
/**
* Delete a user's access to view the PM, or if they're the author, the PM itself.
*
* @param int $pm_id ID of Pm to delete.
* @param int $user_id ID of user to use.
* @return bool Whether the action succeeded or not.
*/
public function deletePM(int $pm_id = null, int $user_id = null) {
if ($user_id && $pm_id) {
// Is the user the author?
$data = $this->_db->get('private_messages', array('id', '=', $pm_id));
if ($data->count()) {
$data = $data->results();
$data = $data[0];
if ($data->author_id != $user_id) {
// User is not the author, only delete
$pms = $this->_db->get('private_messages_users', array('pm_id', '=', $pm_id))->results();
foreach ($pms as $pm) {
if ($pm->user_id == $user_id) {
// get the ID and delete
$id = $pm->id;
$this->_db->delete('private_messages_users', array('id', '=', $id));
return true;
}
}
} else {
// User is the author, delete the PM altogether
$this->_db->delete('private_messages_users', array('pm_id', '=', $pm_id));
$this->_db->delete('private_messages', array('id', '=', $pm_id));
return true;
}
}
}
return false;
}
// Get the number of unread PMs for the specified user
public function getUnreadPMs(int $user_id = null) {
if ($user_id) {
$pms = $this->_db->get('private_messages_users', array('user_id', '=', $user_id));
if ($pms->count()) {
$pms = $pms->results();
$count = 0;
foreach ($pms as $pm) {
if ($pm->read == 0) {
$count++;
}
}
return $count;
} else {
return 0;
}
}
return false;
}
/**
* Can the specified user view StaffCP?
*
* @return bool Whether they can view it or not.
*/
public function canViewStaffCP(): bool {
if (count($this->_groups)) {
foreach ($this->_groups as $group) {
if ($group->admin_cp == 1) {
return true;
}
}
}
return false;
}
/**
* Check the user's permission to see if they can view this staffCP page or not.
* If they cannot, this will handle appropriate redirection.
*
* @param string $permission Permission required for this page.
*/
public function handlePanelPageLoad(string $permission = null): bool {
// Set page user is trying to access in session, to allow for redirection post-auth
if (FRIENDLY_URLS === true) {
$split = explode('?', $_SERVER['REQUEST_URI']);
if (count($split) > 1)
$_SESSION['last_page'] = URL::build($split[0], $split[1]);
else
$_SESSION['last_page'] = URL::build($split[0]);
} else
$_SESSION['last_page'] = URL::build($_GET['route']);
if (defined('CONFIG_PATH'))
$_SESSION['last_page'] = substr($_SESSION['last_page'], strlen(CONFIG_PATH));
if (!$this->isLoggedIn()) {
Redirect::to(URL::build('/login'));
die();
}
if (!$this->canViewStaffCP()) {
Redirect::to(URL::build('/'));
die();
}
if (!$this->isAdmLoggedIn()) {
Redirect::to(URL::build('/panel/auth'));
die();
}
if ($permission != null && !$this->hasPermission($permission)) {
return false;
}
return true;
}
/**
* Get profile fields for specified user
*
* @param int $user_id User to retrieve fields for.
* @param bool| $public Whether to only return public fields or not (default `true`).
* @param bool $forum Whether to only return fields which display on forum posts, only if $public is true (default `false`).
*
* @return array Array of profile fields.