UserModel

Packagecraft.app.models
NamespaceCraft
Inheritanceclass UserModel » BaseElementModel » BaseModel » \CModel » \CComponent
Implements\ArrayAccess, \Traversable, \IteratorAggregate
Since1.0
Source Codecraft/app/models/UserModel.php

User model class.

Public Properties #

PropertyTypeDescriptionDefined By
allErrorsarrayReturns all errors in a single, flattened list, devoid of attribute names.BaseModel
ancestorsElementCriteriaModelReturns the element's ancestors.BaseElementModel
attributeConfigsarrayReturns this model's normalized attribute configs.BaseModel
attributesarrayReturns an array of attribute values.BaseModel
childrenElementCriteriaModelReturns the element's children.BaseElementModel
classHandlestringGet the class name, sans namespace and suffix.BaseModel
contentContentModelReturns the content for the element.BaseElementModel
contentFromPostarrayReturns the raw content from the post data, before it was passed through prepValueFromPost().BaseElementModel
contentPostLocationstring / nullReturns the location in POST that the content was pulled from.BaseElementModel
contentTablestringReturns the name of the table this element's content is stored in.BaseElementModel
cooldownEndTimeDateTime / nullReturns the time when the user will be over their cooldown period.UserModel
cpEditUrlstring / falseReturns the element's CP edit URL.UserModel
descendantsElementCriteriaModelReturns the element's descendants.BaseElementModel
elementTypestringReturns the type of element this is.BaseElementModel
errorsarrayReturns the errors for all attribute or a single attribute.\CModel
extraAttributeNamesarrayReturns a list of the names of the extra attributes that have been saved on this model, if it's not strict.BaseModel
fieldColumnPrefixstringReturns the field column prefix this element's content uses.BaseElementModel
fieldContextstringReturns the field context this element's content uses.BaseElementModel
fieldLayoutFieldLayoutModel / nullReturns the field layout used by this element.BaseElementModel
friendlyNamestring / nullGets the user's first name or username.UserModel
fullNamestring / nullGets the user's full name.UserModel
groupsarrayReturns the user's groups.UserModel
hasFreshContentboolReturns whether the element’s content is "fresh" (unsaved and without validation errors).BaseElementModel
iterator\CMapIteratorReturns an iterator for traversing the attributes in the model.\CModel
localesarrayReturns the locale IDs this element is available in.BaseElementModel
namestringReturns the user's full name or username.UserModel
nextElementCriteriaModel / nullReturns the next element relative to this one, from a given set of criteria.BaseElementModel
nextSiblingBaseElementModel / nullReturns the element's next sibling.BaseElementModel
parentBaseElementModel / nullGet the element's parent.BaseElementModel
parentsElementCriteriaModelReturns a new ElementCriteriaModel prepped to return this element's same-type parents.BaseElementModel
photoUrlstring / nullReturns the URL to the user's photo.UserModel
prevElementCriteriaModel / nullReturns the previous element relative to this one, from a given set of criteria.BaseElementModel
prevSiblingBaseElementModel / nullReturns the element's previous sibling.BaseElementModel
rawContentmixedReturns the raw content saved on this entity.BaseElementModel
refstring / nullReturns the reference string to this element.UserModel
remainingCooldownTimeDateInterval / nullReturns the remaining cooldown time for this user, if they've entered their password incorrectly too many times.UserModel
safeAttributeNamesarrayReturns the attribute names that are safe to be massively assigned.\CModel
scenariostringReturns the scenario that this model is used in.\CModel
siblingsElementCriteriaModelReturns all of the element's siblings.BaseElementModel
statusstring / nullReturns the element's status.UserModel
thumbUrlfalse / null / stringReturns the URL to the element's thumbnail, if there is one.UserModel
titlestringReturns the element's title.BaseElementModel
totalDescendantsboolReturns the total number of descendants that the element has.BaseElementModel
urlstringReturns the element's full URL.BaseElementModel
urlFormatstring / nullReturns the URL format used to generate this element's URL.BaseElementModel
validatorList\CListReturns all the validators declared in the model.\CModel
validatorsarrayReturns the validators applicable to the current scenario.\CModel

Protected Properties #

