Elgg  Version 6.2
ElggUser.php
Go to the documentation of this file.
1 <?php
2 
3 use Elgg\Exceptions\InvalidArgumentException as ElggInvalidArgumentException;
5 use Elgg\Traits\Entity\Friends;
6 use Elgg\Traits\Entity\PluginSettings;
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 
42  $this->attributes['type'] = 'user';
43  $this->attributes['subtype'] = 'user';
44 
45  $this->attributes['access_id'] = ACCESS_PUBLIC;
46  $this->attributes['owner_guid'] = 0; // Users aren't owned by anyone, even if they are admin created.
47  $this->attributes['container_guid'] = 0; // Users aren't contained by anyone, even if they are admin created.
48 
49  // Before Elgg 3.0 this was handled by database logic
50  $this->setMetadata('banned', 'no');
51  $this->setMetadata('admin', 'no');
52  $this->language = elgg_get_config('language');
53  $this->prev_last_action = 0;
54  $this->last_login = 0;
55  $this->prev_last_login = 0;
56  }
57 
66  public function getLanguage(string $fallback = null): string {
67  if (!empty($this->language)) {
68  return $this->language;
69  }
70 
71  if ($fallback !== null) {
72  return $fallback;
73  }
74 
75  return elgg_get_config('language');
76  }
77 
83  public function __set($name, $value) {
84  switch ($name) {
85  case 'salt':
86  case 'password':
87  _elgg_services()->logger->error("User entities no longer contain {$name}");
88  return;
89  case 'password_hash':
90  _elgg_services()->logger->error('password_hash is a readonly attribute.');
91  return;
92  case 'email':
93  try {
94  _elgg_services()->accounts->assertValidEmail($value);
95  } catch (RegistrationException $ex) {
96  throw new ElggInvalidArgumentException($ex->getMessage(), $ex->getCode(), $ex);
97  }
98  break;
99  case 'username':
100  try {
101  _elgg_services()->accounts->assertValidUsername($value);
102  } catch (RegistrationException $ex) {
103  throw new ElggInvalidArgumentException($ex->getMessage(), $ex->getCode(), $ex);
104  }
105 
107  if ($existing_user instanceof \ElggUser && ($existing_user->guid !== $this->guid)) {
108  throw new ElggInvalidArgumentException("{$name} is supposed to be unique for ElggUser");
109  }
110  break;
111  case 'admin':
112  throw new ElggInvalidArgumentException(_elgg_services()->translator->translate('ElggUser:Error:SetAdmin', ['makeAdmin() / removeAdmin()']));
113  case 'banned':
114  throw new ElggInvalidArgumentException(_elgg_services()->translator->translate('ElggUser:Error:SetBanned', ['ban() / unban()']));
115  }
116 
117  parent::__set($name, $value);
118  }
119 
127  public function ban(string $reason = ''): bool {
128 
129  if (!$this->canEdit()) {
130  return false;
131  }
132 
133  if (!_elgg_services()->events->trigger('ban', 'user', $this)) {
134  return false;
135  }
136 
137  $this->ban_reason = $reason;
138  $this->setMetadata('banned', 'yes');
139 
140  $this->invalidateCache();
141 
142  return true;
143  }
144 
150  public function unban(): bool {
151 
152  if (!$this->canEdit()) {
153  return false;
154  }
155 
156  if (!_elgg_services()->events->trigger('unban', 'user', $this)) {
157  return false;
158  }
159 
160  unset($this->ban_reason);
161  $this->setMetadata('banned', 'no');
162 
163  $this->invalidateCache();
164 
165  return true;
166  }
167 
173  public function isBanned(): bool {
174  return $this->banned === 'yes';
175  }
176 
182  public function isAdmin(): bool {
183  return $this->admin === 'yes';
184  }
185 
191  public function makeAdmin(): bool {
192 
193  if ($this->isAdmin()) {
194  return true;
195  }
196 
197  if (!_elgg_services()->events->trigger('make_admin', 'user', $this)) {
198  return false;
199  }
200 
201  $this->setMetadata('admin', 'yes');
202 
203  $this->invalidateCache();
204 
205  return true;
206  }
207 
213  public function removeAdmin(): bool {
214 
215  if (!$this->isAdmin()) {
216  return true;
217  }
218 
219  if (!_elgg_services()->events->trigger('remove_admin', 'user', $this)) {
220  return false;
221  }
222 
223  $this->setMetadata('admin', 'no');
224 
225  $this->invalidateCache();
226 
227  return true;
228  }
229 
235  public function setLastLogin(): void {
236  $time = $this->getCurrentTime()->getTimestamp();
237 
238  if ($this->last_login == $time) {
239  // no change required
240  return;
241  }
242 
244  // these writes actually work, we just type hint read-only.
245  $this->prev_last_login = $this->last_login;
246  $this->last_login = $time;
247  });
248  }
249 
255  public function setLastAction(): void {
256 
257  $time = $this->getCurrentTime()->getTimestamp();
258 
259  if ($this->last_action == $time) {
260  // no change required
261  return;
262  }
263 
264  $user = $this;
265 
266  elgg_register_event_handler('shutdown', 'system', function () use ($user, $time) {
267  // these writes actually work, we just type hint read-only.
268  $user->prev_last_action = $user->last_action;
269 
270  $user->updateLastAction($time);
271  });
272  }
273 
279  public function isValidated(): ?bool {
280  if (!isset($this->validated)) {
281  return null;
282  }
283 
284  return (bool) $this->validated;
285  }
286 
295  public function setValidationStatus(bool $status, string $method = ''): void {
296  if ($status === $this->isValidated()) {
297  // no change needed
298  return;
299  }
300 
301  $this->validated = $status;
302 
303  if ($status) {
304  $this->validated_method = $method;
305  $this->validated_ts = time();
306 
307  // make sure the user is enabled
308  if (!$this->isEnabled()) {
309  $this->enable();
310  }
311 
312  // let the system know the user is validated
313  _elgg_services()->events->triggerAfter('validate', 'user', $this);
314  } else {
315  // invalidating
316  unset($this->validated_ts);
317  unset($this->validated_method);
318  _elgg_services()->events->triggerAfter('invalidate', 'user', $this);
319  }
320  }
321 
329  public function getGroups(array $options = []) {
330  $options['type'] = 'group';
331  $options['relationship'] = 'member';
332  $options['relationship_guid'] = $this->guid;
333 
334  return elgg_get_entities($options);
335  }
336 
340  public function getObjects(array $options = []) {
341  $options['type'] = 'object';
342  $options['owner_guid'] = $this->guid;
343 
344  return elgg_get_entities($options);
345  }
346 
354  public function getOwnerGUID(): int {
355  $owner_guid = parent::getOwnerGUID();
356  if ($owner_guid === 0) {
357  $owner_guid = (int) $this->guid;
358  }
359 
360  return $owner_guid;
361  }
362 
366  protected function prepareObject(\Elgg\Export\Entity $object) {
367  $object = parent::prepareObject($object);
368  $object->name = $this->getDisplayName();
369  $object->username = $this->username;
370  $object->language = $this->language;
371  unset($object->read_access);
372  return $object;
373  }
374 
383  public function setPassword(string $password): void {
384  $this->setMetadata('password_hash', _elgg_services()->passwords->generateHash($password));
385  if ($this->guid === elgg_get_logged_in_user_guid()) {
386  // update the session user token, so this session remains valid
387  // other sessions for this user will be invalidated
388  _elgg_services()->session_manager->setUserToken();
389  }
390  }
391 
402  public function setNotificationSetting(string $method, bool $enabled = true, string $purpose = 'default'): bool {
403  if (empty($purpose)) {
404  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
405  }
406 
407  $this->{"notification:{$purpose}:{$method}"} = (int) $enabled;
408  return $this->save();
409  }
410 
425  public function getNotificationSettings(string $purpose = 'default'): array {
426  if (empty($purpose)) {
427  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
428  }
429 
430  $settings = [];
431 
432  $methods = _elgg_services()->notifications->getMethods();
433  foreach ($methods as $method) {
434  if ($purpose !== 'default' && !isset($this->{"notification:{$purpose}:{$method}"})) {
435  // fallback to the default settings
436  $settings[$method] = (bool) $this->{"notification:default:{$method}"};
437  } else {
438  $settings[$method] = (bool) $this->{"notification:{$purpose}:{$method}"};
439  }
440  }
441 
442  return $settings;
443  }
444 
448  public function persistentDelete(bool $recursive = true): bool {
449  $result = parent::persistentDelete($recursive);
450  if ($result) {
451  // cleanup remember me cookie records
452  _elgg_services()->users_remember_me_cookies_table->deleteAllHashes($this);
453  }
454 
455  return $result;
456  }
457 
469  public function getPluginSetting(string $plugin_id, string $name, $default = null) {
470  $plugin = _elgg_services()->plugins->get($plugin_id);
471  if (!$plugin instanceof \ElggPlugin || !$plugin->isActive()) {
472  return $default;
473  }
474 
475  $static_defaults = (array) $plugin->getStaticConfig('user_settings', []);
476 
477  $default = elgg_extract($name, $static_defaults, $default);
478 
479  return $this->psGetPluginSetting($plugin_id, $name, $default);
480  }
481 }
$guid
Reset an ElggUpgrade.
Definition: reset.php:6
if(! $user instanceof \ElggUser) if($user->email===$email) $existing_user
$username
Definition: delete.php:23
if(! $user||! $user->canDelete()) $name
Definition: delete.php:22
$plugin_id
Remove all user and plugin settings from the give plugin ID.
Definition: remove.php:8
$language
Definition: useradd.php:17
return[ 'admin/delete_admin_notices'=>['access'=> 'admin'], 'admin/menu/save'=>['access'=> 'admin'], 'admin/plugins/activate'=>['access'=> 'admin'], 'admin/plugins/activate_all'=>['access'=> 'admin'], 'admin/plugins/deactivate'=>['access'=> 'admin'], 'admin/plugins/deactivate_all'=>['access'=> 'admin'], 'admin/plugins/set_priority'=>['access'=> 'admin'], 'admin/security/security_txt'=>['access'=> 'admin'], 'admin/security/settings'=>['access'=> 'admin'], 'admin/security/regenerate_site_secret'=>['access'=> 'admin'], 'admin/site/cache/invalidate'=>['access'=> 'admin'], 'admin/site/flush_cache'=>['access'=> 'admin'], 'admin/site/icons'=>['access'=> 'admin'], 'admin/site/set_maintenance_mode'=>['access'=> 'admin'], 'admin/site/set_robots'=>['access'=> 'admin'], 'admin/site/theme'=>['access'=> 'admin'], 'admin/site/unlock_upgrade'=>['access'=> 'admin'], 'admin/site/settings'=>['access'=> 'admin'], 'admin/upgrade'=>['access'=> 'admin'], 'admin/upgrade/reset'=>['access'=> 'admin'], 'admin/user/ban'=>['access'=> 'admin'], 'admin/user/bulk/ban'=>['access'=> 'admin'], 'admin/user/bulk/delete'=>['access'=> 'admin'], 'admin/user/bulk/unban'=>['access'=> 'admin'], 'admin/user/bulk/validate'=>['access'=> 'admin'], 'admin/user/change_email'=>['access'=> 'admin'], 'admin/user/delete'=>['access'=> 'admin'], 'admin/user/login_as'=>['access'=> 'admin'], 'admin/user/logout_as'=>[], 'admin/user/makeadmin'=>['access'=> 'admin'], 'admin/user/resetpassword'=>['access'=> 'admin'], 'admin/user/removeadmin'=>['access'=> 'admin'], 'admin/user/unban'=>['access'=> 'admin'], 'admin/user/validate'=>['access'=> 'admin'], 'annotation/delete'=>[], 'avatar/upload'=>[], 'comment/save'=>[], 'diagnostics/download'=>['access'=> 'admin'], 'entity/chooserestoredestination'=>[], 'entity/delete'=>[], 'entity/mute'=>[], 'entity/restore'=>[], 'entity/subscribe'=>[], 'entity/trash'=>[], 'entity/unmute'=>[], 'entity/unsubscribe'=>[], 'login'=>['access'=> 'logged_out'], 'logout'=>[], 'notifications/mute'=>['access'=> 'public'], 'plugins/settings/remove'=>['access'=> 'admin'], 'plugins/settings/save'=>['access'=> 'admin'], 'plugins/usersettings/save'=>[], 'register'=>['access'=> 'logged_out', 'middleware'=>[\Elgg\Router\Middleware\RegistrationAllowedGatekeeper::class,],], 'river/delete'=>[], 'settings/notifications'=>[], 'settings/notifications/subscriptions'=>[], 'user/changepassword'=>['access'=> 'public'], 'user/requestnewpassword'=>['access'=> 'public'], 'useradd'=>['access'=> 'admin'], 'usersettings/save'=>[], 'widgets/add'=>[], 'widgets/delete'=>[], 'widgets/move'=>[], 'widgets/save'=>[],]
Definition: actions.php:73
if(! $annotation instanceof ElggAnnotation) $time
Definition: time.php:20
$user
Definition: ban.php:7
Plugin class containing helper functions for plugin activation/deactivation, dependency checking capa...
Definition: ElggPlugin.php:17
isAdmin()
Is this user admin?
Definition: ElggUser.php:182
removeAdmin()
Remove the admin flag for user.
Definition: ElggUser.php:213
getPluginSetting(string $plugin_id, string $name, $default=null)
Get a plugin setting.
Definition: ElggUser.php:469
initializeAttributes()
{Initialize the attributes array.This is vital to distinguish between metadata and base parameters....
Definition: ElggUser.php:39
getObjects(array $options=[])
{}
Definition: ElggUser.php:340
persistentDelete(bool $recursive=true)
{Permanently delete the entity from the database.If true (default) then all entities which are owned ...
Definition: ElggUser.php:448
__set($name, $value)
{Set an attribute or metadata value for this entity.Anything that is not an attribute is saved as met...
Definition: ElggUser.php:83
unban()
Unban this user.
Definition: ElggUser.php:150
isValidated()
Gets the validation status of a user.
Definition: ElggUser.php:279
getOwnerGUID()
Get a user's owner GUID.
Definition: ElggUser.php:354
setNotificationSetting(string $method, bool $enabled=true, string $purpose='default')
Enable or disable a notification delivery method.
Definition: ElggUser.php:402
isBanned()
Is this user banned or not?
Definition: ElggUser.php:173
setPassword(string $password)
Set the necessary metadata to store a hash of the user's password.
Definition: ElggUser.php:383
makeAdmin()
Make the user an admin.
Definition: ElggUser.php:191
ban(string $reason='')
Ban this user.
Definition: ElggUser.php:127
setValidationStatus(bool $status, string $method='')
Set the validation status for a user.
Definition: ElggUser.php:295
setLastAction()
Sets the last action time of the given user to right now.
Definition: ElggUser.php:255
prepareObject(\Elgg\Export\Entity $object)
{Prepare an object copy for toObject()Object representation of the entity\Elgg\Export\Entity}
Definition: ElggUser.php:366
getGroups(array $options=[])
Gets the user's groups.
Definition: ElggUser.php:329
setLastLogin()
Sets the last logon time of the user to right now.
Definition: ElggUser.php:235
getNotificationSettings(string $purpose='default')
Returns users's notification settings [ 'email' => true, // enabled 'ajax' => false,...
Definition: ElggUser.php:425
getLanguage(string $fallback=null)
Get user language or default to site language.
Definition: ElggUser.php:66
Could not register a new user for whatever reason.
Exception thrown if an argument is not of the expected type.
$owner_guid
elgg_get_config(string $name, $default=null)
Get an Elgg configuration value.
const ELGG_IGNORE_ACCESS
elgg_call() flags
Definition: constants.php:121
const ELGG_DISABLE_SYSTEM_LOG
Definition: constants.php:125
const ACCESS_PUBLIC
Definition: constants.php:12
if($who_can_change_language==='nobody') elseif($who_can_change_language==='admin_only' &&!elgg_is_admin_logged_in()) $options
Definition: language.php:20
$last_login
Definition: online.php:17
if($email instanceof \Elgg\Email) $object
Definition: body.php:24
_elgg_services()
Get the global service provider.
Definition: elgglib.php:353
elgg_call(int $flags, Closure $closure)
Calls a callable autowiring the arguments using public DI services and applying logic based on flags.
Definition: elgglib.php:306
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:256
elgg_get_user_by_username(string $username, bool $try_email=false)
Get a user by username.
Definition: users.php:31
elgg_get_entities(array $options=[])
Fetches/counts entities or performs a calculation on their properties.
Definition: entities.php:507
$value
Definition: generic.php:51
$default
Definition: checkbox.php:30
elgg_register_event_handler(string $event, string $type, callable|string $callback, int $priority=500)
Helper functions for event handling.
Definition: events.php:48
setMetadata(string $name, mixed $value, string $value_type='', bool $multiple=false)
Set metadata on this entity.
Definition: Metadata.php:78
trait ProfileData
Adds methods to save profile data to an ElggEntity.
Definition: ProfileData.php:11
if(! $user||! $user->canEdit()) $password
if(parse_url(elgg_get_site_url(), PHP_URL_PATH) !=='/') if(file_exists(elgg_get_root_path() . 'robots.txt'))
Set robots.txt.
Definition: robots.php:10
elgg_get_logged_in_user_guid()
Return the current logged in user by guid.
Definition: sessions.php:34
$plugin
$purpose
Definition: record.php:16
$methods
Definition: subscribe.php:8
if($type !='user') $settings
Definition: save.php:16