MediaWiki  master
BlockRestriction.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Block;
24 
31 
33 
37  private static $types = [
40  ];
41 
50  public static function loadByBlockId( $blockId, IDatabase $db = null ) {
51  if ( $blockId === null || $blockId === [] ) {
52  return [];
53  }
54 
55  $db = $db ?: wfGetDB( DB_REPLICA );
56 
57  $result = $db->select(
58  [ 'ipblocks_restrictions', 'page' ],
59  [ 'ir_ipb_id', 'ir_type', 'ir_value', 'page_namespace', 'page_title' ],
60  [ 'ir_ipb_id' => $blockId ],
61  __METHOD__,
62  [],
63  [ 'page' => [ 'LEFT JOIN', [ 'ir_type' => PageRestriction::TYPE_ID, 'ir_value=page_id' ] ] ]
64  );
65 
66  return self::resultToRestrictions( $result );
67  }
68 
76  public static function insert( array $restrictions ) {
77  if ( !$restrictions ) {
78  return false;
79  }
80 
81  $rows = [];
82  foreach ( $restrictions as $restriction ) {
83  if ( !$restriction instanceof Restriction ) {
84  continue;
85  }
86  $rows[] = $restriction->toRow();
87  }
88 
89  if ( !$rows ) {
90  return false;
91  }
92 
93  $dbw = wfGetDB( DB_MASTER );
94 
95  $dbw->insert(
96  'ipblocks_restrictions',
97  $rows,
98  __METHOD__,
99  [ 'IGNORE' ]
100  );
101 
102  return true;
103  }
104 
113  public static function update( array $restrictions ) {
114  $dbw = wfGetDB( DB_MASTER );
115 
116  $dbw->startAtomic( __METHOD__ );
117 
118  // Organize the restrictions by blockid.
119  $restrictionList = self::restrictionsByBlockId( $restrictions );
120 
121  // Load the existing restrictions and organize by block id. Any block ids
122  // that were passed into this function will be used to load all of the
123  // existing restrictions. This list might be the same, or may be completely
124  // different.
125  $existingList = [];
126  $blockIds = array_keys( $restrictionList );
127  if ( !empty( $blockIds ) ) {
128  $result = $dbw->select(
129  [ 'ipblocks_restrictions' ],
130  [ 'ir_ipb_id', 'ir_type', 'ir_value' ],
131  [ 'ir_ipb_id' => $blockIds ],
132  __METHOD__,
133  [ 'FOR UPDATE' ]
134  );
135 
136  $existingList = self::restrictionsByBlockId(
137  self::resultToRestrictions( $result )
138  );
139  }
140 
141  $result = true;
142  // Perform the actions on a per block-id basis.
143  foreach ( $restrictionList as $blockId => $blockRestrictions ) {
144  // Insert all of the restrictions first, ignoring ones that already exist.
145  $success = self::insert( $blockRestrictions );
146 
147  // Update the result. The first false is the result, otherwise, true.
148  $result = $success && $result;
149 
150  $restrictionsToRemove = self::restrictionsToRemove(
151  $existingList[$blockId] ?? [],
152  $restrictions
153  );
154 
155  if ( empty( $restrictionsToRemove ) ) {
156  continue;
157  }
158 
159  $success = self::delete( $restrictionsToRemove );
160 
161  // Update the result. The first false is the result, otherwise, true.
162  $result = $success && $result;
163  }
164 
165  $dbw->endAtomic( __METHOD__ );
166 
167  return $result;
168  }
169 
178  public static function updateByParentBlockId( $parentBlockId, array $restrictions ) {
179  // If removing all of the restrictions, then just delete them all.
180  if ( empty( $restrictions ) ) {
181  return self::deleteByParentBlockId( $parentBlockId );
182  }
183 
184  $parentBlockId = (int)$parentBlockId;
185 
186  $db = wfGetDB( DB_MASTER );
187 
188  $db->startAtomic( __METHOD__ );
189 
190  $blockIds = $db->selectFieldValues(
191  'ipblocks',
192  'ipb_id',
193  [ 'ipb_parent_block_id' => $parentBlockId ],
194  __METHOD__,
195  [ 'FOR UPDATE' ]
196  );
197 
198  $result = true;
199  foreach ( $blockIds as $id ) {
200  $success = self::update( self::setBlockId( $id, $restrictions ) );
201  // Update the result. The first false is the result, otherwise, true.
202  $result = $success && $result;
203  }
204 
205  $db->endAtomic( __METHOD__ );
206 
207  return $result;
208  }
209 
218  public static function delete( array $restrictions ) {
219  $dbw = wfGetDB( DB_MASTER );
220  $result = true;
221  foreach ( $restrictions as $restriction ) {
222  if ( !$restriction instanceof Restriction ) {
223  continue;
224  }
225 
226  $success = $dbw->delete(
227  'ipblocks_restrictions',
228  // The restriction row is made up of a compound primary key. Therefore,
229  // the row and the delete conditions are the same.
230  $restriction->toRow(),
231  __METHOD__
232  );
233  // Update the result. The first false is the result, otherwise, true.
234  $result = $success && $result;
235  }
236 
237  return $result;
238  }
239 
248  public static function deleteByBlockId( $blockId ) {
249  $dbw = wfGetDB( DB_MASTER );
250  return $dbw->delete(
251  'ipblocks_restrictions',
252  [ 'ir_ipb_id' => $blockId ],
253  __METHOD__
254  );
255  }
256 
265  public static function deleteByParentBlockId( $parentBlockId ) {
266  $dbw = wfGetDB( DB_MASTER );
267  return $dbw->deleteJoin(
268  'ipblocks_restrictions',
269  'ipblocks',
270  'ir_ipb_id',
271  'ipb_id',
272  [ 'ipb_parent_block_id' => $parentBlockId ],
273  __METHOD__
274  );
275  }
276 
287  public static function equals( array $a, array $b ) {
288  $filter = function ( $restriction ) {
289  return $restriction instanceof Restriction;
290  };
291 
292  // Ensure that every item in the array is a Restriction. This prevents a
293  // fatal error from calling Restriction::getHash if something in the array
294  // is not a restriction.
295  $a = array_filter( $a, $filter );
296  $b = array_filter( $b, $filter );
297 
298  $aCount = count( $a );
299  $bCount = count( $b );
300 
301  // If the count is different, then they are obviously a different set.
302  if ( $aCount !== $bCount ) {
303  return false;
304  }
305 
306  // If both sets contain no items, then they are the same set.
307  if ( $aCount === 0 && $bCount === 0 ) {
308  return true;
309  }
310 
311  $hasher = function ( $r ) {
312  return $r->getHash();
313  };
314 
315  $aHashes = array_map( $hasher, $a );
316  $bHashes = array_map( $hasher, $b );
317 
318  sort( $aHashes );
319  sort( $bHashes );
320 
321  return $aHashes === $bHashes;
322  }
323 
332  public static function setBlockId( $blockId, array $restrictions ) {
333  $blockRestrictions = [];
334 
335  foreach ( $restrictions as $restriction ) {
336  if ( !$restriction instanceof Restriction ) {
337  continue;
338  }
339 
340  // Clone the restriction so any references to the current restriction are
341  // not suddenly changed to a different blockId.
342  $restriction = clone $restriction;
343  $restriction->setBlockId( $blockId );
344 
345  $blockRestrictions[] = $restriction;
346  }
347 
348  return $blockRestrictions;
349  }
350 
359  private static function restrictionsToRemove( array $existing, array $new ) {
360  return array_filter( $existing, function ( $e ) use ( $new ) {
361  foreach ( $new as $restriction ) {
362  if ( !$restriction instanceof Restriction ) {
363  continue;
364  }
365 
366  if ( $restriction->equals( $e ) ) {
367  return false;
368  }
369  }
370 
371  return true;
372  } );
373  }
374 
382  private static function restrictionsByBlockId( array $restrictions ) {
383  $blockRestrictions = [];
384 
385  foreach ( $restrictions as $restriction ) {
386  // Ensure that all of the items in the array are restrictions.
387  if ( !$restriction instanceof Restriction ) {
388  continue;
389  }
390 
391  if ( !isset( $blockRestrictions[$restriction->getBlockId()] ) ) {
392  $blockRestrictions[$restriction->getBlockId()] = [];
393  }
394 
395  $blockRestrictions[$restriction->getBlockId()][] = $restriction;
396  }
397 
398  return $blockRestrictions;
399  }
400 
407  private static function resultToRestrictions( IResultWrapper $result ) {
408  $restrictions = [];
409  foreach ( $result as $row ) {
410  $restriction = self::rowToRestriction( $row );
411 
412  if ( !$restriction ) {
413  continue;
414  }
415 
416  $restrictions[] = $restriction;
417  }
418 
419  return $restrictions;
420  }
421 
428  private static function rowToRestriction( \stdClass $row ) {
429  if ( array_key_exists( (int)$row->ir_type, self::$types ) ) {
430  $class = self::$types[ (int)$row->ir_type ];
431  return call_user_func( [ $class, 'newFromRow' ], $row );
432  }
433 
434  return null;
435  }
436 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
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 $rows
Definition: hooks.txt:2633
static insert(array $restrictions)
Inserts the restrictions into the database.
static loadByBlockId( $blockId, IDatabase $db=null)
Retrieves the restrictions from the database by block id.
$success
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
static updateByParentBlockId( $parentBlockId, array $restrictions)
Updates the list of restrictions by parent id.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
static rowToRestriction(\stdClass $row)
Convert a result row from the database into a restriction object.
const DB_MASTER
Definition: defines.php:26
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
static setBlockId( $blockId, array $restrictions)
Set the blockId on a set of restrictions and return a new set.
static $types
Map of all of the restriction types.
Result wrapper for grabbing data queried from an IDatabase object.
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
static restrictionsByBlockId(array $restrictions)
Converts an array of restrictions to an associative array of restrictions where the keys are the bloc...
$filter
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
static equals(array $a, array $b)
Checks if two arrays of Restrictions are effectively equal.
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
static restrictionsToRemove(array $existing, array $new)
Get the restrictions that should be removed, which are existing restrictions that are not in the new ...
static update(array $restrictions)
Updates the list of restrictions.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static deleteByParentBlockId( $parentBlockId)
Delete the restrictions by Parent Block ID.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and insert
Definition: hooks.txt:2061
static resultToRestrictions(IResultWrapper $result)
Convert an Result Wrapper to an array of restrictions.
const DB_REPLICA
Definition: defines.php:25
static deleteByBlockId( $blockId)
Delete the restrictions by Block ID.