PropertyTypeDescriptionDefined By
classSuffixstringBaseModel
strictAttributesboolWhether this model should be strict about only allowing values to be set on defined attributesBaseModel

Public Methods #

MethodDescriptionDefined By
__call()Magic __call() method, used for chain-setting attribute values.BaseModel
__construct()ConstructorBaseModel
__get()GetterBaseElementModel
__isset()Treats custom fields as properties.BaseElementModel
__set()PHP setter magic method.BaseModel
__toString()Use the full name or username as the string representation.UserModel
__unset()Sets a component property to be null.\CComponent
addError()Adds a new error to the specified attribute.\CModel
addErrors()Adds a list of errors.\CModel
asa()Returns the named behavior object.\CComponent
attachBehavior()Attaches a behavior to this component.\CComponent
attachBehaviors()Attaches a list of behaviors to the component.\CComponent
attachEventHandler()Attaches an event handler to an event.\CComponent
attributeLabels()Returns the attribute labels.BaseModel
attributeNames()Returns the list of this model's attribute names.BaseModel
behaviors()Returns a list of behaviors that this model should behave as.\CModel
can()Returns whether the user has permission to perform a given action.UserModel
canGetProperty()Determines whether a property can be read.\CComponent
canSetProperty()Determines whether a property can be set.\CComponent
clearErrors()Removes errors for all attributes or a single attribute.\CModel
copy()Returns a copy of this model.BaseModel
createValidators()Creates validator objects based on the specification in rules.\CModel
detachBehavior()Detaches a behavior from the component.\CComponent
detachBehaviors()Detaches all behaviors from the component.\CComponent
detachEventHandler()Detaches an existing event handler.\CComponent
disableBehavior()Disables an attached behavior.\CComponent
disableBehaviors()Disables all behaviors attached to this component.\CComponent
enableBehavior()Enables an attached behavior.\CComponent
enableBehaviors()Enables all behaviors attached to this component.\CComponent
evaluateExpression()Evaluates a PHP expression or callback under the context of this component.\CComponent
generateAttributeLabel()Generates a user friendly attribute label. This is done by replacing underscores or dashes with blanks and changing the first letter of each word to upper case. For example, 'department_name' or 'DepartmentName' becomes 'Department Name'.BaseModel
getAllErrors()Returns all errors in a single, flattened list, devoid of attribute names.BaseModel
getAncestors()Returns the element's ancestors.BaseElementModel
getAttribute()Gets an attribute’s value.BaseElementModel
getAttributeConfigs()Returns this model's normalized attribute configs.BaseModel
getAttributeLabel()Returns the text label for the specified attribute.\CModel
getAttributes()Returns an array of attribute values.BaseModel
getChildren()Returns the element's children.BaseElementModel
getClassHandle()Get the class name, sans namespace and suffix.BaseModel
getContent()Returns the content for the element.BaseElementModel
getContentFromPost()Returns the raw content from the post data, before it was passed through prepValueFromPost().BaseElementModel
getContentPostLocation()Returns the location in POST that the content was pulled from.BaseElementModel
getContentTable()Returns the name of the table this element's content is stored in.BaseElementModel
getCooldownEndTime()Returns the time when the user will be over their cooldown period.UserModel
getCpEditUrl()Returns the element's CP edit URL.UserModel
getDescendants()Returns the element's descendants.BaseElementModel
getEagerLoadedElements()Returns some eager-loaded elements on a given handle.BaseElementModel
getElementType()Returns the type of element this is.BaseElementModel
getError()Returns the first error of the specified attribute.\CModel
getErrors()Returns the errors for all attribute or a single attribute.\CModel
getEventHandlers()Returns the list of attached event handlers for an event.\CComponent
getExtraAttributeNames()Returns a list of the names of the extra attributes that have been saved on this model, if it's not strict.BaseModel
getFieldColumnPrefix()Returns the field column prefix this element's content uses.BaseElementModel
getFieldContext()Returns the field context this element's content uses.BaseElementModel
getFieldLayout()Returns the field layout used by this element.BaseElementModel
getFieldValue()Returns the prepped content for a given field.BaseElementModel
getFriendlyName()Gets the user's first name or username.UserModel
getFullName()Gets the user's full name.UserModel
getGroups()Returns the user's groups.UserModel
getHasFreshContent()Returns whether the element’s content is "fresh" (unsaved and without validation errors).BaseElementModel
getIterator()Returns an iterator for traversing the attributes in the model.\CModel
getLocales()Returns the locale IDs this element is available in.BaseElementModel
getName()Returns the user's full name or username.UserModel
getNext()Returns the next element relative to this one, from a given set of criteria.BaseElementModel
getNextSibling()Returns the element's next sibling.BaseElementModel
getParent()Get the element's parent.BaseElementModel
getParents()Returns a new ElementCriteriaModel prepped to return this element's same-type parents.BaseElementModel
getPhotoUrl()Returns the URL to the user's photo.UserModel
getPrev()Returns the previous element relative to this one, from a given set of criteria.BaseElementModel
getPrevSibling()Returns the element's previous sibling.BaseElementModel
getRawContent()Returns the raw content saved on this entity.BaseElementModel
getRef()Returns the reference string to this element.UserModel
getRemainingCooldownTime()Returns the remaining cooldown time for this user, if they've entered their password incorrectly too many times.UserModel
getSafeAttributeNames()Returns the attribute names that are safe to be massively assigned.\CModel
getScenario()Returns the scenario that this model is used in.\CModel
getSiblings()Returns all of the element's siblings.BaseElementModel
getStatus()Returns the element's status.UserModel
getThumbUrl()Returns the URL to the element's thumbnail, if there is one.UserModel
getTitle()Returns the element's title.BaseElementModel
getTotalDescendants()Returns the total number of descendants that the element has.BaseElementModel
getUrl()Returns the element's full URL.BaseElementModel
getUrlFormat()Returns the URL format used to generate this element's URL.BaseElementModel
getValidatorList()Returns all the validators declared in the model.\CModel
getValidators()Returns the validators applicable to the current scenario.\CModel
hasDescendants()Returns whether the element has descendants.BaseElementModel
hasEagerLoadedElements()Returns whether elements have been eager-loaded with a given handle.BaseElementModel
hasErrors()Returns a value indicating whether there is any validation error.\CModel
hasEvent()Determines whether an event is defined.\CComponent
hasEventHandler()Checks whether the named event has attached handlers.\CComponent
hasProperty()Determines whether a property is defined.\CComponent
hasShunned()Returns whether the user has shunned a given message.UserModel
isAncestorOf()Returns whether this element is an ancestor of another one.BaseElementModel
isAttributeRequired()Returns a value indicating whether the attribute is required.\CModel
isAttributeSafe()Returns a value indicating whether the attribute is safe for massive assignments.\CModel
isChildOf()Returns whether this element is a direct child of another one.BaseElementModel
isCurrent()Returns whether this is the current logged-in user.UserModel
isDescendantOf()Returns whether this element is a descendant of another one.BaseElementModel
isEditable()Returns whether the current user can edit the element.UserModel
isInGroup()Returns whether the user is in a specific group.UserModel
isNextSiblingOf()Returns whether this element is the direct next sibling of another one.BaseElementModel
isParentOf()Returns whether this element is a direct parent of another one.BaseElementModel
isPrevSiblingOf()Returns whether this element is the direct previous sibling of another one.BaseElementModel
isSiblingOf()Returns whether this element is a sibling of another one.BaseElementModel
offsetExists()Treats custom fields as array offsets.BaseElementModel
offsetGet()Returns the element at the specified offset.\CModel
offsetSet()Sets the element at the specified offset.\CModel
offsetUnset()Unsets the element at the specified offset.\CModel
onAfterConstruct()This event is raised after the model instance is created by new operator.\CModel
onAfterValidate()This event is raised after the validation is performed.\CModel
onBeforeValidate()This event is raised before the validation is performed.\CModel
onUnsafeAttribute()This method is invoked when an unsafe attribute is being massively assigned.\CModel
populateModel()Populates a new model instance with a given set of attributes.UserModel
populateModels()Mass-populates models based on an array of attribute arrays.BaseModel
raiseEvent()Raises an event.\CComponent
rules()Returns this model's validation rules.BaseModel
setActive()Sets a user's status to active.UserModel
setAttribute()Sets an attribute's value.BaseModel
setAttributes()Sets multiple attribute values at once.BaseModel
setContent()Sets the content for the element.BaseElementModel
setContentFromPost()Sets the content from post data, calling prepValueFromPost() on the field types.BaseElementModel
setContentPostLocation()Sets the location in POST that the content was pulled from.BaseElementModel
setEagerLoadedElements()Sets some eager-loaded elements on a given handle.BaseElementModel
setGroups()Sets an array of UserGroupModel objects on the user.UserModel
setNext()Sets the default next element.BaseElementModel
setParent()Sets the element's parent.BaseElementModel
setPrev()Sets the default previous element.BaseElementModel
setRawPostContent()Sets a field’s raw post content.BaseElementModel
setScenario()Sets the scenario for the model.\CModel
unsetAttributes()Sets the attributes to be null.\CModel
validate()Validates all of the attributes for the current Model. Any attributes that fail validation will additionally get logged to the craft/storage/runtime/logs folder with a level of LogLevel::Warning.UserModel

