MediaWiki  1.30.0
UserGroupMembership.php
Go to the documentation of this file.
1 <?php
24 
38  private $userId;
39 
41  private $group;
42 
44  private $expiry;
45 
51  public function __construct( $userId = 0, $group = null, $expiry = null ) {
52  $this->userId = (int)$userId;
53  $this->group = $group; // TODO throw on invalid group?
54  $this->expiry = $expiry ?: null;
55  }
56 
60  public function getUserId() {
61  return $this->userId;
62  }
63 
67  public function getGroup() {
68  return $this->group;
69  }
70 
74  public function getExpiry() {
75  return $this->expiry;
76  }
77 
78  protected function initFromRow( $row ) {
79  $this->userId = (int)$row->ug_user;
80  $this->group = $row->ug_group;
81  $this->expiry = $row->ug_expiry === null ?
82  null :
83  wfTimestamp( TS_MW, $row->ug_expiry );
84  }
85 
92  public static function newFromRow( $row ) {
93  $ugm = new self;
94  $ugm->initFromRow( $row );
95  return $ugm;
96  }
97 
103  public static function selectFields() {
104  return [
105  'ug_user',
106  'ug_group',
107  'ug_expiry',
108  ];
109  }
110 
118  public function delete( IDatabase $dbw = null ) {
119  if ( wfReadOnly() ) {
120  return false;
121  }
122 
123  if ( $dbw === null ) {
124  $dbw = wfGetDB( DB_MASTER );
125  }
126 
127  $dbw->delete(
128  'user_groups',
129  [ 'ug_user' => $this->userId, 'ug_group' => $this->group ],
130  __METHOD__ );
131  if ( !$dbw->affectedRows() ) {
132  return false;
133  }
134 
135  // Remember that the user was in this group
136  $dbw->insert(
137  'user_former_groups',
138  [ 'ufg_user' => $this->userId, 'ufg_group' => $this->group ],
139  __METHOD__,
140  [ 'IGNORE' ] );
141 
142  return true;
143  }
144 
155  public function insert( $allowUpdate = false, IDatabase $dbw = null ) {
156  if ( $dbw === null ) {
157  $dbw = wfGetDB( DB_MASTER );
158  }
159 
160  // Purge old, expired memberships from the DB
161  self::purgeExpired( $dbw );
162 
163  // Check that the values make sense
164  if ( $this->group === null ) {
165  throw new UnexpectedValueException(
166  'Don\'t try inserting an uninitialized UserGroupMembership object' );
167  } elseif ( $this->userId <= 0 ) {
168  throw new UnexpectedValueException(
169  'UserGroupMembership::insert() needs a positive user ID. ' .
170  'Did you forget to add your User object to the database before calling addGroup()?' );
171  }
172 
173  $row = $this->getDatabaseArray( $dbw );
174  $dbw->insert( 'user_groups', $row, __METHOD__, [ 'IGNORE' ] );
175  $affected = $dbw->affectedRows();
176 
177  // Don't collide with expired user group memberships
178  // Do this after trying to insert, in order to avoid locking
179  if ( !$affected ) {
180  $conds = [
181  'ug_user' => $row['ug_user'],
182  'ug_group' => $row['ug_group'],
183  ];
184  // if we're unconditionally updating, check that the expiry is not already the
185  // same as what we are trying to update it to; otherwise, only update if
186  // the expiry date is in the past
187  if ( $allowUpdate ) {
188  if ( $this->expiry ) {
189  $conds[] = 'ug_expiry IS NULL OR ug_expiry != ' .
190  $dbw->addQuotes( $dbw->timestamp( $this->expiry ) );
191  } else {
192  $conds[] = 'ug_expiry IS NOT NULL';
193  }
194  } else {
195  $conds[] = 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp() );
196  }
197 
198  $row = $dbw->selectRow( 'user_groups', $this::selectFields(), $conds, __METHOD__ );
199  if ( $row ) {
200  $dbw->update(
201  'user_groups',
202  [ 'ug_expiry' => $this->expiry ? $dbw->timestamp( $this->expiry ) : null ],
203  [ 'ug_user' => $row->ug_user, 'ug_group' => $row->ug_group ],
204  __METHOD__ );
205  $affected = $dbw->affectedRows();
206  }
207  }
208 
209  return $affected > 0;
210  }
211 
217  protected function getDatabaseArray( IDatabase $db ) {
218  return [
219  'ug_user' => $this->userId,
220  'ug_group' => $this->group,
221  'ug_expiry' => $this->expiry ? $db->timestamp( $this->expiry ) : null,
222  ];
223  }
224 
229  public function isExpired() {
230  if ( !$this->expiry ) {
231  return false;
232  } else {
233  return wfTimestampNow() > $this->expiry;
234  }
235  }
236 
242  public static function purgeExpired( IDatabase $dbw = null ) {
243  if ( wfReadOnly() ) {
244  return;
245  }
246 
247  if ( $dbw === null ) {
248  $dbw = wfGetDB( DB_MASTER );
249  }
250 
252  $dbw,
253  __METHOD__,
254  function ( IDatabase $dbw, $fname ) {
255  $expiryCond = [ 'ug_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ];
256  $res = $dbw->select( 'user_groups', self::selectFields(), $expiryCond, $fname );
257 
258  // save an array of users/groups to insert to user_former_groups
259  $usersAndGroups = [];
260  foreach ( $res as $row ) {
261  $usersAndGroups[] = [ 'ufg_user' => $row->ug_user, 'ufg_group' => $row->ug_group ];
262  }
263 
264  // delete 'em all
265  $dbw->delete( 'user_groups', $expiryCond, $fname );
266 
267  // and push the groups to user_former_groups
268  $dbw->insert( 'user_former_groups', $usersAndGroups, __METHOD__, [ 'IGNORE' ] );
269  }
270  ) );
271  }
272 
281  public static function getMembershipsForUser( $userId, IDatabase $db = null ) {
282  if ( !$db ) {
283  $db = wfGetDB( DB_REPLICA );
284  }
285 
286  $res = $db->select( 'user_groups',
287  self::selectFields(),
288  [ 'ug_user' => $userId ],
289  __METHOD__ );
290 
291  $ugms = [];
292  foreach ( $res as $row ) {
293  $ugm = self::newFromRow( $row );
294  if ( !$ugm->isExpired() ) {
295  $ugms[$ugm->group] = $ugm;
296  }
297  }
298 
299  return $ugms;
300  }
301 
312  public static function getMembership( $userId, $group, IDatabase $db = null ) {
313  if ( !$db ) {
314  $db = wfGetDB( DB_REPLICA );
315  }
316 
317  $row = $db->selectRow( 'user_groups',
318  self::selectFields(),
319  [ 'ug_user' => $userId, 'ug_group' => $group ],
320  __METHOD__ );
321  if ( !$row ) {
322  return false;
323  }
324 
325  $ugm = self::newFromRow( $row );
326  if ( !$ugm->isExpired() ) {
327  return $ugm;
328  } else {
329  return false;
330  }
331  }
332 
346  public static function getLink( $ugm, IContextSource $context, $format,
347  $userName = null
348  ) {
349  if ( $format !== 'wiki' && $format !== 'html' ) {
350  throw new MWException( 'UserGroupMembership::getLink() $format parameter should be ' .
351  "'wiki' or 'html'" );
352  }
353 
354  if ( $ugm instanceof UserGroupMembership ) {
355  $expiry = $ugm->getExpiry();
356  $group = $ugm->getGroup();
357  } else {
358  $expiry = null;
359  $group = $ugm;
360  }
361 
362  if ( $userName !== null ) {
363  $groupName = self::getGroupMemberName( $group, $userName );
364  } else {
365  $groupName = self::getGroupName( $group );
366  }
367 
368  // link to the group description page, if it exists
369  $linkTitle = self::getGroupPage( $group );
370  if ( $linkTitle ) {
371  if ( $format === 'wiki' ) {
372  $linkPage = $linkTitle->getFullText();
373  $groupLink = "[[$linkPage|$groupName]]";
374  } else {
375  $groupLink = Linker::link( $linkTitle, htmlspecialchars( $groupName ) );
376  }
377  } else {
378  $groupLink = htmlspecialchars( $groupName );
379  }
380 
381  if ( $expiry ) {
382  // format the expiry to a nice string
383  $uiLanguage = $context->getLanguage();
384  $uiUser = $context->getUser();
385  $expiryDT = $uiLanguage->userTimeAndDate( $expiry, $uiUser );
386  $expiryD = $uiLanguage->userDate( $expiry, $uiUser );
387  $expiryT = $uiLanguage->userTime( $expiry, $uiUser );
388  if ( $format === 'html' ) {
389  $groupLink = Message::rawParam( $groupLink );
390  }
391  return $context->msg( 'group-membership-link-with-expiry' )
392  ->params( $groupLink, $expiryDT, $expiryD, $expiryT )->text();
393  } else {
394  return $groupLink;
395  }
396  }
397 
405  public static function getGroupName( $group ) {
406  $msg = wfMessage( "group-$group" );
407  return $msg->isBlank() ? $group : $msg->text();
408  }
409 
418  public static function getGroupMemberName( $group, $username ) {
419  $msg = wfMessage( "group-$group-member", $username );
420  return $msg->isBlank() ? $group : $msg->text();
421  }
422 
430  public static function getGroupPage( $group ) {
431  $msg = wfMessage( "grouppage-$group" )->inContentLanguage();
432  if ( $msg->exists() ) {
433  $title = Title::newFromText( $msg->text() );
434  if ( is_object( $title ) ) {
435  return $title;
436  }
437  }
438  return false;
439  }
440 }
UserGroupMembership\getDatabaseArray
getDatabaseArray(IDatabase $db)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition: UserGroupMembership.php:217
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:268
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:2581
UserGroupMembership\insert
insert( $allowUpdate=false, IDatabase $dbw=null)
Insert a user right membership into the database.
Definition: UserGroupMembership.php:155
UserGroupMembership\getExpiry
getExpiry()
Definition: UserGroupMembership.php:74
UserGroupMembership\getGroupName
static getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
Definition: UserGroupMembership.php:405
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2040
UserGroupMembership\$expiry
string null $expiry
Timestamp of expiry in TS_MW format, or null if no expiry.
Definition: UserGroupMembership.php:44
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
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
Definition: DeferredUpdates.php:76
$fname
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition: Setup.php:36
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1324
$res
$res
Definition: database.txt:21
UserGroupMembership\getGroup
getGroup()
Definition: UserGroupMembership.php:67
UserGroupMembership\getGroupPage
static getGroupPage( $group)
Gets the title of a page describing a particular user group.
Definition: UserGroupMembership.php:430
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
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
UserGroupMembership\getMembershipsForUser
static getMembershipsForUser( $userId, IDatabase $db=null)
Returns UserGroupMembership objects for all the groups a user currently belongs to.
Definition: UserGroupMembership.php:281
UserGroupMembership\getUserId
getUserId()
Definition: UserGroupMembership.php:60
Wikimedia\Rdbms\IDatabase\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
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:932
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:346
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2856
UserGroupMembership\purgeExpired
static purgeExpired(IDatabase $dbw=null)
Purge expired memberships from the user_groups table.
Definition: UserGroupMembership.php:242
UserGroupMembership\newFromRow
static newFromRow( $row)
Creates a new UserGroupMembership object from a database row.
Definition: UserGroupMembership.php:92
UserGroupMembership\__construct
__construct( $userId=0, $group=null, $expiry=null)
Definition: UserGroupMembership.php:51
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2069
DB_MASTER
const DB_MASTER
Definition: defines.php:26
UserGroupMembership\isExpired
isExpired()
Has the membership expired?
Definition: UserGroupMembership.php:229
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:103
UserGroupMembership\$userId
int $userId
The ID of the user who belongs to the group.
Definition: UserGroupMembership.php:38
AtomicSectionUpdate
Deferrable Update for closure/callback updates via IDatabase::doAtomicSection()
Definition: AtomicSectionUpdate.php:9
Wikimedia\Rdbms\IDatabase\selectRow
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
Linker\link
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:107
Wikimedia\Rdbms\IDatabase\update
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
UserGroupMembership\initFromRow
initFromRow( $row)
Definition: UserGroupMembership.php:78
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
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.
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 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
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:312
UserGroupMembership\$group
string $group
Definition: UserGroupMembership.php:41
group
no text was provided for refs named< code > blankwithnoreference</code ></span ></li ></ol ></div > ! 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:306
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:781
UserGroupMembership\getGroupMemberName
static getGroupMemberName( $group, $username)
Gets the localized name for a member of a group, if it exists.
Definition: UserGroupMembership.php:418
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:36