Elgg  Version 4.3
ElggUser.php
Go to the documentation of this file.
1 <?php
2 
9 
29 class ElggUser extends \ElggEntity {
30 
31  use Friends;
32  use PluginSettings {
33  setPluginSetting as protected psSetPluginSetting;
35  }
36  use ProfileData;
37 
41  protected function initializeAttributes() {
42  parent::initializeAttributes();
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 
61  public function getType() {
62  return 'user';
63  }
64 
73  public function getLanguage($fallback = null) {
74  if (!empty($this->language)) {
75  return $this->language;
76  }
77  if ($fallback !== null) {
78  return $fallback;
79  }
80  return elgg_get_config('language');
81  }
82 
86  public function __set($name, $value) {
87  switch ($name) {
88  case 'salt':
89  case 'password':
90  _elgg_services()->logger->error("User entities no longer contain {$name}");
91  return;
92  case 'password_hash':
93  _elgg_services()->logger->error("password_hash is a readonly attribute.");
94  return;
95  case 'email':
96  try {
97  _elgg_services()->accounts->assertValidEmail($value);
98  } catch (RegistrationException $ex) {
99  throw new InvalidParameterException($ex->getMessage(), $ex->getCode(), $ex);
100  }
101  break;
102  case 'username':
103  try {
104  _elgg_services()->accounts->assertValidUsername($value);
105  } catch (RegistrationException $ex) {
106  throw new InvalidParameterException($ex->getMessage(), $ex->getCode(), $ex);
107  }
108  $existing_user = get_user_by_username($value);
109  if ($existing_user && ($existing_user->guid !== $this->guid)) {
110  throw new InvalidParameterException("{$name} is supposed to be unique for ElggUser");
111  }
112  break;
113  case 'admin':
114  throw new ElggInvalidArgumentException(_elgg_services()->translator->translate('ElggUser:Error:SetAdmin', ['makeAdmin() / removeAdmin()']));
115  case 'banned':
116  throw new ElggInvalidArgumentException(_elgg_services()->translator->translate('ElggUser:Error:SetBanned', ['ban() / unban()']));
117  }
118 
119  parent::__set($name, $value);
120  }
121 
129  public function ban($reason = '') {
130 
131  if (!$this->canEdit()) {
132  return false;
133  }
134 
135  if (!_elgg_services()->events->trigger('ban', 'user', $this)) {
136  return false;
137  }
138 
139  $this->ban_reason = $reason;
140  $this->setMetadata('banned', 'yes');
141 
142  $this->invalidateCache();
143 
144  return true;
145  }
146 
152  public function unban() {
153 
154  if (!$this->canEdit()) {
155  return false;
156  }
157 
158  if (!_elgg_services()->events->trigger('unban', 'user', $this)) {
159  return false;
160  }
161 
162  unset($this->ban_reason);
163  $this->setMetadata('banned', 'no');
164 
165  $this->invalidateCache();
166 
167  return true;
168  }
169 
175  public function isBanned() {
176  return $this->banned === 'yes';
177  }
178 
184  public function isAdmin() {
185  return $this->admin === 'yes';
186  }
187 
193  public function makeAdmin() {
194 
195  if ($this->isAdmin()) {
196  return true;
197  }
198 
199  if (!_elgg_services()->events->trigger('make_admin', 'user', $this)) {
200  return false;
201  }
202 
203  $this->setMetadata('admin', 'yes');
204 
205  $this->invalidateCache();
206 
207  return true;
208  }
209 
215  public function removeAdmin() {
216 
217  if (!$this->isAdmin()) {
218  return true;
219  }
220 
221  if (!_elgg_services()->events->trigger('remove_admin', 'user', $this)) {
222  return false;
223  }
224 
225  $this->setMetadata('admin', 'no');
226 
227  $this->invalidateCache();
228 
229  return true;
230  }
231 
237  public function setLastLogin() {
238 
239  $time = $this->getCurrentTime()->getTimestamp();
240 
241  if ($this->last_login == $time) {
242  // no change required
243  return;
244  }
245 
246  // these writes actually work, we just type hint read-only.
247  $this->prev_last_login = $this->last_login;
248  $this->last_login = $time;
249  }
250 
256  public function setLastAction() {
257 
258  $time = $this->getCurrentTime()->getTimestamp();
259 
260  if ($this->last_action == $time) {
261  // no change required
262  return;
263  }
264 
265  $user = $this;
266 
267  elgg_register_event_handler('shutdown', 'system', function () use ($user, $time) {
268  // these writes actually work, we just type hint read-only.
269  $user->prev_last_action = $user->last_action;
270 
271  $user->updateLastAction($time);
272  });
273  }
274 
280  public function isValidated() {
281  if (!isset($this->validated)) {
282  return null;
283  }
284  return (bool) $this->validated;
285  }
286 
294  public function setValidationStatus(bool $status, string $method = ''): void {
295  if ($status === $this->isValidated()) {
296  // no change needed
297  return;
298  }
299 
300  $this->validated = $status;
301 
302  if ($status) {
303  $this->validated_method = $method;
304  $this->validated_ts = time();
305 
306  // make sure the user is enabled
307  if (!$this->isEnabled()) {
308  $this->enable();
309  }
310 
311  // let the system know the user is validated
312  _elgg_services()->events->triggerAfter('validate', 'user', $this);
313  } else {
314  // invalidating
315  unset($this->validated_ts);
316  unset($this->validated_method);
317  _elgg_services()->events->triggerAfter('invalidate', 'user', $this);
318  }
319  }
320 
328  public function getGroups(array $options = []) {
329  $options['type'] = 'group';
330  $options['relationship'] = 'member';
331  $options['relationship_guid'] = $this->guid;
332 
333  return elgg_get_entities($options);
334  }
335 
339  public function getObjects(array $options = []) {
340  $options['type'] = 'object';
341  $options['owner_guid'] = $this->guid;
342 
343  return elgg_get_entities($options);
344  }
345 
353  public function getOwnerGUID() {
354  if ($this->owner_guid == 0) {
355  return $this->guid;
356  }
357 
358  return $this->owner_guid;
359  }
360 
364  protected function prepareObject(\Elgg\Export\Entity $object) {
365  $object = parent::prepareObject($object);
366  $object->name = $this->getDisplayName();
367  $object->username = $this->username;
368  $object->language = $this->language;
369  unset($object->read_access);
370  return $object;
371  }
372 
380  public function setPassword($password) {
381  $this->setMetadata('password_hash', _elgg_services()->passwords->generateHash($password));
382  if ($this->guid === elgg_get_logged_in_user_guid()) {
383  // update the session user token, so this session remains valid
384  // other sessions for this user will be invalidated
385  _elgg_services()->session->setUserToken();
386  }
387  }
388 
399  public function setNotificationSetting(string $method, bool $enabled = true, string $purpose = 'default') {
400  if (empty($purpose)) {
401  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
402  }
403 
404  $this->{"notification:{$purpose}:{$method}"} = (int) $enabled;
405  return $this->save();
406  }
407 
422  public function getNotificationSettings(string $purpose = 'default') {
423  if (empty($purpose)) {
424  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
425  }
426 
427  $settings = [];
428 
429  $methods = _elgg_services()->notifications->getMethods();
430  foreach ($methods as $method) {
431  if ($purpose !== 'default' && !isset($this->{"notification:{$purpose}:{$method}"})) {
432  // fallback to the default settings
433  $settings[$method] = (bool) $this->{"notification:default:{$method}"};
434  } else {
435  $settings[$method] = (bool) $this->{"notification:{$purpose}:{$method}"};
436  }
437  }
438 
439  return $settings;
440 
441  }
442 
446  public function delete($recursive = true) {
447  $result = parent::delete($recursive);
448  if ($result) {
449  // cleanup remember me cookie records
450  _elgg_services()->users_remember_me_cookies_table->deleteAllHashes($this);
451  }
452 
453  return $result;
454  }
455 
466  public function setPluginSetting(string $plugin_id, string $name, $value): bool {
467  $value = _elgg_services()->hooks->triggerDeprecated('usersetting', 'plugin', [
468  'user' => $this,
469  'plugin' => _elgg_services()->plugins->get($plugin_id),
470  'plugin_id' => $plugin_id,
471  'name' => $name,
472  'value' => $value,
473  ], $value, "Please user the plugin hook 'plugin_settings', '{$this->getType()}'", '4.0');
474 
475  return $this->psSetPluginSetting($plugin_id, $name, $value);
476  }
477 
488  public function getPluginSetting(string $plugin_id, string $name, $default = null): string {
489  $plugin = _elgg_services()->plugins->get($plugin_id);
490  if ($plugin instanceof \ElggPlugin) {
491  $static_defaults = (array) $plugin->getStaticConfig('user_settings', []);
492 
493  $default = elgg_extract($name, $static_defaults, $default);
494  }
495 
496  return $this->psGetPluginSetting($plugin_id, $name, $default);
497  }
498 }
$default
Definition: checkbox.php:31
enable($recursive=true)
Enable the entity.
setValidationStatus(bool $status, string $method= '')
Set the validation status for a user.
Definition: ElggUser.php:294
$plugin
getLanguage($fallback=null)
Get user language or default to site language.
Definition: ElggUser.php:73
$last_login
Definition: online.php:22
makeAdmin()
Make the user an admin.
Definition: ElggUser.php:193
getPluginSetting(string $plugin_id, string $name, $default=null)
Get a plugin setting.
Definition: ElggUser.php:488
Elgg registration action.
setPassword($password)
Set the necessary metadata to store a hash of the user&#39;s password.
Definition: ElggUser.php:380
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.
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
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:237
Could not register a new user for whatever reason.
initializeAttributes()
{}
Definition: ElggUser.php:41
prepareObject(\Elgg\Export\Entity $object)
{}
Definition: ElggUser.php:364
canEdit($user_guid=0)
Can a user edit this entity?
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
$value
Definition: generic.php:51
get_user_by_username($username)
Get user by username.
Definition: users.php:41
getCurrentTime($modifier= '')
Get the (cloned) time.
Definition: TimeUsing.php:25
$owner_guid
getObjects(array $options=[])
{}
Definition: ElggUser.php:339
if(!$user||!$user->canEdit()) $password
setLastAction()
Sets the last action time of the given user to right now.
Definition: ElggUser.php:256
unban()
Unban this user.
Definition: ElggUser.php:152
$language
Definition: useradd.php:19
elgg_get_entities(array $options=[])
Fetches/counts entities or performs a calculation on their properties.
Definition: entities.php:545
$enabled
Sample cli installer script.
setPluginSetting(string $plugin_id, string $name, $value)
Save a plugin setting.
Definition: ElggUser.php:466
$user
Definition: ban.php:7
ban($reason= '')
Ban this user.
Definition: ElggUser.php:129
getOwnerGUID()
Get a user&#39;s owner GUID.
Definition: ElggUser.php:353
isEnabled()
Is this entity enabled?
elgg_extract($key, $array, $default=null, $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:547
$purpose
Definition: record.php:16
getType()
{}
Definition: ElggUser.php:61
setMetadata($name, $value, $value_type= '', $multiple=false)
Set metadata on this entity.
Definition: ElggEntity.php:376
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Definition: elgglib.php:126
getGroups(array $options=[])
Gets the user&#39;s groups.
Definition: ElggUser.php:328
setNotificationSetting(string $method, bool $enabled=true, string $purpose= 'default')
Enable or disable a notification delivery method.
Definition: ElggUser.php:399
if($email instanceof\Elgg\Email) $object
Definition: body.php:24
getNotificationSettings(string $purpose= 'default')
Returns users&#39;s notification settings [ &#39;email&#39; => true, // enabled &#39;ajax&#39; => false, // disabled ]
Definition: ElggUser.php:422
isAdmin()
Is this user admin?
Definition: ElggUser.php:184
isValidated()
Gets the validation status of a user.
Definition: ElggUser.php:280
removeAdmin()
Remove the admin flag for user.
Definition: ElggUser.php:215
_elgg_services()
Get the global service provider.
Definition: elgglib.php:638
const ACCESS_PUBLIC
Definition: constants.php:14
isBanned()
Is this user banned or not?
Definition: ElggUser.php:175
__set($name, $value)
{}
Definition: ElggUser.php:86
$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:318
elgg_get_config($name, $default=null)
Get an Elgg configuration value.
$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
getPluginSetting as psGetPluginSetting
Definition: ElggUser.php:34