Protected Methods #

MethodDescriptionDefined By
afterConstruct()This method is invoked after a model instance is created by new operator.\CModel
afterValidate()This method is invoked after validation ends.\CModel
beforeValidate()This method is invoked before validation starts.\CModel
createContent()Creates the content model associated with this element.BaseElementModel
defineAttributes()Defines this model's attributes.UserModel
getFieldByHandle()Returns the field with a given handle.BaseElementModel

Events #

EventDescriptionDefined By
onAfterConstructThis event is raised after the model instance is created by new operator.\CModel
onBeforeValidateThis event is raised before the validation is performed.\CModel
onAfterValidateThis event is raised after the validation is performed.\CModel
onUnsafeAttributeThis method is invoked when an unsafe attribute is being massively assigned.\CModel

Property Details #

cooldownEndTime #

read-only
public DateTime|null getCooldownEndTime()

Returns the time when the user will be over their cooldown period.

cpEditUrl #

read-only
public string|false getCpEditUrl()

Returns the element's CP edit URL.

friendlyName #

read-only
public string|null getFriendlyName()

Gets the user's first name or username.

fullName #

read-only
public string|null getFullName()

Gets the user's full name.

groups #

public array getGroups(string|null $indexBy = null)
public null setGroups($groups $groups)

Returns the user's groups.

