MediaWiki  1.33.0
UserGroupMembership.php
Go to the documentation of this file.
1 <?php
25 
39  private $userId;
40 
42  private $group;
43 
45  private $expiry;
46 
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 
61  public function getUserId() {
62  return $this->userId;
63  }
64 
68  public function getGroup() {
69  return $this->group;
70  }
71 
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 
93  public static function newFromRow( $row ) {
94  $ugm = new self;
95  $ugm->initFromRow( $row );
96  return $ugm;
97  }
98 
104  public static function selectFields() {
105  return [
106  'ug_user',
107  'ug_group',
108  'ug_expiry',
109  ];
110  }
111 
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 
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
163 
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()?' );
172  }
173 
174  $row = $this->getDatabaseArray( $dbw );
175  $dbw->insert( 'user_groups', $row, __METHOD__, [ 'IGNORE' ] );
176  $affected = $dbw->affectedRows();
177 
178  // Don't collide with expired user group memberships
179  // Do this after trying to insert, in order to avoid locking
180  if ( !$affected ) {
181  $conds = [
182  'ug_user' => $row['ug_user'],
183  'ug_group' => $row['ug_group'],
184  ];
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 ) );
192  } else {
193  $conds[] = 'ug_expiry IS NOT NULL';
194  }
195  } else {
196  $conds[] = 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp() );
197  }
198 
199  $row = $dbw->selectRow( 'user_groups', $this::selectFields(), $conds, __METHOD__ );
200  if ( $row ) {
201  $dbw->update(
202  'user_groups',
203  [ 'ug_expiry' => $this->expiry ? $dbw->timestamp( $this->expiry ) : null ],
204  [ 'ug_user' => $row->ug_user, 'ug_group' => $row->ug_group ],
205  __METHOD__ );
206  $affected = $dbw->affectedRows();
207  }
208  }
209 
210  return $affected > 0;
211  }
212 
218  protected function getDatabaseArray( IDatabase $db ) {
219  return [
220  'ug_user' => $this->userId,
221  'ug_group' => $this->group,
222  'ug_expiry' => $this->expiry ? $db->timestamp( $this->expiry ) : null,
223  ];
224  }
225 
230  public function isExpired() {
231  if ( !$this->expiry ) {
232  return false;
233  }
234  return wfTimestampNow() > $this->expiry;
235  }
236 
243  public static function purgeExpired() {
244  $services = MediaWikiServices::getInstance();
245  if ( $services->getReadOnlyMode()->isReadOnly() ) {
246  return false;
247  }
248 
249  $lbFactory = $services->getDBLoadBalancerFactory();
250  $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
251  $dbw = $services->getDBLoadBalancer()->getConnection( DB_MASTER );
252 
253  $lockKey = $dbw->getDomainID() . ':usergroups-prune'; // specific to this wiki
254  $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 0 );
255  if ( !$scopedLock ) {
256  return false; // already running
257  }
258 
259  $now = time();
260  $purgedRows = 0;
261  do {
262  $dbw->startAtomic( __METHOD__ );
263 
264  $res = $dbw->select(
265  'user_groups',
266  self::selectFields(),
267  [ 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp( $now ) ) ],
268  __METHOD__,
269  [ 'FOR UPDATE', 'LIMIT' => 100 ]
270  );
271 
272  if ( $res->numRows() > 0 ) {
273  $insertData = []; // array of users/groups to insert to user_former_groups
274  $deleteCond = []; // array for deleting the rows that are to be moved around
275  foreach ( $res as $row ) {
276  $insertData[] = [ 'ufg_user' => $row->ug_user, 'ufg_group' => $row->ug_group ];
277  $deleteCond[] = $dbw->makeList(
278  [ 'ug_user' => $row->ug_user, 'ug_group' => $row->ug_group ],
280  );
281  }
282  // Delete the rows we're about to move
283  $dbw->delete(
284  'user_groups',
285  $dbw->makeList( $deleteCond, $dbw::LIST_OR ),
286  __METHOD__
287  );
288  // Push the groups to user_former_groups
289  $dbw->insert( 'user_former_groups', $insertData, __METHOD__, [ 'IGNORE' ] );
290  // Count how many rows were purged
291  $purgedRows += $res->numRows();
292  }
293 
294  $dbw->endAtomic( __METHOD__ );
295 
296  $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
297  } while ( $res->numRows() > 0 );
298  return $purgedRows;
299  }
300 
309  public static function getMembershipsForUser( $userId, IDatabase $db = null ) {
310  if ( !$db ) {
311  $db = wfGetDB( DB_REPLICA );
312  }
313 
314  $res = $db->select( 'user_groups',
315  self::selectFields(),
316  [ 'ug_user' => $userId ],
317  __METHOD__ );
318 
319  $ugms = [];
320  foreach ( $res as $row ) {
321  $ugm = self::newFromRow( $row );
322  if ( !$ugm->isExpired() ) {
323  $ugms[$ugm->group] = $ugm;
324  }
325  }
326  ksort( $ugms );
327 
328  return $ugms;
329  }
330 
341  public static function getMembership( $userId, $group, IDatabase $db = null ) {
342  if ( !$db ) {
343  $db = wfGetDB( DB_REPLICA );
344  }
345 
346  $row = $db->selectRow( 'user_groups',
347  self::selectFields(),
348  [ 'ug_user' => $userId, 'ug_group' => $group ],
349  __METHOD__ );
350  if ( !$row ) {
351  return false;
352  }
353 
354  $ugm = self::newFromRow( $row );
355  if ( !$ugm->isExpired() ) {
356  return $ugm;
357  }
358  return false;
359  }
360 
374  public static function getLink( $ugm, IContextSource $context, $format,
375  $userName = null
376  ) {
377  if ( $format !== 'wiki' && $format !== 'html' ) {
378  throw new MWException( 'UserGroupMembership::getLink() $format parameter should be ' .
379  "'wiki' or 'html'" );
380  }
381 
382  if ( $ugm instanceof UserGroupMembership ) {
383  $expiry = $ugm->getExpiry();
384  $group = $ugm->getGroup();
385  } else {
386  $expiry = null;
387  $group = $ugm;
388  }
389 
390  if ( $userName !== null ) {
391  $groupName = self::getGroupMemberName( $group, $userName );
392  } else {
393  $groupName = self::getGroupName( $group );
394  }
395 
396  // link to the group description page, if it exists
397  $linkTitle = self::getGroupPage( $group );
398  if ( $linkTitle ) {
399  if ( $format === 'wiki' ) {
400  $linkPage = $linkTitle->getFullText();
401  $groupLink = "[[$linkPage|$groupName]]";
402  } else {
403  $groupLink = Linker::link( $linkTitle, htmlspecialchars( $groupName ) );
404  }
405  } else {
406  $groupLink = htmlspecialchars( $groupName );
407  }
408 
409  if ( $expiry ) {
410  // format the expiry to a nice string
411  $uiLanguage = $context->getLanguage();
412  $uiUser = $context->getUser();
413  $expiryDT = $uiLanguage->userTimeAndDate( $expiry, $uiUser );
414  $expiryD = $uiLanguage->userDate( $expiry, $uiUser );
415  $expiryT = $uiLanguage->userTime( $expiry, $uiUser );
416  if ( $format === 'html' ) {
417  $groupLink = Message::rawParam( $groupLink );
418  }
419  return $context->msg( 'group-membership-link-with-expiry' )
420  ->params( $groupLink, $expiryDT, $expiryD, $expiryT )->text();
421  }
422  return $groupLink;
423  }
424 
432  public static function getGroupName( $group ) {
433  $msg = wfMessage( "group-$group" );
434  return $msg->isBlank() ? $group : $msg->text();
435  }
436 
445  public static function getGroupMemberName( $group, $username ) {
446  $msg = wfMessage( "group-$group-member", $username );
447  return $msg->isBlank() ? $group : $msg->text();
448  }
449 
457  public static function getGroupPage( $group ) {
458  $msg = wfMessage( "grouppage-$group" )->inContentLanguage();
459  if ( $msg->exists() ) {
460  $title = Title::newFromText( $msg->text() );
461  if ( is_object( $title ) ) {
462  return $title;
463  }
464  }
465  return false;
466  }
467 }
UserGroupMembership\getDatabaseArray
getDatabaseArray(IDatabase $db)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition: UserGroupMembership.php:218
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:306
Wikimedia\Rdbms\IDatabase\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2636
Wikimedia\Rdbms\IDatabase\makeList
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
UserGroupMembership\insert
insert( $allowUpdate=false, IDatabase $dbw=null)
Insert a user right membership into the database.
Definition: UserGroupMembership.php:156
UserGroupMembership\getExpiry
getExpiry()
Definition: UserGroupMembership.php:75
UserGroupMembership\getGroupName
static getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
Definition: UserGroupMembership.php:432
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1912
UserGroupMembership\$expiry
string null $expiry
Timestamp of expiry in TS_MW format, or null if no expiry.
Definition: UserGroupMembership.php:45
Wikimedia\Rdbms\IDatabase\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1197
$res
$res
Definition: database.txt:21
UserGroupMembership\purgeExpired
static purgeExpired()
Purge expired memberships from the user_groups table.
Definition: UserGroupMembership.php:243
UserGroupMembership\getGroup
getGroup()
Definition: UserGroupMembership.php:68
UserGroupMembership\getGroupPage
static getGroupPage( $group)
Gets the title of a page describing a particular user group.
Definition: UserGroupMembership.php:457
Wikimedia\Rdbms\IDatabase\insert
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
LIST_AND
const LIST_AND
Definition: Defines.php:43
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
UserGroupMembership\getMembershipsForUser
static getMembershipsForUser( $userId, IDatabase $db=null)
Returns UserGroupMembership objects for all the groups a user currently belongs to.
Definition: UserGroupMembership.php:309
UserGroupMembership\getUserId
getUserId()
Definition: UserGroupMembership.php:61
Wikimedia\Rdbms\IDatabase\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
LIST_OR
const LIST_OR
Definition: Defines.php:46
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
UserGroupMembership\getLink
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
Definition: UserGroupMembership.php:374
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2636
UserGroupMembership\newFromRow
static newFromRow( $row)
Creates a new UserGroupMembership object from a database row.
Definition: UserGroupMembership.php:93
UserGroupMembership\__construct
__construct( $userId=0, $group=null, $expiry=null)
Definition: UserGroupMembership.php:52
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1941
DB_MASTER
const DB_MASTER
Definition: defines.php:26
UserGroupExpiryJob
Definition: UserGroupExpiryJob.php:24
UserGroupMembership\isExpired
isExpired()
Has the membership expired?
Definition: UserGroupMembership.php:230
UserGroupMembership\selectFields
static selectFields()
Returns the list of user_groups fields that should be selected to create a new user group membership.
Definition: UserGroupMembership.php:104
null
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
UserGroupMembership\$userId
int $userId
The ID of the user who belongs to the group.
Definition: UserGroupMembership.php:39
Wikimedia\Rdbms\IDatabase\selectRow
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
Wikimedia\Rdbms\IDatabase\getScopedLockAndFlush
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
Wikimedia\Rdbms\IDatabase\getDomainID
getDomainID()
Return the currently selected domain ID.
Linker\link
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:84
Wikimedia\Rdbms\IDatabase\update
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
UserGroupMembership\initFromRow
initFromRow( $row)
Definition: UserGroupMembership.php:79
group
invalid e g too many</span ></p > ! end ! test with< references/> in group ! wikitext Wikipedia rocks< ref > Proceeds of vol XXI</ref > Wikipedia rocks< ref group="note"> Proceeds of vol XXI</ref >< references/>< references group="note"/> ! html< p > Wikipedia rocks< sup id="cite_ref-1" class="reference">< a href="#cite_note-1"> &Wikipedia rocks< sup id="cite_ref-2" class="reference">< a href="#cite_note-2"> &</p >< div class="mw-references-wrap">< ol class="references">< li id="cite_note-1">< span class="mw-cite-backlink">< a href="#cite_ref-1"> ↑</a ></span >< span class="reference-text"> Proceeds of vol XXI</span ></li ></ol ></div >< div class="mw-references-wrap">< ol class="references">< li id="cite_note-2">< span class="mw-cite-backlink">< a href="#cite_ref-2"> ↑</a ></span >< span class="reference-text"> Proceeds of vol XXI</span ></li ></ol ></div > ! end ! test with< references/> in group
Definition: citeParserTests.txt:349
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
Wikimedia\Rdbms\IDatabase\addQuotes
addQuotes( $s)
Adds quotes and backslashes.
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Wikimedia\Rdbms\IDatabase\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
$services
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2220
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
UserGroupMembership\getMembership
static getMembership( $userId, $group, IDatabase $db=null)
Returns a UserGroupMembership object that pertains to the given user and group, or false if the user ...
Definition: UserGroupMembership.php:341
UserGroupMembership\$group
string $group
Definition: UserGroupMembership.php:42
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
UserGroupMembership\getGroupMemberName
static getGroupMemberName( $group, $username)
Gets the localized name for a member of a group, if it exists.
Definition: UserGroupMembership.php:445
Wikimedia\Rdbms\IDatabase\delete
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
UserGroupMembership
Represents a "user group membership" – a specific instance of a user belonging to a group.
Definition: UserGroupMembership.php:37
Wikimedia\Rdbms\IDatabase\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.