3 * Represents the membership of a user to a user group.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\IDatabase
;
24 use MediaWiki\MediaWikiServices
;
27 * Represents a "user group membership" -- a specific instance of a user belonging
28 * to a group. For example, the fact that user Mary belongs to the sysop group is a
29 * user group membership.
31 * The class encapsulates rows in the user_groups table. The logic is low-level and
32 * doesn't run any hooks. Often, you will want to call User::addGroup() or
33 * User::removeGroup() instead.
37 class UserGroupMembership
{
38 /** @var int The ID of the user who belongs to the group */
44 /** @var string|null Timestamp of expiry in TS_MW format, or null if no expiry */
48 * @param int $userId The ID of the user who belongs to the group
49 * @param string $group The internal group name
50 * @param string|null $expiry Timestamp of expiry in TS_MW format, or null if no expiry
52 public function __construct( $userId = 0, $group = null, $expiry = null ) {
53 $this->userId
= (int)$userId;
54 $this->group
= $group; // TODO throw on invalid group?
55 $this->expiry
= $expiry ?
: null;
61 public function getUserId() {
68 public function getGroup() {
73 * @return string|null Timestamp of expiry in TS_MW format, or null if no expiry
75 public function getExpiry() {
79 protected function initFromRow( $row ) {
80 $this->userId
= (int)$row->ug_user
;
81 $this->group
= $row->ug_group
;
82 $this->expiry
= $row->ug_expiry
=== null ?
84 wfTimestamp( TS_MW
, $row->ug_expiry
);
88 * Creates a new UserGroupMembership object from a database row.
90 * @param stdClass $row The row from the user_groups table
91 * @return UserGroupMembership
93 public static function newFromRow( $row ) {
95 $ugm->initFromRow( $row );
100 * Returns the list of user_groups fields that should be selected to create
101 * a new user group membership.
104 public static function selectFields() {
113 * Delete the row from the user_groups table.
115 * @throws MWException
116 * @param IDatabase|null $dbw Optional master database connection to use
117 * @return bool Whether or not anything was deleted
119 public function delete( IDatabase
$dbw = null ) {
120 if ( wfReadOnly() ) {
124 if ( $dbw === null ) {
125 $dbw = wfGetDB( DB_MASTER
);
130 [ 'ug_user' => $this->userId
, 'ug_group' => $this->group
],
132 if ( !$dbw->affectedRows() ) {
136 // Remember that the user was in this group
138 'user_former_groups',
139 [ 'ufg_user' => $this->userId
, 'ufg_group' => $this->group
],
147 * Insert a user right membership into the database. When $allowUpdate is false,
148 * the function fails if there is a conflicting membership entry (same user and
149 * group) already in the table.
151 * @throws MWException
152 * @param bool $allowUpdate Whether to perform "upsert" instead of INSERT
153 * @param IDatabase|null $dbw If you have one available
154 * @return bool Whether or not anything was inserted
156 public function insert( $allowUpdate = false, IDatabase
$dbw = null ) {
157 if ( $dbw === null ) {
158 $dbw = wfGetDB( DB_MASTER
);
161 // Purge old, expired memberships from the DB
162 JobQueueGroup
::singleton()->push( new UserGroupExpiryJob() );
164 // Check that the values make sense
165 if ( $this->group
=== null ) {
166 throw new UnexpectedValueException(
167 'Don\'t try inserting an uninitialized UserGroupMembership object' );
168 } elseif ( $this->userId
<= 0 ) {
169 throw new UnexpectedValueException(
170 'UserGroupMembership::insert() needs a positive user ID. ' .
171 'Did you forget to add your User object to the database before calling addGroup()?' );
174 $row = $this->getDatabaseArray( $dbw );
175 $dbw->insert( 'user_groups', $row, __METHOD__
, [ 'IGNORE' ] );
176 $affected = $dbw->affectedRows();
178 // Don't collide with expired user group memberships
179 // Do this after trying to insert, in order to avoid locking
182 'ug_user' => $row['ug_user'],
183 'ug_group' => $row['ug_group'],
185 // if we're unconditionally updating, check that the expiry is not already the
186 // same as what we are trying to update it to; otherwise, only update if
187 // the expiry date is in the past
188 if ( $allowUpdate ) {
189 if ( $this->expiry
) {
190 $conds[] = 'ug_expiry IS NULL OR ug_expiry != ' .
191 $dbw->addQuotes( $dbw->timestamp( $this->expiry
) );
193 $conds[] = 'ug_expiry IS NOT NULL';
196 $conds[] = 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp() );
199 $row = $dbw->selectRow( 'user_groups', $this::selectFields(), $conds, __METHOD__
);
203 [ 'ug_expiry' => $this->expiry ?
$dbw->timestamp( $this->expiry
) : null ],
204 [ 'ug_user' => $row->ug_user
, 'ug_group' => $row->ug_group
],
206 $affected = $dbw->affectedRows();
210 return $affected > 0;
214 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
215 * @param IDatabase $db
218 protected function getDatabaseArray( IDatabase
$db ) {
220 'ug_user' => $this->userId
,
221 'ug_group' => $this->group
,
222 'ug_expiry' => $this->expiry ?
$db->timestamp( $this->expiry
) : null,
227 * Has the membership expired?
230 public function isExpired() {
231 if ( !$this->expiry
) {
234 return wfTimestampNow() > $this->expiry
;
239 * Purge expired memberships from the user_groups table
241 public static function purgeExpired() {
242 $services = MediaWikiServices
::getInstance();
243 if ( $services->getReadOnlyMode()->isReadOnly() ) {
247 $lbFactory = $services->getDBLoadBalancerFactory();
248 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
249 $dbw = $services->getDBLoadBalancer()->getConnection( DB_MASTER
);
251 $lockKey = $dbw->getDomainID() . ':usergroups-prune'; // specific to this wiki
252 $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__
, 0 );
253 if ( !$scopedLock ) {
254 return; // already running
259 $dbw->startAtomic( __METHOD__
);
263 self
::selectFields(),
264 [ 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp( $now ) ) ],
266 [ 'FOR UPDATE', 'LIMIT' => 100 ]
269 if ( $res->numRows() > 0 ) {
270 $insertData = []; // array of users/groups to insert to user_former_groups
271 $deleteCond = []; // array for deleting the rows that are to be moved around
272 foreach ( $res as $row ) {
273 $insertData[] = [ 'ufg_user' => $row->ug_user
, 'ufg_group' => $row->ug_group
];
274 $deleteCond[] = $dbw->makeList(
275 [ 'ug_user' => $row->ug_user
, 'ug_group' => $row->ug_group
],
279 // Delete the rows we're about to move
282 $dbw->makeList( $deleteCond, $dbw::LIST_OR
),
285 // Push the groups to user_former_groups
286 $dbw->insert( 'user_former_groups', $insertData, __METHOD__
, [ 'IGNORE' ] );
289 $dbw->endAtomic( __METHOD__
);
291 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
292 } while ( $res->numRows() > 0 );
296 * Returns UserGroupMembership objects for all the groups a user currently
299 * @param int $userId ID of the user to search for
300 * @param IDatabase|null $db Optional database connection
301 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
303 public static function getMembershipsForUser( $userId, IDatabase
$db = null ) {
305 $db = wfGetDB( DB_REPLICA
);
308 $res = $db->select( 'user_groups',
309 self
::selectFields(),
310 [ 'ug_user' => $userId ],
314 foreach ( $res as $row ) {
315 $ugm = self
::newFromRow( $row );
316 if ( !$ugm->isExpired() ) {
317 $ugms[$ugm->group
] = $ugm;
325 * Returns a UserGroupMembership object that pertains to the given user and group,
326 * or false if the user does not belong to that group (or the assignment has
329 * @param int $userId ID of the user to search for
330 * @param string $group User group name
331 * @param IDatabase|null $db Optional database connection
332 * @return UserGroupMembership|false
334 public static function getMembership( $userId, $group, IDatabase
$db = null ) {
336 $db = wfGetDB( DB_REPLICA
);
339 $row = $db->selectRow( 'user_groups',
340 self
::selectFields(),
341 [ 'ug_user' => $userId, 'ug_group' => $group ],
347 $ugm = self
::newFromRow( $row );
348 if ( !$ugm->isExpired() ) {
356 * Gets a link for a user group, possibly including the expiry date if relevant.
358 * @param string|UserGroupMembership $ugm Either a group name as a string, or
359 * a UserGroupMembership object
360 * @param IContextSource $context
361 * @param string $format Either 'wiki' or 'html'
362 * @param string|null $userName If you want to use the group member message
363 * ("administrator"), pass the name of the user who belongs to the group; it
364 * is used for GENDER of the group member message. If you instead want the
365 * group name message ("Administrators"), omit this parameter.
368 public static function getLink( $ugm, IContextSource
$context, $format,
371 if ( $format !== 'wiki' && $format !== 'html' ) {
372 throw new MWException( 'UserGroupMembership::getLink() $format parameter should be ' .
373 "'wiki' or 'html'" );
376 if ( $ugm instanceof UserGroupMembership
) {
377 $expiry = $ugm->getExpiry();
378 $group = $ugm->getGroup();
384 if ( $userName !== null ) {
385 $groupName = self
::getGroupMemberName( $group, $userName );
387 $groupName = self
::getGroupName( $group );
390 // link to the group description page, if it exists
391 $linkTitle = self
::getGroupPage( $group );
393 if ( $format === 'wiki' ) {
394 $linkPage = $linkTitle->getFullText();
395 $groupLink = "[[$linkPage|$groupName]]";
397 $groupLink = Linker
::link( $linkTitle, htmlspecialchars( $groupName ) );
400 $groupLink = htmlspecialchars( $groupName );
404 // format the expiry to a nice string
405 $uiLanguage = $context->getLanguage();
406 $uiUser = $context->getUser();
407 $expiryDT = $uiLanguage->userTimeAndDate( $expiry, $uiUser );
408 $expiryD = $uiLanguage->userDate( $expiry, $uiUser );
409 $expiryT = $uiLanguage->userTime( $expiry, $uiUser );
410 if ( $format === 'html' ) {
411 $groupLink = Message
::rawParam( $groupLink );
413 return $context->msg( 'group-membership-link-with-expiry' )
414 ->params( $groupLink, $expiryDT, $expiryD, $expiryT )->text();
421 * Gets the localized friendly name for a group, if it exists. For example,
422 * "Administrators" or "Bureaucrats"
424 * @param string $group Internal group name
425 * @return string Localized friendly group name
427 public static function getGroupName( $group ) {
428 $msg = wfMessage( "group-$group" );
429 return $msg->isBlank() ?
$group : $msg->text();
433 * Gets the localized name for a member of a group, if it exists. For example,
434 * "administrator" or "bureaucrat"
436 * @param string $group Internal group name
437 * @param string $username Username for gender
438 * @return string Localized name for group member
440 public static function getGroupMemberName( $group, $username ) {
441 $msg = wfMessage( "group-$group-member", $username );
442 return $msg->isBlank() ?
$group : $msg->text();
446 * Gets the title of a page describing a particular user group. When the name
447 * of the group appears in the UI, it can link to this page.
449 * @param string $group Internal group name
450 * @return Title|bool Title of the page if it exists, false otherwise
452 public static function getGroupPage( $group ) {
453 $msg = wfMessage( "grouppage-$group" )->inContentLanguage();
454 if ( $msg->exists() ) {
455 $title = Title
::newFromText( $msg->text() );
456 if ( is_object( $title ) ) {