name #

read-only
public string getName()

Returns the user's full name or username.

photoUrl #

read-only
public string|null getPhotoUrl(int $size = 100)

Returns the URL to the user's photo.

ref #

read-only
public string|null getRef()

Returns the reference string to this element.

remainingCooldownTime #

read-only
public DateInterval|null getRemainingCooldownTime()

Returns the remaining cooldown time for this user, if they've entered their password incorrectly too many times.

status #

read-only
public string|null getStatus()

Returns the element's status.

thumbUrl #

read-only
public false|null|string getThumbUrl(int $size = 100)

Returns the URL to the element's thumbnail, if there is one.

Method Details #

__toString() #

public function __toString()
{
     if (craft()->config->get('useEmailAsUsername'))
     {
          return (string)$this->email;
     }
     else
     {
          return (string)$this->username;
     }
}
Returnsstring

Use the full name or username as the string representation.

can() #

public function can($permission)
{
     if (craft()->getEdition() >= Craft::Client)
     {
          if ($this->admin)
          {
               return true;
          }
          else if ($this->id)
          {
               return craft()->userPermissions->doesUserHavePermission($this->id, $permission);
          }
          else
          {
               return false;
          }
     }
     else
     {
          return true;
     }
}
$permissionstring
Returnsbool

Returns whether the user has permission to perform a given action.

defineAttributes() #

