code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
public function getResultIDs() { $results = $this->executeGetResults(); $ids = []; foreach ($results as $result) { $ids[] = $result['uID']; } return $ids; }
similar to get except it returns an array of userIDs much faster than getting a UserInfo object for each result if all you need is the user's id. @return array $userIDs
getResultIDs
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByIsActive($isActive) { $this->includeInactiveUsers(); $this->query->andWhere('u.uIsActive = :uIsActive'); $this->query->setParameter('uIsActive', $isActive); }
Explicitly filters by whether a user is active or not. Does this by setting "include inactive users" to true, THEN filtering them in our out. Some settings here are redundant given the default settings but a little duplication is ok sometimes. @param $val @param mixed $isActive
filterByIsActive
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByIsValidated($isValidated) { $this->includeInactiveUsers(); if (!$isValidated) { $this->includeUnvalidatedUsers(); $this->query->andWhere('u.uIsValidated = :uIsValidated'); $this->query->setParameter('uIsValidated', $isValidated); } }
Filter list by whether a user is validated or not. @param bool $isValidated
filterByIsValidated
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByUserName($username) { $this->query->andWhere('u.uName = :uName'); $this->query->setParameter('uName', $username); }
Filter list by user name. @param $username
filterByUserName
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByFuzzyUserName($username) { $this->query->andWhere( $this->query->expr()->like('u.uName', ':uName') ); $this->query->setParameter('uName', '%' . $username . '%'); }
Filter list by user name but as a like parameter. @param $username
filterByFuzzyUserName
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByKeywords($keywords) { $expressions = []; if ($this->includeUsernameInKeywordSearch) { $expressions[] = $this->query->expr()->like('u.uName', ':keywords'); } if ($this->includeEmailInKeywordSearch) { $expressions[] = $this->query->expr()->like('u.uEmail', ':keywords'); } if ($this->includeAttributesInKeywordSearch) { $keys = \Concrete\Core\Attribute\Key\UserKey::getSearchableIndexedList(); foreach ($keys as $ak) { $cnt = $ak->getController(); $expressions[] = $cnt->searchKeywords($keywords, $this->query); } } if (count($expressions)) { $expr = $this->query->expr(); $this->query->andWhere(call_user_func_array([$expr, 'orX'], $expressions)); $this->query->setParameter('keywords', '%' . $keywords . '%'); } else { throw new \RuntimeException(t('Called filterByKeywords but did not provide any valid criteria to search.')); } }
Filters keyword fields by keywords (including username, email and attributes). @param $keywords
filterByKeywords
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByGroup($group = '', $inGroup = true) { if (!($group instanceof \Concrete\Core\User\Group\Group)) { $groupName = $group; $group = \Concrete\Core\User\Group\Group::getByName($groupName); if (!$group) { throw new \RuntimeException(t('Group "%s" does not exist.', $groupName)); } } $this->checkGroupJoin(); $app = Application::getFacadeApplication(); /** @var LikeBuilder $likeBuilder */ $likeBuilder = $app->make(LikeBuilder::class); $query = $this->getQueryObject()->getConnection()->createQueryBuilder(); $orX = $this->getQueryObject()->expr()->orX(); $query->select('u.uID')->from('Users', 'u') ->leftJoin('u', 'UserGroups', 'ug', 'u.uID=ug.uID') ->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g', 'ug.gID=g.gID') ; $orX->add($this->getQueryObject()->expr()->like('g.gPath', ':groupPath_' . $group->getGroupID())); $this->getQueryObject()->setParameter('groupPath_' . $group->getGroupID(), $likeBuilder->escapeForLike($group->getGroupPath()) . '/%'); $orX->add($this->getQueryObject()->expr()->eq('g.gID', $group->getGroupID())); $query->where($orX); if ($inGroup) { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->in('u.uID', $query->getSQL())); } else { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->notIn('u.uID', $query->getSQL())); } }
Filters the user list for only users within the provided group. Accepts an instance of a group object or a string group name. @param \Group | string $group @param bool $inGroup
filterByGroup
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByInAnyGroup($groups, $inGroups = true) { $this->checkGroupJoin(); $groupIDs = []; $orX = $this->getQueryObject()->expr()->orX(); $app = Application::getFacadeApplication(); /** @var LikeBuilder $likeBuilder */ $likeBuilder = $app->make(LikeBuilder::class); $query = $this->getQueryObject()->getConnection()->createQueryBuilder(); foreach ($groups as $group) { if ($group instanceof \Concrete\Core\User\Group\Group) { $orX->add($this->getQueryObject()->expr()->like('g.gPath', ':groupPathChild_' . $group->getGroupID())); $this->getQueryObject()->setParameter('groupPathChild_' . $group->getGroupID(), $likeBuilder->escapeForLike($group->getGroupPath()) . '/%'); $groupIDs[] = $group->getGroupID(); } } if (is_array($groups) && count($groups) > 0) { $query->select('u.uID')->from('Users', 'u') ->leftJoin('u', 'UserGroups', 'ug', 'u.uID=ug.uID') ->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g', 'ug.gID=g.gID') ; $orX->add($this->getQueryObject()->expr()->in('g.gID', $groupIDs)); $query->where($orX)->andWhere($this->getQueryObject()->expr()->isNotNull('g.gID')); if ($inGroups) { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->in('u.uID', $query->getSQL())); } else { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->notIn('u.uID', $query->getSQL())); $this->getQueryObject()->setParameter('groupIDs', $groupIDs, \Concrete\Core\Database\Connection\Connection::PARAM_INT_ARRAY); } } }
Filters the user list for only users within at least one of the provided groups. @param \Concrete\Core\User\Group\Group[]|\Generator $groups @param bool $inGroups Set to true to search users that are in at least in one of the specified groups, false to search users that aren't in any of the specified groups
filterByInAnyGroup
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByDateAdded($date, $comparison = '=') { $this->query->andWhere($this->query->expr()->comparison( 'u.uDateAdded', $comparison, $this->query->createNamedParameter($date) )); }
Filters by date added. @param string $date @param mixed $comparison
filterByDateAdded
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
public function filterByGroupID($gID) { $group = Group::getByID($gID); $this->filterByGroup($group); }
Filters by Group ID. @param mixed $gID
filterByGroupID
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
private function checkGroupJoin() { $query = $this->getQueryObject(); $params = $query->getQueryPart('join'); $isGroupSet = false; $isUserGroupSet = false; // Loop twice as params returns an array of arrays foreach ($params as $param) { foreach ($param as $setTable) if (in_array('ug', $setTable)) { $isUserGroupSet = true; } if (in_array('g', $setTable)) { $isGroupSet = true; } } if ($isUserGroupSet === false) { $query->leftJoin('u', 'UserGroups', 'ug', 'ug.uID = u.uID'); } if ($isGroupSet === false) { $query->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g', 'ug.gID = g.gID'); } }
Function used to check if a group join has already been set.
checkGroupJoin
php
concretecms/concretecms
concrete/src/User/UserList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserList.php
MIT
protected function bindContainer(Application $app) { $this->app->when(PasswordUsageTracker::class)->needs('$maxReuse')->give(function () { return $this->app['config']->get('concrete.user.password.reuse.track', 5); }); $this->app->bindShared('user/registration', function () use ($app) { return $app->make('Concrete\Core\User\RegistrationService'); }); $this->app->bindShared('user/avatar', function () use ($app) { return $app->make('Concrete\Core\User\Avatar\AvatarService'); }); $this->app->bindShared('user/status', function () use ($app) { return $app->make('Concrete\Core\User\StatusService'); }); $this->app->bind('Concrete\Core\User\RegistrationServiceInterface', function () use ($app) { return $app->make('user/registration'); }); $this->app->bind('Concrete\Core\User\StatusServiceInterface', function () use ($app) { return $app->make('user/status'); }); $this->app->bind('Concrete\Core\User\Avatar\AvatarServiceInterface', function () use ($app) { return $app->make('user/avatar'); }); }
Bind things to the container @param \Concrete\Core\Application\Application $app
bindContainer
php
concretecms/concretecms
concrete/src/User/UserServiceProvider.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserServiceProvider.php
MIT
public function handleEvent($event, UserNotificationEventHandler $service) { // If our event is the wrong type, just do a null/void return if (!$event instanceof DeactivateUser) { return; } $entity = $event->getUserEntity(); if ($entity) { $service->deactivated($event); } }
Handle routing bound events @param object $event @param \Concrete\Core\User\Notification\UserNotificationEventHandler $service @internal
handleEvent
php
concretecms/concretecms
concrete/src/User/UserServiceProvider.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserServiceProvider.php
MIT
public function transform(UserInfo $user) { return [ 'id' => $user->getUserID(), 'name' => $user->getUserName(), 'email' => $user->getUserEmail(), 'dateAdded' => $this->date->formatDateTime($user->getUserDateAdded()), 'status' => $this->getUserStatus($user), 'totalLogins' => $user->getNumLogins(), ]; }
Basic transforming of a user into an array @param UserInfo $user @return array
transform
php
concretecms/concretecms
concrete/src/User/UserTransformer.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/UserTransformer.php
MIT
protected static function generate($len = 64) { return Core::make('helper/validation/identifier')->getString($len); }
Generates a random string. @param int $len @return string
generate
php
concretecms/concretecms
concrete/src/User/ValidationHash.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/ValidationHash.php
MIT
protected static function removeExpired($type) { switch ($type) { case UVTYPE_CHANGE_PASSWORD: $lifetime = USER_CHANGE_PASSWORD_URL_LIFETIME; break; case UVTYPE_LOGIN_FOREVER: $lifetime = USER_FOREVER_COOKIE_LIFETIME; break; default: $lifetime = 5184000; // 60 days break; } $db = Database::connection(); $db->executeQuery('DELETE FROM UserValidationHashes WHERE type = ? AND uDateGenerated <= ?', array($type, time() - $lifetime)); }
Removes old entries for the supplied type. @param int $type
removeExpired
php
concretecms/concretecms
concrete/src/User/ValidationHash.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/ValidationHash.php
MIT
public static function add($uID, $type, $singeHashAllowed = false, $hashLength = 64) { self::removeExpired($type); $hash = self::generate($hashLength); $db = Database::connection(); if ($singeHashAllowed) { $db->executeQuery("DELETE FROM UserValidationHashes WHERE uID = ? AND type = ?", array($uID, $type)); } $db->executeQuery("insert into UserValidationHashes (uID, uHash, uDateGenerated, type) values (?, ?, ?, ?)", array($uID, $hash, time(), intval($type))); return $hash; }
Adds a hash to the lookup table for a user and type, removes any other existing hashes for the same user and type. @param int $uID @param int $type @param bool $singeHashAllowed @param int $hashLength @return string
add
php
concretecms/concretecms
concrete/src/User/ValidationHash.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/ValidationHash.php
MIT
public static function getUserID($hash, $type) { self::removeExpired($type); $db = Database::connection(); $uID = $db->fetchColumn("SELECT uID FROM UserValidationHashes WHERE uHash = ? AND type = ?", array($hash, $type)); if (is_numeric($uID) && $uID > 0) { return $uID; } else { return false; } }
Gets the users id for a given hash and type. @param string $hash @param int $type @return int | false
getUserID
php
concretecms/concretecms
concrete/src/User/ValidationHash.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/ValidationHash.php
MIT
public static function getType($hash) { $db = Database::connection(); $type = $db->fetchColumn("SELECT type FROM UserValidationHashes WHERE uHash = ? ", array($hash)); if (is_numeric($type) && $type > 0) { return $type; } else { return false; } }
Gets the hash type for a given hash. @param string $hash @return int | false
getType
php
concretecms/concretecms
concrete/src/User/ValidationHash.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/ValidationHash.php
MIT
public static function isValid($hash) { $type = self::getType($hash); self::removeExpired($type); return (bool) self::getUserID($hash, $type); }
Validate the given hash @param $hash @return bool
isValid
php
concretecms/concretecms
concrete/src/User/ValidationHash.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/ValidationHash.php
MIT
public function inMyAccount($pageOrPath) { $path = ''; if (is_string($pageOrPath)) { $path = $pageOrPath; } elseif ($pageOrPath instanceof Page && !$pageOrPath->isError()) { $path = $pageOrPath->getCollectionPath(); } return $path === '/account' || strpos($path, '/account/') === 0; }
Test if the a page or path path is within the my account section. @param \Concrete\Core\Page\Page|string|null $pageOrPath @return bool
inMyAccount
php
concretecms/concretecms
concrete/src/User/Account/AccountService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Account/AccountService.php
MIT
public function __construct(Connection $connection, Repository $config) { $this->connection = $connection; $this->config = $config; }
@param Connection $connection @param Repository $config
__construct
php
concretecms/concretecms
concrete/src/User/Command/RemoveOldFileAttachmentsCommandHandler.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Command/RemoveOldFileAttachmentsCommandHandler.php
MIT
public function __construct(UserInfo $user, UploadedFile $avatarFile) { $this->user = $user; $this->avatarFile = $avatarFile; }
UpdateUserAvatarCommand constructor. @param UserInfo $user @param UploadedFile $avatarFile
__construct
php
concretecms/concretecms
concrete/src/User/Command/UpdateUserAvatarCommand.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Command/UpdateUserAvatarCommand.php
MIT
public function __construct(UserEntity $user, ?UserEntity $actorEntity = null, ?DateTime $dateCreated = null) { $this->user = $user; $this->actor = $actorEntity; $this->created = $dateCreated ?: Carbon::now('utc'); }
DeactivateUser constructor. @param \Concrete\Core\Entity\User\User $user @param \Concrete\Core\Entity\User\User|null $actorEntity @param \DateTime|null $dateCreated
__construct
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public function getNotificationDate() { return $this->created; }
Get the date of this notification @return \DateTime
getNotificationDate
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public function getUsersToExcludeFromNotification() { return [$this->getUserEntity()]; }
Get the users that should be excluded from notifications Expected return value would be users involved in the creation of the notification, they may not need to be notified. @return \Concrete\Core\Entity\User\User[]
getUsersToExcludeFromNotification
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public function getUserInfoObject() { return $this->user->getUserInfoObject(); }
Pass through calls for the user info object to the associated user info object @return \Concrete\Core\User\UserInfo|null
getUserInfoObject
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public function getUserEntity() { return $this->user; }
Get the user that is being deactivated @return \Concrete\Core\Entity\User\User
getUserEntity
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public function getActorEntity() { return $this->actor; }
Get the user that is running the deactivation @return \Concrete\Core\Entity\User\User|null
getActorEntity
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public static function create(UserEntity $userEntity, ?UserEntity $actorEntity = null, ?DateTime $dateCreated = null) { return new self($userEntity, $actorEntity, $dateCreated); }
Factory method for creating new User event objects @param \Concrete\Core\Entity\User\User $userEntity The user being deactivated @param \Concrete\Core\Entity\User\User|null $actorEntity The user running the deactivate action @param \DateTime|null $dateCreated @return \Concrete\Core\User\Event\DeactivateUser
create
php
concretecms/concretecms
concrete/src/User/Event/DeactivateUser.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/DeactivateUser.php
MIT
public function getResponse(): ?Response { $response = $this->getArgument(static::RESPONSE_ARGUMENT_KEY); return $response instanceof Response ? $response : null; }
Get the response to be sent to clients after the logout process (if available).
getResponse
php
concretecms/concretecms
concrete/src/User/Event/Logout.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/Logout.php
MIT
public function setResponse(?Response $response): self { return $this->setArgument(static::RESPONSE_ARGUMENT_KEY, $response); }
Set the response to be sent to clients after the logout process. @return $this
setResponse
php
concretecms/concretecms
concrete/src/User/Event/Logout.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/Logout.php
MIT
public function setApplier(\Concrete\Core\User\User $applier) { $this->applier = $applier; }
@param \Concrete\Core\User\User $applier
setApplier
php
concretecms/concretecms
concrete/src/User/Event/UserInfo.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Event/UserInfo.php
MIT
protected function userCanDeleteGroups(): bool { return $this->getWhyUserCantDeleteGroups() === ''; }
Can the current user delete groups? @return bool
userCanDeleteGroups
php
concretecms/concretecms
concrete/src/User/Group/CanDeleteGroupsTrait.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/CanDeleteGroupsTrait.php
MIT
protected function getWhyUserCantDeleteGroups(): string { $app = app(); $config = $app->make(Repository::class); if ($config->get('concrete.user.group.delete_requires_superuser')) { if (!$app->make(User::class)->isSuperUser()) { return t('You need to be a super user to delete groups.'); } } return ''; }
Get the reason why the current user can't delete groups. @return string Empty string if the current user CAN delete groups
getWhyUserCantDeleteGroups
php
concretecms/concretecms
concrete/src/User/Group/CanDeleteGroupsTrait.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/CanDeleteGroupsTrait.php
MIT
public function getGroups(): array { return $this->groups; }
@return \Concrete\Core\User\Group\Group[]
getGroups
php
concretecms/concretecms
concrete/src/User/Group/EditResponse.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/EditResponse.php
MIT
public function getJSONObject() { $result = $this->getBaseJSONObject(); $result->groups = $this->getGroups(); return $result; }
{@inheritdoc} @see \Concrete\Core\Application\EditResponse::getJSONObject()
getJSONObject
php
concretecms/concretecms
concrete/src/User/Group/EditResponse.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/EditResponse.php
MIT
public function create() { $type = NodeType::getByHandle('group_folder'); if (!is_object($type)) { $type = NodeType::add('group_folder'); } $groupTree = \Concrete\Core\Tree\Type\Group::get(); // transform the parent group node to a group folder $app = Application::getFacadeApplication(); /** @var Connection $db */ $db = $app->make(Connection::class); $db->executeQuery("UPDATE TreeNodes n SET n.treeNodeTypeID = ? WHERE n.treeNodeID = ?", [ $type->getTreeNodeTypeID(), $groupTree->getRootTreeNodeID() ]); return $groupTree; }
Creates everything necessary to store files in folders. @return \Concrete\Core\Tree\Type\Group @throws \Doctrine\DBAL\Exception
create
php
concretecms/concretecms
concrete/src/User/Group/FolderManager.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/FolderManager.php
MIT
public function getFolder($folderID) { $node = Node::getByID($folderID); if ($node instanceof GroupFolder) { return $node; } }
Get a folder given its ID. @param mixed $folderID @return \Concrete\Core\Tree\Node\Type\FileFolder|null
getFolder
php
concretecms/concretecms
concrete/src/User/Group/FolderManager.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/FolderManager.php
MIT
public function getRootFolder() { $tree = \Concrete\Core\Tree\Type\Group::get(); if ($tree !== null) { return $tree->getRootTreeNodeObject(); } }
Get the root folder. @return \Concrete\Core\Tree\Node\Type\GroupFolder|null
getRootFolder
php
concretecms/concretecms
concrete/src/User/Group/FolderManager.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/FolderManager.php
MIT
public function addFolder(GroupFolder $folder, $name) { return $folder->add($name, $folder); }
Create a new folder. @param GroupFolder $folder The parent folder @param string $name The name of the new folder @return \Concrete\Core\Tree\Node\Type\GroupFolder
addFolder
php
concretecms/concretecms
concrete/src/User/Group/FolderManager.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/FolderManager.php
MIT
public function getGroupDateTimeEntered($user) { if (is_object($user)) { $userID = (int)$user->getUserID(); } elseif (is_numeric($user)) { $userID = (int)$user; } else { $userID = 0; } $result = null; if ($userID !== 0) { $db = Application::getFacadeApplication()->make(Connection::class); /* @var Connection $db */ $value = $db->fetchColumn( 'select ugEntered from UserGroups where gID = ? and uID = ?', [$this->getGroupID(), $userID] ); if ($value) { $result = $value; } } return $result; }
Get the date/time when a user entered this group. @param object|int $user the user ID or an object with a getUserID method @return string|null
getGroupDateTimeEntered
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function changeUserRole($user, $userRole) { $activeUser = new User(); if ($this->hasUserManagerPermissions($activeUser) && $user->inGroup($this)) { if ($user->isRegistered() && $this->isPetitionForPublicEntry()) { $app = Application::getFacadeApplication(); /** @var Connection $db */ $db = $app->make(Connection::class); $db->executeQuery("UPDATE UserGroups SET grID = ? WHERE gID = ? AND uID = ?", [$userRole->getId(), $this->getGroupID(), $user->getUserID()]); /** @noinspection PhpUnhandledExceptionInspection */ $subject = new GroupRoleChange($this, $user, $userRole); /** @var GroupRoleChangeType $type */ $type = $app->make('manager/notification/types')->driver('group_role_change'); $notifier = $type->getNotifier(); if (method_exists($notifier, 'notify')) { $subscription = $type->getSubscription($subject); $users = $notifier->getUsersToNotify($subscription, $subject); $notification = new GroupRoleChangeNotification($subject); $subject->getNotifications()->add($notification); $notifier->notify($users, $notification); } return true; } } return false; }
@param User $user @param GroupRole $userRole @return bool
changeUserRole
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function getThumbnailImage() { $bf = false; if ($this->gThumbnailFID) { $bf = \Concrete\Core\File\File::getByID($this->gThumbnailFID); if (!is_object($bf) || $bf->isError()) { unset($bf); } } return $bf; }
@return \Concrete\Core\Entity\File\File|bool
getThumbnailImage
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function setThumbnailImage(\Concrete\Core\Entity\File\File $file) { $app = Application::getFacadeApplication(); /** @var Connection $db */ $db = $app->make(Connection::class); $this->gThumbnailFID = $file->getFileID(); try { $db->executeQuery("update `Groups` set gThumbnailFID = ? where gID = ?", [$this->gThumbnailFID, $this->getGroupID()]); return true; } catch (Exception $e) { return false; } }
@param \Concrete\Core\Entity\File\File $file @return bool
setThumbnailImage
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function getUserRole($user) { if ($user->isRegistered()) { $app = Application::getFacadeApplication(); /** @var Connection $db */ $db = $app->make(Connection::class); $row = $db->fetchAssoc("SELECT grID FROM UserGroups WHERE gID = ? AND uID = ?", [$this->getGroupID(), $user->getUserID()]); if (isset($row)) { return GroupRole::getByID($row["grID"]); } } return null; }
@param User $user @return GroupRole|null
getUserRole
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function getParentGroup() { $node = GroupTreeNode::getTreeNodeByGroupID($this->getGroupID()); $parent = $node->getTreeNodeParentObject(); return $parent instanceof \Concrete\Core\Tree\Node\Type\Group ? $parent->getTreeNodeGroupObject() : null; }
@return \Concrete\Core\User\Group\Group|null
getParentGroup
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function getGroupStartDate() { return $this->cgStartDate; }
Gets the group start date. @return string date formated like: 2009-01-01 00:00:00
getGroupStartDate
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function getGroupEndDate() { return $this->cgEndDate; }
Gets the group end date. @return string date formated like: 2009-01-01 00:00:00
getGroupEndDate
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public static function add($gName, $gDescription, $parentGroup = false, $pkg = null) { $app = Facade::getFacadeApplication(); $command = new AddGroupCommand(); $command->setName($gName); $command->setDescription($gDescription); if ($parentGroup) { $command->setParentGroupID($parentGroup->getGroupID()); } if ($pkg) { $command->setPackageID($pkg->getPackageID()); } return $app->executeCommand($command); }
Creates a new user group. @param string $gName @param string $gDescription @return Group @deprecated This is deprecated; use the AddGroupCommand and the command bus.
add
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public static function addBeneathFolder($gName, $gDescription, $parentFolder = false, $pkg = null) { $app = Facade::getFacadeApplication(); $command = new AddGroupCommand(); $command->setName($gName); $command->setDescription($gDescription); if ($parentFolder) { $command->setParentNodeID($parentFolder->getTreeNodeID()); } if ($pkg) { $command->setPackageID($pkg->getPackageID()); } return $app->executeCommand($command); }
Creates a new user group. This is deprecated; use the AddGroupCommand and the command bus. @param string $gName @param string $gDescription @param GroupFolder $parentFolder @return Group
addBeneathFolder
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function setBadgeOptions($gBadgeFID, $gBadgeDescription, $gBadgeCommunityPointValue) { $db = Database::connection(); $db->executeQuery( 'update ' . $db->getDatabasePlatform()->quoteSingleIdentifier('Groups') . ' set gIsBadge = 1, gBadgeFID = ?, gBadgeDescription = ?, gBadgeCommunityPointValue = ? where gID = ?', [intval($gBadgeFID), $gBadgeDescription, $gBadgeCommunityPointValue, $this->getGroupID()] ); }
@param $gBadgeFID @param $gBadgeDescription @param $gBadgeCommunityPointValue @deprecated
setBadgeOptions
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public static function getByID($gID) { $app = Facade::getFacadeApplication(); $repository = $app->make(GroupRepository::class); return $repository->getGroupByID($gID); }
Takes the numeric id of a group and returns a group object. @param string $gID @return Group @deprecated This is deprecated, user the grouprepository instead.
getByID
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public static function getByName($gName) { $app = Facade::getFacadeApplication(); $repository = $app->make(GroupRepository::class); return $repository->getGroupByName($gName); }
Takes the name of a group and returns a group object. @param string $gName @return Group @deprecated This is deprecated, user the grouprepository instead.
getByName
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public static function getByPath($gPath) { $app = Facade::getFacadeApplication(); $repository = $app->make(GroupRepository::class); return $repository->getGroupByPath($gPath); }
@param string $gPath The group path @return Group|null @deprecated This is deprecated, user the grouprepository instead.
getByPath
php
concretecms/concretecms
concrete/src/User/Group/Group.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Group.php
MIT
public function getGroupObject() { return $this->group; }
@return \Concrete\Core\User\Group\Group
getGroupObject
php
concretecms/concretecms
concrete/src/User/Group/GroupAutomationController.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupAutomationController.php
MIT
public function filterByKeywords($keywords) { $expressions = [ $this->query->expr()->like('g.gName', ':keywords'), $this->query->expr()->like('g.gDescription', ':keywords'), ]; $expr = $this->query->expr(); $this->query->andWhere(call_user_func_array([$expr, 'orX'], $expressions)); $this->query->setParameter('keywords', '%' . $keywords . '%'); }
Filters keyword fields by keywords (including name and description). @param $keywords
filterByKeywords
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
public function filterByAssignable() { $app = Application::getFacadeApplication(); /** @var Repository $config */ $config = $app->make(Repository::class); if ($config->get('concrete.permissions.model') != 'simple') { // there's gotta be a more reasonable way than this but right now i'm not sure what that is. $excludeGroupIDs = [GUEST_GROUP_ID, REGISTERED_GROUP_ID]; /** @var Connection $db */ $db = $app->make(Connection::class); /** @noinspection PhpUnhandledExceptionInspection */ /** @noinspection SqlNoDataSourceInspection */ $r = $db->executeQuery('select gID from ' . $db->getDatabasePlatform()->quoteSingleIdentifier('Groups') . ' where gID > ?', [REGISTERED_GROUP_ID]); while ($row = $r->fetch()) { $g = $this->getGroupRepository()->getGroupById($row['gID']); $gp = new Checker($g); /** @noinspection PhpUndefinedMethodInspection */ if (!$gp->canAssignGroup()) { $excludeGroupIDs[] = $row['gID']; } } $this->query->andWhere( $this->query->expr()->notIn('g.gId', array_map([$db, 'quote'], $excludeGroupIDs)) ); } }
Only return groups the user has the ability to assign.
filterByAssignable
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
public function filterByHavingMembership() { $app = Facade::getFacadeApplication(); /** @var User $u */ $u = $app->make(User::class); /** @var Connection $db */ $db = $app->make(Connection::class); if ($u->isRegistered()) { $groups = $u->getUserGroups(); // returns an array of IDs $this->query->andWhere( $this->query->expr()->in('g.gId', array_map([$db, 'quote'], $groups)) ); } }
Only return groups the user is actually a member of
filterByHavingMembership
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
public function getTotalResults() { $query = $this->deliverQueryObject(); return $query->resetQueryParts(['groupBy', 'orderBy'])->select('count(distinct g.gID)')->setMaxResults(1)->execute()->fetchColumn(); }
The total results of the query. @return int
getTotalResults
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
protected function createPaginationObject() { $adapter = new DoctrineDbalAdapter($this->deliverQueryObject(), function ($query) { $query->resetQueryParts(['groupBy', 'orderBy'])->select('count(distinct g.gID)')->setMaxResults(1); }); $pagination = new Pagination($this, $adapter); return $pagination; }
Gets the pagination object for the query. @return Pagination
createPaginationObject
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
public function getResult($queryRow) { $g = Group::getByID($queryRow['gID']); return $g; }
@param $queryRow @return \Concrete\Core\User\Group\Group
getResult
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
function getPaginationAdapter() { return new DoctrineDbalAdapter($this->deliverQueryObject(), function ($query) { // We need to reset the potential custom order by here because otherwise, if we've added // items to the select parts, and we're ordering by them, we get a SQL error // when we get total results, because we're resetting the select $query->resetQueryParts(['groupBy', 'orderBy'])->select('count(distinct g.gID)')->setMaxResults(1); }); }
Returns the standard pagination adapter. This is used for non-permissioned objects and is typically something like DoctrineDbalAdapter @return mixed
getPaginationAdapter
php
concretecms/concretecms
concrete/src/User/Group/GroupList.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupList.php
MIT
public static function add($grName, $grIsManager) { $app = Application::getFacadeApplication(); /** @var Connection $db */ $db = $app->make(Connection::class); try { $db->executeQuery('insert into GroupRoles (grName, grIsManager) values (?,?)', [$grName, (int)$grIsManager]); } catch (Exception $e) { return false; } $id = $db->lastInsertId(); return self::getByID($id); }
@param string $grName @param bool $grIsManager @return bool|static
add
php
concretecms/concretecms
concrete/src/User/Group/GroupRole.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupRole.php
MIT
public function getGroupSetDisplayName($format = 'html') { $value = tc('GroupSetName', $this->getGroupSetName()); switch ($format) { case 'html': return h($value); case 'text': default: return $value; } }
Returns the display name for this group set (localized and escaped accordingly to $format) @param string $format = 'html' Escape the result in html format (if $format is 'html'). If $format is 'text' or any other value, the display name won't be escaped. @return string
getGroupSetDisplayName
php
concretecms/concretecms
concrete/src/User/Group/GroupSet.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupSet.php
MIT
public static function add($gtName, $gtPetitionForPublicEntry) { $app = Application::getFacadeApplication(); /** @var Connection $db */ $db = $app->make(Connection::class); try { $db->executeQuery('insert into GroupTypes (gtName, gtPetitionForPublicEntry) values (?,?)', [$gtName, (int)$gtPetitionForPublicEntry]); } catch (Exception $e) { return false; } $id = $db->lastInsertId(); return self::getByID($id); }
@param string $gtName @param bool $gtPetitionForPublicEntry @return bool|static
add
php
concretecms/concretecms
concrete/src/User/Group/GroupType.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/GroupType.php
MIT
public function check(User $ux) { return true; }
Return true to automatically enter the current ux into the group.
check
php
concretecms/concretecms
concrete/src/User/Group/AutomatedGroup/DefaultAutomation.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/AutomatedGroup/DefaultAutomation.php
MIT
public function setOnChildGroups(int $value): object { $this->onChildGroups = $value; return $this; }
@return $this @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_MOVETOROOT @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_MOVETOPARENT @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_ABORT @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_DELETE
setOnChildGroups
php
concretecms/concretecms
concrete/src/User/Group/Command/DeleteGroupCommand.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/DeleteGroupCommand.php
MIT
public function getOnChildGroups(): int { return $this->onChildGroups; }
@see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_MOVETOROOT @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_MOVETOPARENT @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_ABORT @see \Concrete\Core\User\Group\Command\DeleteGroupCommand::ONCHILDGROUPS_DELETE
getOnChildGroups
php
concretecms/concretecms
concrete/src/User/Group/Command/DeleteGroupCommand.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/DeleteGroupCommand.php
MIT
public function __invoke(DeleteGroupCommand $command) { $result = new DeleteGroupCommand\Result(); $groupID = $command->getGroupID(); $group = $this->checkDeletableGroup($groupID, $command->isOnlyIfEmpty(), $result); if ($group === null) { return $command->isExtendedResults() ? $result : false; } $groupNode = GroupTreeNode::getTreeNodeByGroupID($groupID); if ($groupNode !== null) { if ($this->processChildGroups($command, $group, $groupNode, $result) === false) { return $command->isExtendedResults() ? $result : false; } $groupNode->delete(); } $this->cleanupReferences($groupID); $result->addDeletedGroup($groupID); return $command->isExtendedResults() ? $result : null; }
@return \Concrete\Core\User\Group\Command\DeleteGroupCommand\Result|bool
__invoke
php
concretecms/concretecms
concrete/src/User/Group/Command/DeleteGroupCommandHandler.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/DeleteGroupCommandHandler.php
MIT
private function checkDeletableGroup(int $groupID, bool $mustBeWithoutMembers, DeleteGroupCommand\Result $result): ?Group { if ($groupID === REGISTERED_GROUP_ID) { $result->addUndeletableGrup($groupID, t("It's not possible to delete the Registered Users group")); return null; } if ($groupID == GUEST_GROUP_ID) { $result->addUndeletableGrup($groupID, t("It's not possible to delete the Guest group")); return null; } $group = $this->groupRepository->getGroupById($groupID); if (!$group) { $result->addUndeletableGrup($groupID, t('Unable to find the group with ID %s', $groupID)); return null; } if ($mustBeWithoutMembers) { $numMembers = (int) $this->connection->fetchOne('SELECT COUNT(gID) FROM UserGroups WHERE gID = ?', [$groupID]); if ($numMembers !== 0) { $result->addUndeletableGrup( $groupID, t2( "The group \"%2\$s\" can't be deleted because it contains %1\$s member", "The group \"%2\$s\" can't be deleted because it contains %1\$s members", $numMembers, $group->getGroupDisplayName(false) ) ); return null; } } $ge = new DeleteEvent($group); $ge = $this->dispatcher->dispatch('on_group_delete', $ge); if (!$ge->proceed()) { $result->addUndeletableGrup( $groupID, t( 'The removal of the group "%1$s" has been cancelled by the "%2s" event', $group->getGroupDisplayName(false), 'on_group_delete' ) ); return null; } return $group; }
@return \Concrete\Core\User\Group\Group|null returns NULL if the group can't be deleted (the reason will be added to $result)
checkDeletableGroup
php
concretecms/concretecms
concrete/src/User/Group/Command/DeleteGroupCommandHandler.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/DeleteGroupCommandHandler.php
MIT
public function getUndeletableGroups(): array { return $this->undeletableGroups; }
Array keys are the group IDs, array values are the reasons why the group couldn't be deleted.
getUndeletableGroups
php
concretecms/concretecms
concrete/src/User/Group/Command/DeleteGroupCommand/Result.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/DeleteGroupCommand/Result.php
MIT
public function merge(self $other): object { $this->deletedGroupIDs = array_values(array_unique(array_merge($this->deletedGroupIDs, $other->getDeletedGroupIDs()), SORT_NUMERIC)); $this->undeletableGroups += $other->getUndeletableGroups(); return $this; }
Merge another Result instance into this one. @return $this
merge
php
concretecms/concretecms
concrete/src/User/Group/Command/DeleteGroupCommand/Result.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/DeleteGroupCommand/Result.php
MIT
public function getParentGroupID(): ?int { return $this->parentGroupID; }
@deprecated Use the parent node instead. @return int|null
getParentGroupID
php
concretecms/concretecms
concrete/src/User/Group/Command/Traits/GroupDetailsTrait.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/Traits/GroupDetailsTrait.php
MIT
public function setParentGroupID(?int $parentGroupID): object { $this->parentGroupID = $parentGroupID; return $this; }
@deprecated Use the parent node instead. @return $this
setParentGroupID
php
concretecms/concretecms
concrete/src/User/Group/Command/Traits/GroupDetailsTrait.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/Traits/GroupDetailsTrait.php
MIT
public function setParentNodeID(?int $parentNodeID): object { $this->parentNodeID = $parentNodeID; return $this; }
@param int|null $parentNodeID @return object
setParentNodeID
php
concretecms/concretecms
concrete/src/User/Group/Command/Traits/GroupDetailsTrait.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Command/Traits/GroupDetailsTrait.php
MIT
public function __construct(?Node $folder = null, $searchSubFolders = false) { if ($folder) { $this->data['folderID'] = $folder->getTreeNodeID(); $this->data['searchSubFolder'] = $searchSubFolders; $this->isLoaded = true; } }
FolderField constructor. @param GroupFolder|Node $folder @param bool $searchSubFolders
__construct
php
concretecms/concretecms
concrete/src/User/Group/Search/Field/Field/FolderField.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Search/Field/Field/FolderField.php
MIT
public function filterList(ItemList $list) { $folderID = $this->getData('folderID'); if ($folderID) { $folder = Node::getByID($folderID); if ($folder && $folder instanceof GroupFolder) { $list->filterByParentFolder($folder); if ($this->getData('searchSubFolder')) { $list->enableSubFolderSearch(); } } elseif ($folder && $folder instanceof Group) { // Add support for legacy folders $group = $folder->getTreeNodeGroupObject(); if (count($group->getChildGroups()) > 0) { $list->filterByParentFolder($folder); if ($this->getData('searchSubFolder')) { $list->enableSubFolderSearch(); } } } } }
@param \Concrete\Core\User\Group\FolderItemList $list @param $request
filterList
php
concretecms/concretecms
concrete/src/User/Group/Search/Field/Field/FolderField.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Group/Search/Field/Field/FolderField.php
MIT
public function trackAttempt($username, $password) { if (!$this->config->get('concrete.user.deactivation.authentication_failure.enabled', false)) { return $this; } $user = $this->resolveUser($username); if (!$user) { return; } $attempt = new LoginAttempt(); $attempt->setUtcDate(Carbon::now('UTC')); $attempt->setUserId($user->getUserID()); $this->entityManager->persist($attempt); // Make sure we get flushed with the next batch $this->batch[] = $attempt; // Prune old attempts $this->pruneAttempts(); return $this; }
Track a login attempt for a user @param string $username @param string $password @return $this
trackAttempt
php
concretecms/concretecms
concrete/src/User/Login/LoginAttemptService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginAttemptService.php
MIT
public function remainingAttempts($username) { $config = $this->config->get('concrete.user.deactivation.authentication_failure'); $allowed = (int) array_get($config, 'amount', 0); $duration = (int) array_get($config, 'duration', 0); $after = Carbon::now('UTC')->subSeconds($duration); $user = $this->resolveUser($username); if (!$user) { return $allowed; } /** @var \Concrete\Core\Entity\User\LoginAttemptRepository $repository */ $repository = $this->entityManager->getRepository(LoginAttempt::class); $attempts = $repository->after($after, $user, true); return max(0, $allowed - $attempts); }
Determine the amount of attempts remaining for a username @param $username @return int
remainingAttempts
php
concretecms/concretecms
concrete/src/User/Login/LoginAttemptService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginAttemptService.php
MIT
public function pruneAttempts(?DateTime $before = null) { if (!$before) { $duration = (int) $this->config->get('concrete.user.deactivation.authentication_failure.duration'); $before = Carbon::now('UTC')->subSeconds($duration); } // Load our repository and get entries before our date $repository = $this->entityManager->getRepository(LoginAttempt::class); $results = $repository->before($before); // Loop through and remove those entries $batch = []; $max = 50; foreach ($results as $result) { $this->entityManager->remove($result); $batch[] = $result; // Handle the batch $batch = $this->manageBatch($batch, $max); } // Close off the batch $this->manageBatch($batch); }
Prune old login attempts @param \DateTime|null $before The date to prune before. This MUST be in UTC, if not passed this value is derived from config
pruneAttempts
php
concretecms/concretecms
concrete/src/User/Login/LoginAttemptService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginAttemptService.php
MIT
private function manageBatch(array $batch, $max = 0) { if (count($batch) >= $max) { $this->entityManager->flush(); $batch = []; } return $batch; }
Manage a batched ORM operation @param array $batch @param int $max @return array
manageBatch
php
concretecms/concretecms
concrete/src/User/Login/LoginAttemptService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginAttemptService.php
MIT
private function resolveUser($username) { if (isset($this->knownUsers[strtolower($username)])) { return $this->knownUsers[strtolower($username)]; } $repository = $this->entityManager->getRepository(User::class); $user = $repository->findOneBy(['uName' => $username]); // If we couldn't find the user by username, let's try to get it by email if (!$user) { $user = $repository->findOneBy(['uEmail' => $username]); } // No user to actually track against. if (!$user) { return null; } /** * I don't know what detach is doing or why it's here, but it's causing an exception on UserSignup * not being a known entity. Much like drugs, `detach` is not the answer */ //$this->entityManager->detach($user); $this->knownUsers[strtolower($username)] = $user; return $user; }
Resolve the user from username / user email @param $username @return User|null
resolveUser
php
concretecms/concretecms
concrete/src/User/Login/LoginAttemptService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginAttemptService.php
MIT
public function login($username, $password) { /** * @todo Invert this so that the `new User` constructor login relies on this service */ $className = $this->userClass; $user = new $className($username, $password); if ($user->isError()) { // Throw an appropriate acception matching the exceptional state $this->handleUserError($user->getError()); } return $user; }
Attempt login given a username and a password @param string $username The username or email to attempt login with @param string $password The plain text password to attempt login with @return User The logged in user @throws \Concrete\Core\User\Exception\NotActiveException If the user is inactive @throws \Concrete\Core\User\Exception\InvalidCredentialsException If passed credentials don't seem valid @throws \Concrete\Core\User\Exception\NotValidatedException If the user has not yet been validated @throws \Concrete\Core\User\Exception\SessionExpiredException If the session immediately expires after login
login
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
public function loginByUserID($userId) { /** * @todo Move the responsibility of logging users in out of the User class and into this service */ $className = $this->userClass; return $className::getByUserID($userId, true); }
Force log in as a specific user ID This method will setup session and set a cookie @param int $userId The user id to login as @return User The newly logged in user
loginByUserID
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
public function failLogin($username, $password) { $ipFailed = false; $userFailed = false; // Track both failed logins from this IP and attempts to login to this user account $this->ipService->logFailedLogin(); $this->loginAttemptService->trackAttempt($username, $password); // Deal with excessive logins from an IP if ($this->ipService->failedLoginsThresholdReached()) { $this->ipService->addToDenylistForThresholdReached(); $ipFailed = true; } // If the remaining attempts are less than 0 if ($this->loginAttemptService->remainingAttempts($username, $password) <= 0) { $this->loginAttemptService->deactivate($username); $userFailed = true; } // Throw the IP ban error if we hit both ip limit and user limit at the same time if ($ipFailed) { $message = $this->ipService->getErrorMessage(); throw new FailedLoginThresholdExceededException($message); } // If the user has been automatically deactivated and the IP has not been banned if ($userFailed) { throw new UserDeactivatedException($this->config->get('concrete.user.deactivation.message')); } }
Handle a failed login attempt @param string $username The user provided username @param string $password The user provided password @throws \Concrete\Core\User\Exception\FailedLoginThresholdExceededException
failLogin
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
public function logLoginAttempt($username, array $errors = []) { if ($this->app) { $entry = new LoginAttempt( $username, $this->request ? $this->request->getPath() : '', $this->getGroups($username), $errors ); $context = $entry->getContext(); $context['ip_address'] = (string) $this->ipService->getRequestIPAddress(); $this->logger->info($entry->getMessage(), $context); } }
Add a log entry for this login attempt @param $username @param array $errors
logLoginAttempt
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
private function getGroups($username) { if (!$this->entityManager) { return []; } $db = $this->entityManager->getConnection(); $queryBuilder = $db->createQueryBuilder(); $rows = $queryBuilder ->select('g.gName', 'u.uID')->from($db->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g') ->leftJoin('g', 'UserGroups', 'ug', 'ug.gID=g.gID') ->innerJoin('ug', 'Users', 'u', 'ug.uID=u.uID AND (u.uName=? OR u.uEmail=?)') ->setParameters([$username, $username]) ->execute(); $groups = []; $uID = 0; foreach ($rows as $row) { $uID = (int) $row['uID']; $groups[] = $row['gName']; } if ($uID == USER_SUPER_ID) { $groups[] = 'SUPER'; } return $groups; }
Aggregate a list of groups to report @param $username @return array
getGroups
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
protected function handleUserError($errorNum) { switch ($errorNum) { case USER_INACTIVE: throw new NotActiveException(t($this->config->get('concrete.user.deactivation.message'))); case USER_SESSION_EXPIRED: throw new SessionExpiredException(t('Your session has expired. Please sign in again.')); case USER_NON_VALIDATED: throw new NotValidatedException(t( 'This account has not yet been validated. Please check the email associated with this ' . 'account and follow the link it contains.')); case USER_PASSWORD_RESET: throw new UserPasswordResetException(t('This password has been reset.')); case USER_PASSWORD_EXPIRED: throw new UserPasswordExpiredException(t('This password has expired and must be changed.')); case USER_INVALID: if ($this->config->get('concrete.user.registration.email_registration')) { $message = t('Invalid email address or password.'); } else { $message = t('Invalid username or password.'); } throw new InvalidCredentialsException($message); } throw new \RuntimeException(t('An unknown login error occurred. Please try again.')); }
Throw an exception based on the given error number @param int $errorNum The error number retrieved from the user object @throws \RuntimeException If an unknown error number is passed @throws \Concrete\Core\User\Exception\NotActiveException If the user is inactive @throws \Concrete\Core\User\Exception\InvalidCredentialsException If passed credentials don't seem valid @throws \Concrete\Core\User\Exception\NotValidatedException If the user has not yet been validated @throws \Concrete\Core\User\Exception\SessionExpiredException If the session immediately expires after login
handleUserError
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
public function setUserClass($userClass) { $this->userClass = $userClass; }
Change the user class used to validate the given credentials @param string $userClass @deprecated This will be removed once the User class is no longer in charge of negotiating login ~9.0
setUserClass
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
public function getLoggerChannel() { return Channels::CHANNEL_AUTHENTICATION; }
Get the logger channel expected by this LoggerAwareTrait implementation The user is expected to declare this method and return a valid channel name. @return string One of \Concrete\Core\Logging\Channels::CHANNEL_*
getLoggerChannel
php
concretecms/concretecms
concrete/src/User/Login/LoginService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Login/LoginService.php
MIT
public function deactivated(DeactivateUser $event) { /** @var UserDeactivatedType $type */ $type = $this->notificationManager->driver(UserDeactivatedType::IDENTIFIER); $notifier = $type->getNotifier(); if (method_exists($notifier, 'notify')) { $subscription = $type->getSubscription($event); $users = $notifier->getUsersToNotify($subscription, $event); $notification = new UserDeactivatedNotification($event); $notifier->notify($users, $notification); } }
Handle deactivated user events @param \Concrete\Core\User\Event\DeactivateUser $event
deactivated
php
concretecms/concretecms
concrete/src/User/Notification/UserNotificationEventHandler.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Notification/UserNotificationEventHandler.php
MIT
public function handleEvent($event) { if (!$event instanceof UserInfoWithPassword) { throw new InvalidArgumentException(t('Invalid event type provided. Event type must be "UserInfoWithPassword".')); } // Track the password use $this->tracker->trackUse($event->getUserPassword(), $event->getUserInfoObject()); }
Event handler for `on_user_change_password` events @param object $event @throws \InvalidArgumentException If the given event is not the proper subclass type. Must be `UserInfoWithPassword`
handleEvent
php
concretecms/concretecms
concrete/src/User/Password/PasswordChangeEventHandler.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Password/PasswordChangeEventHandler.php
MIT
public function trackUse($string, $subject) { $id = $this->resolveUserID($subject); // If the subject is invalid return false if (!$id) { return false; } if (!is_string($string)) { throw new \InvalidArgumentException(t('Invalid mixed value provided. Must be a string.')); } if ($this->maxReuse) { // Store the use in the database $this->entityManager->transactional(function (EntityManagerInterface $em) use ($id, $string) { $reuse = new UsedString(); $reuse->setDate(Carbon::now()); $reuse->setSubject($id); $reuse->setUsedString(password_hash($string, PASSWORD_DEFAULT)); $em->persist($reuse); }); } // Prune extra tracked uses $this->pruneUses($id); return true; }
Track a string being used @param string $string The password that was used @param int|\Concrete\Core\User\User|\Concrete\Core\User\UserInfo|\Concrete\Core\Entity\User\User $subject The subject that used the password @return bool
trackUse
php
concretecms/concretecms
concrete/src/User/Password/PasswordUsageTracker.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Password/PasswordUsageTracker.php
MIT
private function pruneUses($subject) { $repository = $this->entityManager->getRepository(UsedString::class); $usedStrings = $repository->findBy(['subject' => $subject], ['id' => 'desc']); // IF there are extra used strings, prune the extras if (count($usedStrings) > $this->maxReuse) { array_map([$this->entityManager, 'remove'], array_slice($usedStrings, $this->maxReuse)); $this->entityManager->flush(); } }
Prune uses for a specific subject @param int $subject
pruneUses
php
concretecms/concretecms
concrete/src/User/Password/PasswordUsageTracker.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Password/PasswordUsageTracker.php
MIT
private function resolveUserID($subject) { // Handle `null`, `0`, and any other falsy subject if (!$subject) { return 0; } // If an integer is just passed in if (is_numeric($subject)) { return (int)$subject; } // If we get an actual user instance if ($subject instanceof User || $subject instanceof UserInfo || $subject instanceof EntityUser) { return $subject->getUserID(); } // Non-falsy subject that is unsupported throw new \InvalidArgumentException(t('Unsupported subject provided. Subject must be a User, UserInfo, or User Entity object.')); }
@param $subject @return int @throws \InvalidArgumentException
resolveUserID
php
concretecms/concretecms
concrete/src/User/Password/PasswordUsageTracker.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/Password/PasswordUsageTracker.php
MIT
public function __construct(CookieJar $cookieJar, Repository $config) { $this->cookieJar = $cookieJar; $this->config = $config; }
Initialize the instance. @param \Concrete\Core\Cookie\CookieJar $cookieJar @param \Concrete\Core\Config\Repository\Repository $config
__construct
php
concretecms/concretecms
concrete/src/User/PersistentAuthentication/CookieService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/PersistentAuthentication/CookieService.php
MIT
public function getCookie() { if (!$this->cookieJar->has(static::COOKIE_NAME)) { return null; } $rawValue = $this->cookieJar->get(static::COOKIE_NAME); return $this->unserializeCookieValue($rawValue); }
Get the authentication data corrently contained in the cookie jar. @return \Concrete\Core\User\PersistentAuthentication\CookieValue|null
getCookie
php
concretecms/concretecms
concrete/src/User/PersistentAuthentication/CookieService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/PersistentAuthentication/CookieService.php
MIT
public function setCookie(?CookieValue $value = null) { if ($value === null) { $this->deleteCookie(); return; } $this->cookieJar->getResponseCookies()->addCookie( // $name static::COOKIE_NAME, // $value $this->serializeCookieValue($value), // $expire time() + (int) $this->config->get('concrete.session.remember_me.lifetime'), // $path DIR_REL . '/', // $domain $this->config->get('concrete.session.cookie.cookie_domain'), // $secure $this->config->get('concrete.session.cookie.cookie_secure'), // $httpOnly $this->config->get('concrete.session.cookie.cookie_httponly'), // $raw $this->config->get('concrete.session.cookie.cookie_raw'), // $sameSite $this->config->get('concrete.session.cookie.cookie_samesite') ); }
Set (or delete) the authentication cookie. @param \Concrete\Core\User\PersistentAuthentication\CookieValue|null $value
setCookie
php
concretecms/concretecms
concrete/src/User/PersistentAuthentication/CookieService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/PersistentAuthentication/CookieService.php
MIT
protected function serializeCookieValue(CookieValue $value) { return implode(':', [$value->getUserID(), $value->getAuthenticationTypeHandle(), $value->getToken()]); }
@param \Concrete\Core\User\PersistentAuthentication\CookieValue $value @return string
serializeCookieValue
php
concretecms/concretecms
concrete/src/User/PersistentAuthentication/CookieService.php
https://github.com/concretecms/concretecms/blob/master/concrete/src/User/PersistentAuthentication/CookieService.php
MIT