Merge "Exclude redirects from Special:Fewestrevisions"
[lhc/web/wiklou.git] / includes / user / UserGroupMembership.php
1 <?php
2 /**
3 * Represents the membership of a user to a user group.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\IDatabase;
24 use MediaWiki\MediaWikiServices;
25
26 /**
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.
30 *
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.
34 *
35 * @since 1.29
36 */
37 class UserGroupMembership {
38 /** @var int The ID of the user who belongs to the group */
39 private $userId;
40
41 /** @var string */
42 private $group;
43
44 /** @var string|null Timestamp of expiry in TS_MW format, or null if no expiry */
45 private $expiry;
46
47 /**
48 * @param int $userId The ID of the user who belongs to the group
49 * @param string|null $group The internal group name
50 * @param string|null $expiry Timestamp of expiry in TS_MW format, or null if no expiry
51 */
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;
56 }
57
58 /**
59 * @return int
60 */
61 public function getUserId() {
62 return $this->userId;
63 }
64
65 /**
66 * @return string
67 */
68 public function getGroup() {
69 return $this->group;
70 }
71
72 /**
73 * @return string|null Timestamp of expiry in TS_MW format, or null if no expiry
74 */
75 public function getExpiry() {
76 return $this->expiry;
77 }
78
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 ?
83 null :
84 wfTimestamp( TS_MW, $row->ug_expiry );
85 }
86
87 /**
88 * Creates a new UserGroupMembership object from a database row.
89 *
90 * @param stdClass $row The row from the user_groups table
91 * @return UserGroupMembership
92 */
93 public static function newFromRow( $row ) {
94 $ugm = new self;
95 $ugm->initFromRow( $row );
96 return $ugm;
97 }
98
99 /**
100 * Returns the list of user_groups fields that should be selected to create
101 * a new user group membership.
102 * @return array
103 */
104 public static function selectFields() {
105 return [
106 'ug_user',
107 'ug_group',
108 'ug_expiry',
109 ];
110 }
111
112 /**
113 * Delete the row from the user_groups table.
114 *
115 * @throws MWException
116 * @param IDatabase|null $dbw Optional master database connection to use
117 * @return bool Whether or not anything was deleted
118 */
119 public function delete( IDatabase $dbw = null ) {
120 if ( wfReadOnly() ) {
121 return false;
122 }
123
124 if ( $dbw === null ) {
125 $dbw = wfGetDB( DB_MASTER );
126 }
127
128 $dbw->delete(
129 'user_groups',
130 [ 'ug_user' => $this->userId, 'ug_group' => $this->group ],
131 __METHOD__ );
132 if ( !$dbw->affectedRows() ) {
133 return false;
134 }
135
136 // Remember that the user was in this group
137 $dbw->insert(
138 'user_former_groups',
139 [ 'ufg_user' => $this->userId, 'ufg_group' => $this->group ],
140 __METHOD__,
141 [ 'IGNORE' ] );
142
143 return true;
144 }
145
146 /**
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.
150 *
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
155 */
156 public function insert( $allowUpdate = false, IDatabase $dbw = null ) {
157 if ( $dbw === null ) {
158 $dbw = wfGetDB( DB_MASTER );
159 }
160
161 // Purge old, expired memberships from the DB
162 $hasExpiredRow = $dbw->selectField(
163 'user_groups',
164 '1',
165 [ 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
166 __METHOD__
167 );
168 if ( $hasExpiredRow ) {
169 JobQueueGroup::singleton()->lazyPush( new UserGroupExpiryJob() );
170 }
171
172 // Check that the values make sense
173 if ( $this->group === null ) {
174 throw new UnexpectedValueException(
175 'Don\'t try inserting an uninitialized UserGroupMembership object' );
176 } elseif ( $this->userId <= 0 ) {
177 throw new UnexpectedValueException(
178 'UserGroupMembership::insert() needs a positive user ID. ' .
179 'Did you forget to add your User object to the database before calling addGroup()?' );
180 }
181
182 $row = $this->getDatabaseArray( $dbw );
183 $dbw->insert( 'user_groups', $row, __METHOD__, [ 'IGNORE' ] );
184 $affected = $dbw->affectedRows();
185
186 // Don't collide with expired user group memberships
187 // Do this after trying to insert, in order to avoid locking
188 if ( !$affected ) {
189 $conds = [
190 'ug_user' => $row['ug_user'],
191 'ug_group' => $row['ug_group'],
192 ];
193 // if we're unconditionally updating, check that the expiry is not already the
194 // same as what we are trying to update it to; otherwise, only update if
195 // the expiry date is in the past
196 if ( $allowUpdate ) {
197 if ( $this->expiry ) {
198 $conds[] = 'ug_expiry IS NULL OR ug_expiry != ' .
199 $dbw->addQuotes( $dbw->timestamp( $this->expiry ) );
200 } else {
201 $conds[] = 'ug_expiry IS NOT NULL';
202 }
203 } else {
204 $conds[] = 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp() );
205 }
206
207 $row = $dbw->selectRow( 'user_groups', $this::selectFields(), $conds, __METHOD__ );
208 if ( $row ) {
209 $dbw->update(
210 'user_groups',
211 [ 'ug_expiry' => $this->expiry ? $dbw->timestamp( $this->expiry ) : null ],
212 [ 'ug_user' => $row->ug_user, 'ug_group' => $row->ug_group ],
213 __METHOD__ );
214 $affected = $dbw->affectedRows();
215 }
216 }
217
218 return $affected > 0;
219 }
220
221 /**
222 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
223 * @param IDatabase $db
224 * @return array
225 */
226 protected function getDatabaseArray( IDatabase $db ) {
227 return [
228 'ug_user' => $this->userId,
229 'ug_group' => $this->group,
230 'ug_expiry' => $this->expiry ? $db->timestamp( $this->expiry ) : null,
231 ];
232 }
233
234 /**
235 * Has the membership expired?
236 * @return bool
237 */
238 public function isExpired() {
239 if ( !$this->expiry ) {
240 return false;
241 }
242 return wfTimestampNow() > $this->expiry;
243 }
244
245 /**
246 * Purge expired memberships from the user_groups table
247 *
248 * @return int|bool false if purging wasn't attempted (e.g. because of
249 * readonly), the number of rows purged (might be 0) otherwise
250 */
251 public static function purgeExpired() {
252 $services = MediaWikiServices::getInstance();
253 if ( $services->getReadOnlyMode()->isReadOnly() ) {
254 return false;
255 }
256
257 $lbFactory = $services->getDBLoadBalancerFactory();
258 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
259 $dbw = $services->getDBLoadBalancer()->getConnectionRef( DB_MASTER );
260
261 $lockKey = "{$dbw->getDomainID()}:UserGroupMembership:purge"; // per-wiki
262 $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 0 );
263 if ( !$scopedLock ) {
264 return false; // already running
265 }
266
267 $now = time();
268 $purgedRows = 0;
269 do {
270 $dbw->startAtomic( __METHOD__ );
271
272 $res = $dbw->select(
273 'user_groups',
274 self::selectFields(),
275 [ 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp( $now ) ) ],
276 __METHOD__,
277 [ 'FOR UPDATE', 'LIMIT' => 100 ]
278 );
279
280 if ( $res->numRows() > 0 ) {
281 $insertData = []; // array of users/groups to insert to user_former_groups
282 $deleteCond = []; // array for deleting the rows that are to be moved around
283 foreach ( $res as $row ) {
284 $insertData[] = [ 'ufg_user' => $row->ug_user, 'ufg_group' => $row->ug_group ];
285 $deleteCond[] = $dbw->makeList(
286 [ 'ug_user' => $row->ug_user, 'ug_group' => $row->ug_group ],
287 $dbw::LIST_AND
288 );
289 }
290 // Delete the rows we're about to move
291 $dbw->delete(
292 'user_groups',
293 $dbw->makeList( $deleteCond, $dbw::LIST_OR ),
294 __METHOD__
295 );
296 // Push the groups to user_former_groups
297 $dbw->insert( 'user_former_groups', $insertData, __METHOD__, [ 'IGNORE' ] );
298 // Count how many rows were purged
299 $purgedRows += $res->numRows();
300 }
301
302 $dbw->endAtomic( __METHOD__ );
303
304 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
305 } while ( $res->numRows() > 0 );
306 return $purgedRows;
307 }
308
309 /**
310 * Returns UserGroupMembership objects for all the groups a user currently
311 * belongs to.
312 *
313 * @param int $userId ID of the user to search for
314 * @param IDatabase|null $db Optional database connection
315 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
316 */
317 public static function getMembershipsForUser( $userId, IDatabase $db = null ) {
318 if ( !$db ) {
319 $db = wfGetDB( DB_REPLICA );
320 }
321
322 $res = $db->select( 'user_groups',
323 self::selectFields(),
324 [ 'ug_user' => $userId ],
325 __METHOD__ );
326
327 $ugms = [];
328 foreach ( $res as $row ) {
329 $ugm = self::newFromRow( $row );
330 if ( !$ugm->isExpired() ) {
331 $ugms[$ugm->group] = $ugm;
332 }
333 }
334 ksort( $ugms );
335
336 return $ugms;
337 }
338
339 /**
340 * Returns a UserGroupMembership object that pertains to the given user and group,
341 * or false if the user does not belong to that group (or the assignment has
342 * expired).
343 *
344 * @param int $userId ID of the user to search for
345 * @param string $group User group name
346 * @param IDatabase|null $db Optional database connection
347 * @return UserGroupMembership|false
348 */
349 public static function getMembership( $userId, $group, IDatabase $db = null ) {
350 if ( !$db ) {
351 $db = wfGetDB( DB_REPLICA );
352 }
353
354 $row = $db->selectRow( 'user_groups',
355 self::selectFields(),
356 [ 'ug_user' => $userId, 'ug_group' => $group ],
357 __METHOD__ );
358 if ( !$row ) {
359 return false;
360 }
361
362 $ugm = self::newFromRow( $row );
363 if ( !$ugm->isExpired() ) {
364 return $ugm;
365 }
366 return false;
367 }
368
369 /**
370 * Gets a link for a user group, possibly including the expiry date if relevant.
371 *
372 * @param string|UserGroupMembership $ugm Either a group name as a string, or
373 * a UserGroupMembership object
374 * @param IContextSource $context
375 * @param string $format Either 'wiki' or 'html'
376 * @param string|null $userName If you want to use the group member message
377 * ("administrator"), pass the name of the user who belongs to the group; it
378 * is used for GENDER of the group member message. If you instead want the
379 * group name message ("Administrators"), omit this parameter.
380 * @return string
381 */
382 public static function getLink( $ugm, IContextSource $context, $format,
383 $userName = null
384 ) {
385 if ( $format !== 'wiki' && $format !== 'html' ) {
386 throw new MWException( 'UserGroupMembership::getLink() $format parameter should be ' .
387 "'wiki' or 'html'" );
388 }
389
390 if ( $ugm instanceof UserGroupMembership ) {
391 $expiry = $ugm->getExpiry();
392 $group = $ugm->getGroup();
393 } else {
394 $expiry = null;
395 $group = $ugm;
396 }
397
398 if ( $userName !== null ) {
399 $groupName = self::getGroupMemberName( $group, $userName );
400 } else {
401 $groupName = self::getGroupName( $group );
402 }
403
404 // link to the group description page, if it exists
405 $linkTitle = self::getGroupPage( $group );
406 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
407 if ( $linkTitle ) {
408 if ( $format === 'wiki' ) {
409 $linkPage = $linkTitle->getFullText();
410 $groupLink = "[[$linkPage|$groupName]]";
411 } else {
412 $groupLink = $linkRenderer->makeLink( $linkTitle, $groupName );
413 }
414 } else {
415 $groupLink = htmlspecialchars( $groupName );
416 }
417
418 if ( $expiry ) {
419 // format the expiry to a nice string
420 $uiLanguage = $context->getLanguage();
421 $uiUser = $context->getUser();
422 $expiryDT = $uiLanguage->userTimeAndDate( $expiry, $uiUser );
423 $expiryD = $uiLanguage->userDate( $expiry, $uiUser );
424 $expiryT = $uiLanguage->userTime( $expiry, $uiUser );
425 if ( $format === 'html' ) {
426 $groupLink = Message::rawParam( $groupLink );
427 }
428 return $context->msg( 'group-membership-link-with-expiry' )
429 ->params( $groupLink, $expiryDT, $expiryD, $expiryT )->text();
430 }
431 return $groupLink;
432 }
433
434 /**
435 * Gets the localized friendly name for a group, if it exists. For example,
436 * "Administrators" or "Bureaucrats"
437 *
438 * @param string $group Internal group name
439 * @return string Localized friendly group name
440 */
441 public static function getGroupName( $group ) {
442 $msg = wfMessage( "group-$group" );
443 return $msg->isBlank() ? $group : $msg->text();
444 }
445
446 /**
447 * Gets the localized name for a member of a group, if it exists. For example,
448 * "administrator" or "bureaucrat"
449 *
450 * @param string $group Internal group name
451 * @param string $username Username for gender
452 * @return string Localized name for group member
453 */
454 public static function getGroupMemberName( $group, $username ) {
455 $msg = wfMessage( "group-$group-member", $username );
456 return $msg->isBlank() ? $group : $msg->text();
457 }
458
459 /**
460 * Gets the title of a page describing a particular user group. When the name
461 * of the group appears in the UI, it can link to this page.
462 *
463 * @param string $group Internal group name
464 * @return Title|bool Title of the page if it exists, false otherwise
465 */
466 public static function getGroupPage( $group ) {
467 $msg = wfMessage( "grouppage-$group" )->inContentLanguage();
468 if ( $msg->exists() ) {
469 $title = Title::newFromText( $msg->text() );
470 if ( is_object( $title ) ) {
471 return $title;
472 }
473 }
474 return false;
475 }
476 }