protected function defineAttributes()
{
     $requireUsername = !craft()->config->get('useEmailAsUsername');

     return array_merge(parent::defineAttributes(), array(
          'username'                   => array(AttributeType::String, 'maxLength' => 100, 'required' => $requireUsername),
          'photo'                      => array(AttributeType::String, 'maxLength' => 100),
          'firstName'                  => AttributeType::String,
          'lastName'                   => AttributeType::String,
          'email'                      => array(AttributeType::Email, 'required' => !$requireUsername),
          'password'                   => AttributeType::String,
          'preferredLocale'            => AttributeType::Locale,
          'weekStartDay'               => array(AttributeType::Number, 'default' => craft()->config->get('defaultWeekStartDay')),
          'admin'                      => AttributeType::Bool,
          'client'                     => AttributeType::Bool,
          'locked'                     => AttributeType::Bool,
          'suspended'                  => AttributeType::Bool,
          'pending'                    => AttributeType::Bool,
          'archived'                   => AttributeType::Bool,
          'lastLoginDate'              => AttributeType::DateTime,
          'invalidLoginCount'          => AttributeType::Number,
          'lastInvalidLoginDate'       => AttributeType::DateTime,
          'lockoutDate'                => AttributeType::DateTime,
          'passwordResetRequired'      => AttributeType::Bool,
          'lastPasswordChangeDate'     => AttributeType::DateTime,
          'unverifiedEmail'            => AttributeType::Email,
          'newPassword'                => AttributeType::String,
          'currentPassword'            => AttributeType::String,
          'verificationCodeIssuedDate' => AttributeType::DateTime,
     ));
}
Returnsarray

Defines this model's attributes.

getAttribute() #

public function getAttribute($name, $flattenValue = false)
{
     return parent::getAttribute($name, $flattenValue);
}
$namestringThe attribute’s name.
$flattenValuebool
Returnsmixed

Gets an attribute’s value.

getCooldownEndTime() #

public function getCooldownEndTime()
{
     if ($this->status == UserStatus::Locked)
     {
          // There was an old bug that where a user's lockoutDate could be null if they've
          // passed their cooldownDuration already, but there account status is still locked.
          // If that's the case, just let it return null as if they are past the cooldownDuration.
          if ($this->lockoutDate)
          {
               $cooldownEnd = clone $this->lockoutDate;
               $cooldownEnd->add(new DateInterval(craft()->config->get('cooldownDuration')));

               return $cooldownEnd;
          }
     }
}
ReturnsDateTime / null

Returns the time when the user will be over their cooldown period.

getCpEditUrl() #

public function getCpEditUrl()
{
     if ($this->isCurrent())
     {
          return UrlHelper::getCpUrl('myaccount');
     }
     else if (craft()->getEdition() == Craft::Client && $this->client)
     {
          return UrlHelper::getCpUrl('clientaccount');
     }
     else if (craft()->getEdition() == Craft::Pro)
     {
          return UrlHelper::getCpUrl('users/'.$this->id);
     }
     else
     {
          return false;
     }
}
Returnsstring / false

Returns the element's CP edit URL.

getFriendlyName() #

public function getFriendlyName()
{
     if ($firstName = trim($this->firstName))
     {
          return $firstName;
     }
     else
     {
          return $this->username;
     }
}
Returnsstring / null

Gets the user's first name or username.

getFullName() #

public function getFullName()
{
     $firstName = trim($this->firstName);
     $lastName = trim($this->lastName);

     return $firstName.($firstName && $lastName ? ' ' : '').$lastName;
}
Returnsstring / null

Gets the user's full name.

getGroups() #

public function getGroups($indexBy = null)
{
     if (!isset($this->_groups))
     {
          if (craft()->getEdition() == Craft::Pro)
          {
               $this->_groups = craft()->userGroups->getGroupsByUserId($this->id);
          }
          else
          {
               $this->_groups = array();
          }
     }

     if (!$indexBy)
     {
          $groups = $this->_groups;
     }
     else
     {
          $groups = array();

          foreach ($this->_groups as $group)
          {
               $groups[$group->$indexBy] = $group;
          }
     }

     return $groups;
}
$indexBystring / null
Returnsarray

Returns the user's groups.

getName() #

public function getName()
{
     $fullName = $this->getFullName();

     if ($fullName)
     {
          return $fullName;
     }
     else
     {
          return $this->username;
     }
}
Returnsstring

Returns the user's full name or username.

getPhotoUrl() #

public function getPhotoUrl($size = 100)
{
     if ($this->photo)
     {
          $username = AssetsHelper::cleanAssetName($this->username, false, true);
          return UrlHelper::getResourceUrl('userphotos/'.$username.'/'.$size.'/'.$this->photo);
     }
}
$sizeint
Returnsstring / null

Returns the URL to the user's photo.

getRef() #

