Elgg  Version 4.x
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  }
383 
394  public function setNotificationSetting(string $method, bool $enabled = true, string $purpose = 'default') {
395  if (empty($purpose)) {
396  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
397  }
398 
399  $this->{"notification:{$purpose}:{$method}"} = (int) $enabled;
400  return $this->save();
401  }
402 
417  public function getNotificationSettings(string $purpose = 'default') {
418  if (empty($purpose)) {
419  throw new ElggInvalidArgumentException(__METHOD__ . ' requires $purpose to be set to a non-empty string');
420  }
421 
422  $settings = [];
423 
424  $methods = _elgg_services()->notifications->getMethods();
425  foreach ($methods as $method) {
426  if ($purpose !== 'default' && !isset($this->{"notification:{$purpose}:{$method}"})) {
427  // fallback to the default settings
428  $settings[$method] = (bool) $this->{"notification:default:{$method}"};
429  } else {
430  $settings[$method] = (bool) $this->{"notification:{$purpose}:{$method}"};
431  }
432  }
433 
434  return $settings;
435 
436  }
437 
441  public function delete($recursive = true) {
442  $result = parent::delete($recursive);
443  if ($result) {
444  // cleanup remember me cookie records
445  _elgg_services()->users_remember_me_cookies_table->deleteAllHashes($this);
446  }
447 
448  return $result;
449  }
450 
461  public function setPluginSetting(string $plugin_id, string $name, $value): bool {
462  $value = _elgg_services()->hooks->triggerDeprecated('usersetting', 'plugin', [
463  'user' => $this,
464  'plugin' => _elgg_services()->plugins->get($plugin_id),
465  'plugin_id' => $plugin_id,
466  'name' => $name,
467  'value' => $value,
468  ], $value, "Please user the plugin hook 'plugin_settings', '{$this->getType()}'", '4.0');
469 
470  return $this->psSetPluginSetting($plugin_id, $name, $value);
471  }
472 
483  public function getPluginSetting(string $plugin_id, string $name, $default = null): string {
484  $plugin = _elgg_services()->plugins->get($plugin_id);
485  if ($plugin instanceof \ElggPlugin) {
486  $static_defaults = (array) $plugin->getStaticConfig('user_settings', []);
487 
488  $default = elgg_extract($name, $static_defaults, $default);
489  }
490 
491  return $this->psGetPluginSetting($plugin_id, $name, $default);
492  }
493 }
$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
if(!$user||!$user->canDelete()) $name
Definition: delete.php:22
$username
Definition: delete.php:23
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:483
Elgg registration action.
setPassword($password)
Set the necessary metadata to store a hash of the user&#39;s password.
Definition: ElggUser.php:380
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
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
$new_user language
Definition: useradd.php:58
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:461
$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:686
$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:394
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:417
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:777
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
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
getPluginSetting as psGetPluginSetting
Definition: ElggUser.php:34