Elgg  Version 5.1
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  $time = $this->getCurrentTime()->getTimestamp();
242 
243  if ($this->last_login == $time) {
244  // no change required
245  return;
246  }
247 
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  }
254 
260  public function setLastAction(): void {
261 
262  $time = $this->getCurrentTime()->getTimestamp();
263 
264  if ($this->last_action == $time) {
265  // no change required
266  return;
267  }
268 
269  $user = $this;
270 
271  elgg_register_event_handler('shutdown', 'system', function () use ($user, $time) {
272  // these writes actually work, we just type hint read-only.
273  $user->prev_last_action = $user->last_action;
274 
275  $user->updateLastAction($time);
276  });
277  }
278 
284  public function isValidated(): ?bool {
285  if (!isset($this->validated)) {
286  return null;
287  }
288 
289  return (bool) $this->validated;
290  }
291 
300  public function setValidationStatus(bool $status, string $method = ''): void {
301  if ($status === $this->isValidated()) {
302  // no change needed
303  return;
304  }
305 
306  $this->validated = $status;
307 
308  if ($status) {
309  $this->validated_method = $method;
310  $this->validated_ts = time();
311 
312  // make sure the user is enabled
313  if (!$this->isEnabled()) {
314  $this->enable();
315  }
316 
317  // let the system know the user is validated
318  _elgg_services()->events->triggerAfter('validate', 'user', $this);
319  } else {
320  // invalidating
321  unset($this->validated_ts);
322  unset($this->validated_method);
323  _elgg_services()->events->triggerAfter('invalidate', 'user', $this);
324  }
325  }
326 
334  public function getGroups(array $options = []) {
335  $options['type'] = 'group';
336  $options['relationship'] = 'member';
337  $options['relationship_guid'] = $this->guid;
338 
339  return elgg_get_entities($options);
340  }
341 
345  public function getObjects(array $options = []) {
346  $options['type'] = 'object';
347  $options['owner_guid'] = $this->guid;
348 
349  return elgg_get_entities($options);
350  }
351 
359  public function getOwnerGUID(): int {
360  $owner_guid = parent::getOwnerGUID();
361  if ($owner_guid === 0) {
362  $owner_guid = (int) $this->guid;
363  }
364 
365  return $owner_guid;
366  }
367 
371  protected function prepareObject(\Elgg\Export\Entity $object) {
372  $object = parent::prepareObject($object);
373  $object->name = $this->getDisplayName();
374  $object->username = $this->username;
375  $object->language = $this->language;
376  unset($object->read_access);
377  return $object;
378  }
379 
388  public function setPassword(string $password): void {
389  $this->setMetadata('password_hash', _elgg_services()->passwords->generateHash($password));
390  if ($this->guid === elgg_get_logged_in_user_guid()) {
391  // update the session user token, so this session remains valid
392  // other sessions for this user will be invalidated
393  _elgg_services()->session_manager->setUserToken();
394  }
395  }
396 
407  public function setNotificationSetting(string $method, bool $enabled = true, string $purpose = 'default'): bool {
408  if (empty($purpose)) {
409  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
410  }
411 
412  $this->{"notification:{$purpose}:{$method}"} = (int) $enabled;
413  return $this->save();
414  }
415 
430  public function getNotificationSettings(string $purpose = 'default'): array {
431  if (empty($purpose)) {
432  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
433  }
434 
435  $settings = [];
436 
437  $methods = _elgg_services()->notifications->getMethods();
438  foreach ($methods as $method) {
439  if ($purpose !== 'default' && !isset($this->{"notification:{$purpose}:{$method}"})) {
440  // fallback to the default settings
441  $settings[$method] = (bool) $this->{"notification:default:{$method}"};
442  } else {
443  $settings[$method] = (bool) $this->{"notification:{$purpose}:{$method}"};
444  }
445  }
446 
447  return $settings;
448  }
449 
453  public function delete(bool $recursive = true): bool {
454  $result = parent::delete($recursive);
455  if ($result) {
456  // cleanup remember me cookie records
457  _elgg_services()->users_remember_me_cookies_table->deleteAllHashes($this);
458  }
459 
460  return $result;
461  }
462 
473  public function getPluginSetting(string $plugin_id, string $name, $default = null) {
474  $plugin = _elgg_services()->plugins->get($plugin_id);
475  if ($plugin instanceof \ElggPlugin) {
476  $static_defaults = (array) $plugin->getStaticConfig('user_settings', []);
477 
478  $default = elgg_extract($name, $static_defaults, $default);
479  }
480 
481  return $this->psGetPluginSetting($plugin_id, $name, $default);
482  }
483 }
$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:299
const ELGG_DISABLE_SYSTEM_LOG
Definition: constants.php:134
setValidationStatus(bool $status, string $method= '')
Set the validation status for a user.
Definition: ElggUser.php:300
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:473
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:16
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:371
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
const ELGG_IGNORE_ACCESS
elgg_call() flags
Definition: constants.php:130
$owner_guid
getObjects(array $options=[])
{}
Definition: ElggUser.php:345
if(!$user||!$user->canEdit()) $password
setLastAction()
Sets the last action time of the given user to right now.
Definition: ElggUser.php:260
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
$user
Definition: ban.php:7
getOwnerGUID()
Get a user&#39;s owner GUID.
Definition: ElggUser.php:359
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:334
setNotificationSetting(string $method, bool $enabled=true, string $purpose= 'default')
Enable or disable a notification delivery method.
Definition: ElggUser.php:407
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:430
isAdmin()
Is this user admin?
Definition: ElggUser.php:187
isValidated()
Gets the validation status of a user.
Definition: ElggUser.php:284
setPassword(string $password)
Set the necessary metadata to store a hash of the user&#39;s password.
Definition: ElggUser.php:388
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