public function getRef()
{
     return $this->username;
}
Returnsstring / null

Returns the reference string to this element.

getRemainingCooldownTime() #

public function getRemainingCooldownTime()
{
     if ($this->status == UserStatus::Locked)
     {
          $currentTime = DateTimeHelper::currentUTCDateTime();
          $cooldownEnd = $this->getCooldownEndTime();

          if ($currentTime < $cooldownEnd)
          {
               return $currentTime->diff($cooldownEnd);
          }
     }
}
ReturnsDateInterval / null

Returns the remaining cooldown time for this user, if they've entered their password incorrectly too many times.

getStatus() #

public function getStatus()
{
     if ($this->locked)
     {
          return UserStatus::Locked;
     }

     if ($this->suspended)
     {
          return UserStatus::Suspended;
     }

     if ($this->archived)
     {
          return UserStatus::Archived;
     }

     if ($this->pending)
     {
          return UserStatus::Pending;
     }

     return UserStatus::Active;
}
Returnsstring / null

Returns the element's status.

getThumbUrl() #

public function getThumbUrl($size = 100)
{
     $url = $this->getPhotoUrl($size);

     if (!$url)
     {
          $url = UrlHelper::getResourceUrl('defaultuserphoto');
     }

     return $url;
}
$sizeint / null
Returnsstring / null

Returns the URL to the element's thumbnail, if there is one.

hasShunned() #

public function hasShunned($message)
{
     if ($this->id)
     {
          return craft()->users->hasUserShunnedMessage($this->id, $message);
     }
     else
     {
          return false;
     }
}
$messagestring
Returnsbool

Returns whether the user has shunned a given message.

isCurrent() #

public function isCurrent()
{
     if ($this->id)
     {
          $currentUser = craft()->userSession->getUser();

          if ($currentUser)
          {
               return ($this->id == $currentUser->id);
          }
     }

     return false;
}
Returnsbool

Returns whether this is the current logged-in user.

isEditable() #

public function isEditable()
{
     return craft()->userSession->checkPermission('editUsers');
}
Returnsbool

Returns whether the current user can edit the element.

isInGroup() #

public function isInGroup($group)
{
     if (craft()->getEdition() == Craft::Pro)
     {
          if (is_object($group) && $group instanceof UserGroupModel)
          {
               $group = $group->id;
          }

          if (is_numeric($group))
          {
               $groups = array_keys($this->getGroups('id'));
          }
          else if (is_string($group))
          {
               $groups = array_keys($this->getGroups('handle'));
          }

          if (!empty($groups))
          {
               return in_array($group, $groups);
          }
     }

     return false;
}
$groupmixedThe user group model, its handle, or ID.
Returnsbool

Returns whether the user is in a specific group.

populateModel() #

public static function populateModel($attributes)
{
     $user = parent::populateModel($attributes);

     // Is the user in cooldown mode, and are they past their window?
     if ($user->status == UserStatus::Locked)
     {
          $cooldownDuration = craft()->config->get('cooldownDuration');

          if ($cooldownDuration)
          {
               if (!$user->getRemainingCooldownTime())
               {
                    craft()->users->unlockUser($user);
               }
          }
     }

     return $user;
}
$valuesmixed
ReturnsBaseModel

Populates a new model instance with a given set of attributes.

setActive() #

public function setActive()
{
     $this->pending = false;
     $this->archived = false;
}

Sets a user's status to active.

setGroups() #

public function setGroups($groups)
{
     if (craft()->getEdition() == Craft::Pro)
     {
          $this->_groups = $groups;
     }
}
$groups$groupsAn array of UserGroupModel objects.

Sets an array of UserGroupModel objects on the user.

validate() #

public function validate($attributes = null, $clearErrors = true)
{
     // Don't allow whitespace in the username.
     if (preg_match('/\s+/', $this->username))
     {
          $this->addError('username', Craft::t('Spaces are not allowed in the username.'));
     }

     return parent::validate($attributes, false);
}
$attributesnull
$clearErrorsbool
Returnsbool / null

Validates all of the attributes for the current Model. Any attributes that fail validation will additionally get logged to the craft/storage/runtime/logs folder with a level of LogLevel::Warning.

In addition, we check that the username does not have any whitespace in it.