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 
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 
106  $existing_user = elgg_get_user_by_username($value);
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 
468  public function getPluginSetting(string $plugin_id, string $name, $default = null) {
469  $plugin = _elgg_services()->plugins->get($plugin_id);
470  if ($plugin instanceof \ElggPlugin) {
471  $static_defaults = (array) $plugin->getStaticConfig('user_settings', []);
472 
473  $default = elgg_extract($name, $static_defaults, $default);
474  }
475 
476  return $this->psGetPluginSetting($plugin_id, $name, $default);
477  }
478 }
$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
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:304
const ELGG_DISABLE_SYSTEM_LOG
Definition: constants.php:125
setValidationStatus(bool $status, string $method= '')
Set the validation status for a user.
Definition: ElggUser.php:295
$plugin
$last_login
Definition: online.php:17
makeAdmin()
Make the user an admin.
Definition: ElggUser.php:191
getPluginSetting(string $plugin_id, string $name, $default=null)
Get a plugin setting.
Definition: ElggUser.php:468
elgg_get_config(string $name, $default=null)
Get an Elgg configuration value.
Elgg registration action.
Plugin class containing helper functions for plugin activation/deactivation, dependency checking capa...
Definition: ElggPlugin.php:17
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:31
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.
Definition: ElggEntity.php:950
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:235
Could not register a new user for whatever reason.
initializeAttributes()
{}
Definition: ElggUser.php:39
prepareObject(\Elgg\Export\Entity $object)
{}
Definition: ElggUser.php:366
if($type!= 'user') $settings
Definition: save.php:16
$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:397
$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
if($who_can_change_language=== 'nobody') elseif($who_can_change_language=== 'admin_only'&&!elgg_is_admin_logged_in()) $options
Definition: language.php:20
const ELGG_IGNORE_ACCESS
elgg_call() flags
Definition: constants.php:121
$owner_guid
getObjects(array $options=[])
{}
Definition: ElggUser.php:340
if(!$user||!$user->canEdit()) $password
setLastAction()
Sets the last action time of the given user to right now.
Definition: ElggUser.php:255
unban()
Unban this user.
Definition: ElggUser.php:150
$language
Definition: useradd.php:17
elgg_get_entities(array $options=[])
Fetches/counts entities or performs a calculation on their properties.
Definition: entities.php:507
getLanguage(string $fallback=null)
Get user language or default to site language.
Definition: ElggUser.php:66
$user
Definition: ban.php:7
setMetadata(string $name, mixed $value, string $value_type= '', bool $multiple=false)
Set metadata on this entity.
Definition: Metadata.php:78
getOwnerGUID()
Get a user&#39;s owner GUID.
Definition: ElggUser.php:354
isEnabled()
Is this entity enabled?
$purpose
Definition: record.php:16
getGroups(array $options=[])
Gets the user&#39;s groups.
Definition: ElggUser.php:329
setNotificationSetting(string $method, bool $enabled=true, string $purpose= 'default')
Enable or disable a notification delivery method.
Definition: ElggUser.php:402
if($email instanceof\Elgg\Email) $object
Definition: body.php:24
ban(string $reason= '')
Ban this user.
Definition: ElggUser.php:127
getNotificationSettings(string $purpose= 'default')
Returns users&#39;s notification settings [ &#39;email&#39; => true, // enabled &#39;ajax&#39; => false, // disabled ]
Definition: ElggUser.php:425
isAdmin()
Is this user admin?
Definition: ElggUser.php:182
isValidated()
Gets the validation status of a user.
Definition: ElggUser.php:279
setPassword(string $password)
Set the necessary metadata to store a hash of the user&#39;s password.
Definition: ElggUser.php:383
removeAdmin()
Remove the admin flag for user.
Definition: ElggUser.php:213
_elgg_services()
Get the global service provider.
Definition: elgglib.php:351
const ACCESS_PUBLIC
Definition: constants.php:12
isBanned()
Is this user banned or not?
Definition: ElggUser.php:173
__set($name, $value)
{}
Definition: ElggUser.php:83
$methods
Definition: subscribe.php:8
elgg_get_logged_in_user_guid()
Return the current logged in user by guid.
Definition: sessions.php:34
persistentDelete(bool $recursive=true)
{}
Definition: ElggUser.php:448
getDisplayName()
Get the entity&#39;s display name.
Definition: ElggEntity.php:306
$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