-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.php
More file actions
1081 lines (943 loc) · 23.9 KB
/
User.php
File metadata and controls
1081 lines (943 loc) · 23.9 KB
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
/**
* @package framework
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Hubzero\User;
use Hubzero\Config\Registry;
use Hubzero\Utility\Date;
use Hubzero\Access\Access;
use Hubzero\Access\Map;
use Exception;
use Event;
/**
* Users database model
*
* @uses \Hubzero\Database\Relational
*/
class User extends \Hubzero\Database\Relational
{
/**
* Default order by for model
*
* @var string
* @since 2.1.0
*/
public $orderBy = 'id';
/**
* Default order direction for select queries
*
* @var string
* @since 2.1.0
*/
public $orderDir = 'asc';
/**
* Guest status
*
* @var bool
* @since 2.1.0
*/
public $guest = true;
/**
* Fields and their validation criteria
*
* @var array
* @since 2.1.0
*/
protected $rules = array(
'name' => 'notempty',
'email' => 'notempty',
'username' => 'notempty'
);
/**
* Automatic fields to populate every time a row is created
*
* @var array
* @since 2.1.0
*/
public $initiate = array(
'registerDate',
'registerIP',
'access'
);
/**
* A cached switch for if this user has root access rights.
*
* @var boolean
* @since 2.1.0
*/
protected $isRoot = null;
/**
* User params
*
* @var object
* @since 2.1.0
*/
protected $userParams = null;
/**
* Authorised access groups
*
* @var array
* @since 2.1.0
*/
protected $authGroups = null;
/**
* Authorised access levels
*
* @var array
* @since 2.1.0
*/
protected $authLevels = null;
/**
* Authorised access actions
*
* @var array
* @since 2.1.0
*/
protected $authActions = null;
/**
* Link pattern
*
* @var string
* @since 2.1.0
*/
public static $linkBase = null;
/**
* List of picture resolvers
*
* @var array
* @since 2.1.0
*/
public static $pictureResolvers = array();
/**
* Serializes the model data for storage
*
* @return string
* @since 2.1.0
*/
public function serialize()
{
$attr = $this->__serialize();
return serialize($attr);
}
/**
* Serializes the model data for storage
*
* @return array
*/
public function __serialize()
{
$attr = $this->getAttributes();
$attr['guest'] = $this->guest;
return $attr;
}
/**
* Unserializes the data into a new model
*
* @param string $data The data to build from
* @return void
* @since 2.1.0
*/
public function unserialize($data)
{
$data = unserialize($data);
$this->__unserialize($data);
}
/**
* Unserializes the data into a new model
*
* @param array $data The data to build from
* @return void
*/
public function __unserialize($data)
{
$this->__construct();
if (isset($data['guest']))
{
$this->guest = $data['guest'];
unset($data['guest']);
}
$this->set($data);
}
/**
* Sets up additional custom rules
*
* @return void
*/
public function setup()
{
// Check that username conforms to rules
$this->addRule('username', function($data)
{
$username = $data['username'];
// We do this here because we need to allow one possible
// "invalid" username to pass through, used when creating
// temp accounts during the 3rd party auth registration
if (is_numeric($username) && $username < 0)
{
return false;
}
if (preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $username)
|| strlen(utf8_decode($username)) < 2
|| trim($username) != $username)
{
return \Lang::txt('JLIB_DATABASE_ERROR_VALID_AZ09', 2);
}
return false;
});
// Check for existing username
$this->addRule('username', function($data)
{
$user = self::oneByUsername($data['username']);
if ($user->get('id') && $user->get('id') != $data['id'])
{
return \Lang::txt('JLIB_DATABASE_ERROR_USERNAME_INUSE');
}
return false;
});
// Check for valid email address
// We do this here because we need to allow one possible
// "invalid" address to pass through, used when creating
// temp accounts during the 3rd party auth registration
$this->addRule('email', function($data)
{
$email = $data['email'];
if (preg_match('/^-[0-9]+@invalid$/', $email ?: ''))
{
return false;
}
return (\Hubzero\Utility\Validate::email($email) ? false : 'Email does not appear to be valid');
});
}
/**
* Generates automatic registerDate field value
*
* @param array $data the data being saved
* @return string
*/
public function automaticRegisterDate($data)
{
$dt = new Date('now');
return $dt->toSql();
}
/**
* Generates automatic registerIP field value
*
* @param array $data the data being saved
* @return string
*/
public function automaticRegisterIP($data)
{
if (!isset($data['registerIP']))
{
$data['registerIP'] = \Request::ip();
}
return $data['registerIP'];
}
/**
* Generates automatic access field value
*
* @param array $data the data being saved
* @return string
*/
public function automaticAccess($data)
{
if (!isset($data['access']) || !$data['access'])
{
$data['access'] = 1;
}
return $data['access'];
}
/**
* Defines a one to many relationship between users and reset tokens
*
* @return object \Hubzero\Database\Relationship\OneToMany
* @since 2.0.0
*/
public function tokens()
{
return $this->oneToMany('Hubzero\User\Token', 'user_id');
}
/**
* Defines a one to one relationship between a user and their reputation
*
* @return object \Hubzero\Database\Relationship\OneToOne
* @since 2.0.0
*/
public function reputation()
{
return $this->oneToOne('Hubzero\User\Reputation', 'user_id');
}
/**
* Get access groups
*
* @return object
*/
public function accessgroups()
{
return $this->oneToMany('Hubzero\Access\Map', 'user_id');
}
/**
* Get groups
*
* @param string $role
* @return array
*/
public function groups($role = 'all')
{
//return $this->manyToMany('Hubzero\User\Extended\Group', 'id', 'uidNumber');
static $groups;
if (!isset($groups))
{
$groups = array(
'applicants' => array(),
'invitees' => array(),
'members' => array(),
'managers' => array(),
'all' => array()
);
$all = Helper::getGroups($this->get('id'), 'all', 1);
if ($all)
{
$groups['all'] = $all;
foreach ($groups['all'] as $item)
{
if ($item->registered)
{
if (!$item->regconfirmed)
{
$groups['applicants'][] = $item;
}
else
{
if ($item->manager)
{
$groups['managers'][] = $item;
}
else
{
$groups['members'][] = $item;
}
}
}
else
{
$groups['invitees'][] = $item;
}
}
}
}
if ($role)
{
return (isset($groups[$role])) ? $groups[$role] : array();
}
return $groups;
}
/**
* Defines a relationship with a generic user logging class (not a relational model itself)
*
* @return object \Hubzero\User\Logger
* @since 2.0.0
*/
public function logger()
{
return new Logger($this);
}
/**
* Gets an attribute by key
*
* This will not retrieve properties directly attached to the model,
* even if they are public - those should be accessed directly!
*
* Also, make sure to access properties in transformers using the get method.
* Otherwise you'll just get stuck in a loop!
*
* @param string $key The attribute key to get
* @param mixed $default The value to provide, should the key be non-existent
* @return mixed
*/
public function get($key, $default = null)
{
if ($key == 'guest')
{
return $this->isGuest();
}
if ($key == 'uidNumber')
{
$key = 'id';
}
// If the givenName, middleName, or surname isn't set, try to determine it from the name
if (($key == 'givenName' || $key == 'middleName' || $key == 'surname') && parent::get($key, null) == null)
{
return $this->parseName($key);
}
// Legacy code expects get('id') to always
// return an integer, even if user is logged out
if ($key == 'id' && is_null($default))
{
$default = 0;
}
return parent::get($key, $default);
}
/**
* Sets attributes (i.e. fields) on the model
*
* This must be used when setting data to be saved. Otherwise, the properties
* will be attached directly to the model itself and not included in the save.
*
* @param array|string $key The key to set, or array of key/value pairs
* @param mixed $value The value to set if key is string
* @return object $this Chainable
* @since 2.1.0
*/
public function set($key, $value = null)
{
if (is_string($key) && $key == 'guest')
{
return $this->guest = $value;
}
if (is_string($key) && $key == 'uidNumber')
{
$key = 'id';
}
if (is_string($key) && in_array($key, array('givenName','middleName','surname','name')))
{
$value = \Hubzero\Utility\Sanitize::cleanProperName($value);
}
return parent::set($key, $value);
}
/**
* Is the current user a guest (logged out) or not?
*
* @return boolean
*/
public function isGuest()
{
$pubkeyb64 = Config::get('jwt_pub_key', null);
$env = substr(Config::get('application_env', ''), -5);
// check for a jwt if user is not logged in
if ($this->guest && array_key_exists('jwt', $_COOKIE) &&
$env == 'cloud' && !is_null($pubkeyb64))
{
try
{
// decode public key and use it to check jwt signature
$pubkey = base64_decode($pubkeyb64);
$jwt = \Firebase\JWT\JWT::decode($_COOKIE['jwt'], $pubkey, array('RS512'));
// if we have information for a user, populate the user variable
if (isset($jwt->email) && isset($jwt->id) && isset($jwt->username) && isset($jwt->name) && isset($jwt->exp))
{
if ($jwt->exp < time())
{
setcookie('jwt', -86400, 0, '/', '.' . \Hubzero\Utility\Dns::domain(), true, true);
return $this->guest();
}
$jwtid = $jwt->id;
$jwtemail = $jwt->email;
$jwtuser = $jwt->username;
$jwtname = $jwt->name;
// check if we have a user by this email address
$user = \User::oneByEmail($jwtemail);
// this user does not exist
// we should create this in the hub database
if ($user->isNew())
{
// Using SQL here because the ORM does not currently support writing
// new records with a specific primary key value
$db = App::get('db');
$query = "INSERT INTO `#__users` (`id`, `name`, `username`, `email`, `password`, `usertype`, `block`, " .
"`approved`, `sendEmail`, `activation`, `params`, `access`, `usageAgreement`, `homeDirectory`, `loginShell`, `ftpShell`)
VALUES (" . $db->quote($jwtid) . ", " . $db->quote($jwtname) . ", " . $db->quote($jwtuser) .
", " . $db->quote($jwtemail) . ", " . $db->quote('') . ", " . $db->quote('') . ", " .
$db->quote('0') . ", " . $db->quote('2') . ", " . $db->quote('0') . ", " . $db->quote('1') .
", " . $db->quote('') . ", " . $db->quote('5') . ", " . $db->quote('1') . ", " .
$db->quote('/home/' . $jwtuser) . ", " . $db->quote('/bin/bash') . ", " .
$db->quote('/usr/lib/sftp-server') . ")";
$db->setQuery($query);
$result = $db->query();
$usersConfig = Component::params('com_members');
$newUsertype = $usersConfig->get('new_usertype', '2');
$query = "INSERT INTO `#__user_usergroup_map` (`user_id`, `group_id`) VALUES (" . $db->quote($jwtid) . ", " . $db->quote($newUsertype) . ")";
$db->setQuery($query);
$result = $db->query();
// Clear the session that was not logged in
App::get('session')->restart();
}
// set up the user object to be logged in
\User::set('id', $user->get('id'));
\User::set('email', $jwtemail);
\User::set('username', $jwtuser);
\User::set('guest', false);
\User::set('approved', 2);
// set the user object in the session such that
// next visit and other plugins that use the session
// know what user is logged in
App::get('session')->set('user', App::get('user')->getInstance());
$this->guest = false;
$data = App::get('user')->getInstance()->toArray();
\Event::trigger('user.onUserLogin', array($data));
}
}
catch (Exception $e)
{
// something likely went wrong with the jwt
}
}
return $this->guest;
}
/**
* Transform parameters into object
*
* @return object \Hubzero\Config\Registry
* @since 2.1.0
*/
public function transformParams()
{
if (!isset($this->userParams))
{
$this->userParams = new Registry($this->get('params'));
}
return $this->userParams;
}
/**
* Method to get a parameter value
*
* @param string $key Parameter key
* @param mixed $default Parameter default value
* @return mixed The value or the default if it did not exist
* @since 2.1.0
*/
public function getParam($key, $default = null)
{
return $this->params->get($key, $default);
}
/**
* Method to set a parameter
*
* @param string $key Parameter key
* @param mixed $value Parameter value
* @return mixed Set parameter value
* @since 2.1.0
*/
public function setParam($key, $value)
{
return $this->params->set($key, $value);
}
/**
* Method to set a default parameter if it does not exist
*
* @param string $key Parameter key
* @param mixed $value Parameter value
* @return mixed Set parameter value
* @since 2.1.0
*/
public function defParam($key, $value)
{
return $this->params->def($key, $value);
}
/**
* Get a user's picture
*
* @param integer $anonymous Is user anonymous?
* @param boolean $thumbnail Show thumbnail or full picture?
* @param boolean $serveFile Serve file?
* @return string
* @since 2.1.0
*/
public function picture($anonymous=0, $thumbnail=true, $serveFile=true)
{
static $fallback;
if (!isset($fallback))
{
$image = "<svg xmlns='http://www.w3.org/2000/svg' width='64' height='64' viewBox='0 0 64 64' style='stroke-width: 0px; background-color: #ffffff;'>" .
"<path fill='#d9d9d9' d='M63.9 64v-3c-.6-.9-1-1.8-1.4-2.8l-1.2-3c-.4-1-.9-1.9-1.4-2.8S58.8 50.9 58 " .
"50c-.8-.8-1.5-1.3-2.4-1.5-.6-.2-1.1-.3-1.7-.4-.6 0-2.1-.3-4.4-.6l-8.4-1.3c-.2-.8-.4-1.5-.5-2.4-.1-" .
".8-.3-1.5-.6-2.4.3-.6.7-1 1.1-1.5.4-.6.8-1 1.1-1.5.4-.6.7-1.3 1-2.2.3-.8.8-3.5 1.3-7.8l.4-3c.1-.9." .
"1-1.4.1-1.5 0-2.9-1-5.6-3.1-8-1-1.3-2.4-2.4-4.1-3.2-1.8-.9-3.7-1.4-6-1.4-2.2 0-4.3.4-6 1.3-1.8.9-3" .
".1 2-4.2 3.2-1.1 1.3-1.8 2.6-2.3 4.1-.6 1.4-.7 2.5-.7 3.2 0 .7 0 1.5.1 2.3l.4 2.9.4 3.1.4 3.3c.2 1" .
".1.7 2.4 1.5 3.7.3.6.7 1.1 1.1 1.5l1.1 1.5c-.2.8-.4 1.5-.6 2.4-.1.8-.3 1.5-.6 2.4l-5.6.8-4.6.8c-1." .
"2.2-2.1.3-2.6.4-.6.1-1.1.2-1.7.4-2.1.8-4 3.1-5.7 6.8L.9 58.5c-.4 1-.8 1.9-1.3 2.8V64h64.3z'/>" .
"</svg>";
$fallback = sprintf('data:image/svg+xml;base64,%s', base64_encode($image));
}
if (!$this->get('id') || $anonymous)
{
return $fallback;
}
$picture = null;
foreach (self::$pictureResolvers as $resolver)
{
$picture = $resolver->picture($this->get('id'), $this->get('name'), $this->get('email'), $thumbnail);
if ($picture)
{
break;
}
}
if (!$picture)
{
$picture = $fallback;
}
return $picture;
}
/**
* Generate and return various links to the entry
* Link will vary depending upon action desired such as edit, delete, etc.
*
* @param string $type The type of link to return
* @return string
* @since 2.1.0
*/
public function link($type='')
{
if (!$this->get('id') || !self::$linkBase)
{
return '';
}
$link = str_replace(
array(
'{ID}',
'{USERNAME}',
'{EMAIL}',
'{NAME}'
),
array(
$this->get('id'),
$this->get('username'),
$this->get('email'),
str_replace(' ', '+', $this->get('name'))
),
self::$linkBase
);
return $link;
}
/**
* Finds a user by username
*
* @param string $username
* @return object
* @since 2.1.0
*/
public static function oneByUsername($username)
{
return self::all()
->whereEquals('username', $username)
->row();
}
/**
* Finds a user by email
*
* @param string $email
* @return object
* @since 2.1.0
*/
public static function oneByEmail($email)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
return self::oneByUsername($email);
}
return self::all()
->whereEquals('email', $email)
->row();
}
/**
* Finds a user by activation token
*
* @param string $token
* @return object
* @since 2.1.0
*/
public static function oneByActivationToken($token)
{
return self::all()
->whereEquals('activation', $token)
->row();
}
/**
* Pass through method to the table for setting the last visit date
*
* @param integer $timestamp The timestamp, defaults to 'now'.
* @return boolean True on success.
* @since 2.1.0
*/
public function setLastVisit($timestamp = 'now')
{
$timestamp = new Date($timestamp);
$query = $this->getQuery()
->update($this->getTableName())
->set(array('lastvisitDate' => $timestamp->toSql()))
->whereEquals('id', $this->get('id'));
return $query->execute();
}
/**
* Alias for authorise() method
*
* @param string $action The name of the action to check for permission.
* @param string $assetname The name of the asset on which to perform the action.
* @return boolean True if authorised
* @since 2.1.0
*/
public function authorize($action, $assetname = null)
{
return $this->authorise($action, $assetname);
}
/**
* Method to check User object authorisation against an access control
* object and optionally an access extension object
*
* @param string $action The name of the action to check for permission.
* @param string $assetname The name of the asset on which to perform the action.
* @return boolean True if authorised
* @since 2.1.0
*/
public function authorise($action, $assetname = null)
{
// Make sure we only check for core.admin once during the run.
if ($this->isRoot === null)
{
$this->isRoot = false;
// Check for the configuration file failsafe.
$rootUser = \App::get('config')->get('root_user');
// The root_user variable can be a numeric user ID or a username.
if (is_numeric($rootUser) && $this->get('id') > 0 && $this->get('id') == $rootUser)
{
$this->isRoot = true;
}
elseif ($this->username && $this->username == $rootUser)
{
$this->isRoot = true;
}
else
{
// Get all groups against which the user is mapped.
$identities = $this->getAuthorisedGroups();
array_unshift($identities, $this->get('id') * -1);
if (Access::getAssetRules(1)->allow('core.admin', $identities))
{
$this->isRoot = true;
return true;
}
}
}
return $this->isRoot ? true : Access::check($this->get('id'), $action, $assetname);
}
/**
* Method to return a list of all categories that a user has permission for a given action
*
* @param string $component The component from which to retrieve the categories
* @param string $action The name of the section within the component from which to retrieve the actions.
* @return array List of categories that this group can do this action to (empty array if none). Categories must be published.
* @since 2.1.0
*/
public function getAuthorisedCategories($component, $action)
{
// Brute force method: get all published category rows for the component and check each one
// TODO: Move to ORM-based models
$db = \App::get('db');
$query = $db->getQuery()
->select('c.id', 'id')
->select('a.name', 'asset_name')
->from('#__categories', 'c')
->join('#__assets AS a', 'c.asset_id', 'a.id', 'inner')
->whereEquals('c.extension', $component)
->whereEquals('c.published', '1');
$db->setQuery($query->toString());
$allCategories = $db->loadObjectList('id');
$allowedCategories = array();
foreach ($allCategories as $category)
{
if ($this->authorise($action, $category->asset_name))
{
$allowedCategories[] = (int) $category->id;
}
}
return $allowedCategories;
}
/**
* Gets an array of the authorised access levels for the user
*
* @return array
* @since 2.1.0
*/
public function getAuthorisedViewLevels()
{
if (is_null($this->authLevels))
{
$this->authLevels = array();
}
if (empty($this->_authLevels))
{
$this->authLevels = Access::getAuthorisedViewLevels($this->get('id'));
}
return $this->authLevels;
}
/**
* Gets an array of the authorised user groups
*
* @return array
* @since 2.1.0
*/
public function getAuthorisedGroups()
{
if (is_null($this->authGroups))
{
$this->authGroups = array();
}
if (empty($this->authGroups))
{
$this->authGroups = Access::getGroupsByUser($this->get('id'));
}
return $this->authGroups;
}
/**
* Save data
*
* @return boolean
*/
public function save()
{
if ($this->get('username') == false)
{
return false;
}
// Trigger the onUserBeforeSave event.
$data = $this->toArray();
$isNew = $this->isNew();
// Allow an exception to be thrown.
try
{
$oldUser = self::oneOrNew($this->get('id'));
// Trigger the onUserBeforeSave event.
$result = Event::trigger('user.onUserBeforeSave', array($oldUser->toArray(), $isNew, $data));
if (in_array(false, $result, true))
{
// Plugin will have to raise its own error or throw an exception.
return false;
}
// Get any set access groups
$groups = null;
if ($this->hasAttribute('accessgroups'))
{
$groups = $this->get('accessgroups');
$this->removeAttribute('accessgroups');
}
// Save record
$result = parent::save();
if (!$result)
{
throw new Exception($this->getError());
}
// Update access groups
if ($groups && is_array($groups))
{
Map::destroyByUser($this->get('id'));
Map::addUserToGroup($this->get('id'), $groups);
}
// In case it's a new user, we need to grab the ID
$data['id'] = $this->get('id');
// Fire the onUserAfterSave event
Event::trigger('user.onUserAfterSave', array($data, $isNew, $result, $this->getError()));
$this->purgeCache();
}
catch (Exception $e)
{
$this->addError($e->getMessage());
$result = false;
}
return $result;
}
/**
* Delete the record and associated data
*
* @return boolean False if error, True on success
*/
public function destroy()
{
$data = $this->toArray();
// Trigger the onUserBeforeDelete event
Event::trigger('user.onUserBeforeDelete', array($data));
// Remove associated data
if ($this->reputation->get('id'))
{
if (!$this->reputation->destroy())
{
$this->addError($this->reputation->getError());
return false;
}
}
foreach ($this->tokens()->rows() as $token)
{