Elgg  Version master
ElggUser.php
Go to the documentation of this file.
1 <?php
2 
8 
28 class ElggUser extends \ElggEntity {
29 
30  use Friends;
31  use PluginSettings {
32  getPluginSetting as protected psGetPluginSetting;
33  }
34  use ProfileData;
35 
39  protected function initializeAttributes() {
40  parent::initializeAttributes();
41  $this->attributes['subtype'] = 'user';
42 
43  $this->attributes['access_id'] = ACCESS_PUBLIC;
44  $this->attributes['owner_guid'] = 0; // Users aren't owned by anyone, even if they are admin created.
45  $this->attributes['container_guid'] = 0; // Users aren't contained by anyone, even if they are admin created.
46 
47  // Before Elgg 3.0 this was handled by database logic
48  $this->setMetadata('banned', 'no');
49  $this->setMetadata('admin', 'no');
50  $this->language = elgg_get_config('language');
51  $this->prev_last_action = 0;
52  $this->last_login = 0;
53  $this->prev_last_login = 0;
54  }
55 
59  public function getType(): string {
60  return 'user';
61  }
62 
71  public function getLanguage(string $fallback = null): string {
72  if (!empty($this->language)) {
73  return $this->language;
74  }
75 
76  if ($fallback !== null) {
77  return $fallback;
78  }
79 
80  return elgg_get_config('language');
81  }
82 
88  public function __set($name, $value) {
89  switch ($name) {
90  case 'salt':
91  case 'password':
92  _elgg_services()->logger->error("User entities no longer contain {$name}");
93  return;
94  case 'password_hash':
95  _elgg_services()->logger->error('password_hash is a readonly attribute.');
96  return;
97  case 'email':
98  try {
99  _elgg_services()->accounts->assertValidEmail($value);
100  } catch (RegistrationException $ex) {
101  throw new ElggInvalidArgumentException($ex->getMessage(), $ex->getCode(), $ex);
102  }
103  break;
104  case 'username':
105  try {
106  _elgg_services()->accounts->assertValidUsername($value);
107  } catch (RegistrationException $ex) {
108  throw new ElggInvalidArgumentException($ex->getMessage(), $ex->getCode(), $ex);
109  }
110 
111  $existing_user = elgg_get_user_by_username($value);
112  if ($existing_user instanceof \ElggUser && ($existing_user->guid !== $this->guid)) {
113  throw new ElggInvalidArgumentException("{$name} is supposed to be unique for ElggUser");
114  }
115  break;
116  case 'admin':
117  throw new ElggInvalidArgumentException(_elgg_services()->translator->translate('ElggUser:Error:SetAdmin', ['makeAdmin() / removeAdmin()']));
118  case 'banned':
119  throw new ElggInvalidArgumentException(_elgg_services()->translator->translate('ElggUser:Error:SetBanned', ['ban() / unban()']));
120  }
121 
122  parent::__set($name, $value);
123  }
124 
132  public function ban(string $reason = ''): bool {
133 
134  if (!$this->canEdit()) {
135  return false;
136  }
137 
138  if (!_elgg_services()->events->trigger('ban', 'user', $this)) {
139  return false;
140  }
141 
142  $this->ban_reason = $reason;
143  $this->setMetadata('banned', 'yes');
144 
145  $this->invalidateCache();
146 
147  return true;
148  }
149 
155  public function unban(): bool {
156 
157  if (!$this->canEdit()) {
158  return false;
159  }
160 
161  if (!_elgg_services()->events->trigger('unban', 'user', $this)) {
162  return false;
163  }
164 
165  unset($this->ban_reason);
166  $this->setMetadata('banned', 'no');
167 
168  $this->invalidateCache();
169 
170  return true;
171  }
172 
178  public function isBanned(): bool {
179  return $this->banned === 'yes';
180  }
181 
187  public function isAdmin(): bool {
188  return $this->admin === 'yes';
189  }
190 
196  public function makeAdmin(): bool {
197 
198  if ($this->isAdmin()) {
199  return true;
200  }
201 
202  if (!_elgg_services()->events->trigger('make_admin', 'user', $this)) {
203  return false;
204  }
205 
206  $this->setMetadata('admin', 'yes');
207 
208  $this->invalidateCache();
209 
210  return true;
211  }
212 
218  public function removeAdmin(): bool {
219 
220  if (!$this->isAdmin()) {
221  return true;
222  }
223 
224  if (!_elgg_services()->events->trigger('remove_admin', 'user', $this)) {
225  return false;
226  }
227 
228  $this->setMetadata('admin', 'no');
229 
230  $this->invalidateCache();
231 
232  return true;
233  }
234 
240  public function setLastLogin(): void {
241 
242  $time = $this->getCurrentTime()->getTimestamp();
243 
244  if ($this->last_login == $time) {
245  // no change required
246  return;
247  }
248 
249  // these writes actually work, we just type hint read-only.
250  $this->prev_last_login = $this->last_login;
251  $this->last_login = $time;
252  }
253 
259  public function setLastAction(): void {
260 
261  $time = $this->getCurrentTime()->getTimestamp();
262 
263  if ($this->last_action == $time) {
264  // no change required
265  return;
266  }
267 
268  $user = $this;
269 
270  elgg_register_event_handler('shutdown', 'system', function () use ($user, $time) {
271  // these writes actually work, we just type hint read-only.
272  $user->prev_last_action = $user->last_action;
273 
274  $user->updateLastAction($time);
275  });
276  }
277 
283  public function isValidated(): ?bool {
284  if (!isset($this->validated)) {
285  return null;
286  }
287 
288  return (bool) $this->validated;
289  }
290 
299  public function setValidationStatus(bool $status, string $method = ''): void {
300  if ($status === $this->isValidated()) {
301  // no change needed
302  return;
303  }
304 
305  $this->validated = $status;
306 
307  if ($status) {
308  $this->validated_method = $method;
309  $this->validated_ts = time();
310 
311  // make sure the user is enabled
312  if (!$this->isEnabled()) {
313  $this->enable();
314  }
315 
316  // let the system know the user is validated
317  _elgg_services()->events->triggerAfter('validate', 'user', $this);
318  } else {
319  // invalidating
320  unset($this->validated_ts);
321  unset($this->validated_method);
322  _elgg_services()->events->triggerAfter('invalidate', 'user', $this);
323  }
324  }
325 
333  public function getGroups(array $options = []) {
334  $options['type'] = 'group';
335  $options['relationship'] = 'member';
336  $options['relationship_guid'] = $this->guid;
337 
338  return elgg_get_entities($options);
339  }
340 
344  public function getObjects(array $options = []) {
345  $options['type'] = 'object';
346  $options['owner_guid'] = $this->guid;
347 
348  return elgg_get_entities($options);
349  }
350 
358  public function getOwnerGUID(): int {
359  if ($this->owner_guid == 0) {
360  return $this->guid;
361  }
362 
363  return $this->owner_guid;
364  }
365 
369  protected function prepareObject(\Elgg\Export\Entity $object) {
370  $object = parent::prepareObject($object);
371  $object->name = $this->getDisplayName();
372  $object->username = $this->username;
373  $object->language = $this->language;
374  unset($object->read_access);
375  return $object;
376  }
377 
386  public function setPassword(string $password): void {
387  $this->setMetadata('password_hash', _elgg_services()->passwords->generateHash($password));
388  if ($this->guid === elgg_get_logged_in_user_guid()) {
389  // update the session user token, so this session remains valid
390  // other sessions for this user will be invalidated
391  _elgg_services()->session_manager->setUserToken();
392  }
393  }
394 
405  public function setNotificationSetting(string $method, bool $enabled = true, string $purpose = 'default'): bool {
406  if (empty($purpose)) {
407  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
408  }
409 
410  $this->{"notification:{$purpose}:{$method}"} = (int) $enabled;
411  return $this->save();
412  }
413 
428  public function getNotificationSettings(string $purpose = 'default'): array {
429  if (empty($purpose)) {
430  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
431  }
432 
433  $settings = [];
434 
435  $methods = _elgg_services()->notifications->getMethods();
436  foreach ($methods as $method) {
437  if ($purpose !== 'default' && !isset($this->{"notification:{$purpose}:{$method}"})) {
438  // fallback to the default settings
439  $settings[$method] = (bool) $this->{"notification:default:{$method}"};
440  } else {
441  $settings[$method] = (bool) $this->{"notification:{$purpose}:{$method}"};
442  }
443  }
444 
445  return $settings;
446  }
447 
451  public function delete(bool $recursive = true): bool {
452  $result = parent::delete($recursive);
453  if ($result) {
454  // cleanup remember me cookie records
455  _elgg_services()->users_remember_me_cookies_table->deleteAllHashes($this);
456  }
457 
458  return $result;
459  }
460 
471  public function getPluginSetting(string $plugin_id, string $name, $default = null) {
472  $plugin = _elgg_services()->plugins->get($plugin_id);
473  if ($plugin instanceof \ElggPlugin) {
474  $static_defaults = (array) $plugin->getStaticConfig('user_settings', []);
475 
476  $default = elgg_extract($name, $static_defaults, $default);
477  }
478 
479  return $this->psGetPluginSetting($plugin_id, $name, $default);
480  }
481 }
$default
Definition: checkbox.php:31
elgg_register_event_handler(string $event, string $type, callable|string $callback, int $priority=500)
Helper functions for event handling.
Definition: events.php:48
setValidationStatus(bool $status, string $method= '')
Set the validation status for a user.
Definition: ElggUser.php:299
setMetadata(string $name, $value, string $value_type= '', bool $multiple=false)
Set metadata on this entity.
Definition: ElggEntity.php:370
$plugin
$last_login
Definition: online.php:17
makeAdmin()
Make the user an admin.
Definition: ElggUser.php:196
getPluginSetting(string $plugin_id, string $name, $default=null)
Get a plugin setting.
Definition: ElggUser.php:471
elgg_get_config(string $name, $default=null)
Get an Elgg configuration value.
Elgg registration action.
if(!$user||!$user->canDelete()) $name
Definition: delete.php:22
trait ProfileData
Adds methods to save profile data to an ElggEntity.
Definition: ProfileData.php:11
invalidateCache()
Invalidate cache for entity.
elgg_get_user_by_username(string $username, bool $try_email=false)
Get a user by username.
Definition: users.php:39
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it plus any associated interface definition plus the scripts used to control compilation and installation of the executable as a special the source code distributed need not include anything that is normally and so on of the operating system on which the executable unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated then offering equivalent access to copy the source code from the same place counts as distribution of the source even though third parties are not compelled to copy the source along with the object code You may not or distribute the Program except as expressly provided under this License Any attempt otherwise to sublicense or distribute the Program is void
Definition: LICENSE.txt:215
enable(bool $recursive=true)
Enable the entity.
if(!$annotation instanceof ElggAnnotation) $time
Definition: time.php:20
$username
Definition: delete.php:23
setLastLogin()
Sets the last logon time of the user to right now.
Definition: ElggUser.php:240
Could not register a new user for whatever reason.
initializeAttributes()
{}
Definition: ElggUser.php:39
prepareObject(\Elgg\Export\Entity $object)
{}
Definition: ElggUser.php:369
if($type!= 'user') $settings
Definition: save.php:16
$options
Elgg admin footer.
Definition: footer.php:6
$plugin_id
Remove all user and plugin settings from the give plugin ID.
Definition: remove.php:8
canEdit(int $user_guid=0)
Can a user edit this entity?
Definition: ElggEntity.php:946
$value
Definition: generic.php:51
elgg_extract($key, $array, $default=null, bool $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:254
getCurrentTime($modifier= '')
Get the (cloned) time.
Definition: TimeUsing.php:25
$owner_guid
getObjects(array $options=[])
{}
Definition: ElggUser.php:344
if(!$user||!$user->canEdit()) $password
setLastAction()
Sets the last action time of the given user to right now.
Definition: ElggUser.php:259
unban()
Unban this user.
Definition: ElggUser.php:155
$language
Definition: useradd.php:17
elgg_get_entities(array $options=[])
Fetches/counts entities or performs a calculation on their properties.
Definition: entities.php:504
getLanguage(string $fallback=null)
Get user language or default to site language.
Definition: ElggUser.php:71
$enabled
Sample cli installer script.
$user
Definition: ban.php:7
getOwnerGUID()
Get a user&#39;s owner GUID.
Definition: ElggUser.php:358
isEnabled()
Is this entity enabled?
$purpose
Definition: record.php:16
getType()
{}
Definition: ElggUser.php:59
getGroups(array $options=[])
Gets the user&#39;s groups.
Definition: ElggUser.php:333
setNotificationSetting(string $method, bool $enabled=true, string $purpose= 'default')
Enable or disable a notification delivery method.
Definition: ElggUser.php:405
if($email instanceof\Elgg\Email) $object
Definition: body.php:24
ban(string $reason= '')
Ban this user.
Definition: ElggUser.php:132
getNotificationSettings(string $purpose= 'default')
Returns users&#39;s notification settings [ &#39;email&#39; => true, // enabled &#39;ajax&#39; => false, // disabled ]
Definition: ElggUser.php:428
isAdmin()
Is this user admin?
Definition: ElggUser.php:187
isValidated()
Gets the validation status of a user.
Definition: ElggUser.php:283
setPassword(string $password)
Set the necessary metadata to store a hash of the user&#39;s password.
Definition: ElggUser.php:386
removeAdmin()
Remove the admin flag for user.
Definition: ElggUser.php:218
_elgg_services()
Get the global service provider.
Definition: elgglib.php:346
const ACCESS_PUBLIC
Definition: constants.php:12
isBanned()
Is this user banned or not?
Definition: ElggUser.php:178
__set($name, $value)
{}
Definition: ElggUser.php:88
$methods
Definition: subscribe.php:8
elgg_get_logged_in_user_guid()
Return the current logged in user by guid.
Definition: sessions.php:34
getDisplayName()
Get the entity&#39;s display name.
Definition: ElggEntity.php:312
$guid
Reset an ElggUpgrade.
Definition: reset.php:6
Bundled plugins(the contents of the"/mod"directory) are available only under the GPLv2 license.The remainder of the project is available under either MIT or GPLv2.Both licenses can be found below.More info and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two distribute and or modify the software for each author s protection and we want to make certain that everyone understands that there is no warranty for this free software If the software is modified by someone else and passed we want its recipients to know that what they have is not the so that any problems introduced by others will not reflect on the original authors reputations any free program is threatened constantly by software patents We wish to avoid the danger that redistributors of a free program will individually obtain patent in effect making the program proprietary To prevent we have made it clear that any patent must be licensed for everyone s free use or not licensed at all The precise terms and conditions for distribution and modification follow GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR DISTRIBUTION AND MODIFICATION This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License The refers to any such program or and a work based on the Program means either the Program or any derivative work under copyright a work containing the Program or a portion of either verbatim or with modifications and or translated into another language(Hereinafter, translation is included without limitation in the term"modification".) Each licensee is addressed as"you".Activities other than copying