MediaWiki  master
BlockListPager.php
Go to the documentation of this file.
1 <?php
31 
32 class BlockListPager extends TablePager {
33 
34  protected $conds;
35 
41  protected $restrictions = [];
42 
47  public function __construct( $page, $conds ) {
48  $this->conds = $conds;
49  $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
50  parent::__construct( $page->getContext() );
51  }
52 
53  function getFieldNames() {
54  static $headers = null;
55 
56  if ( $headers === null ) {
57  $headers = [
58  'ipb_timestamp' => 'blocklist-timestamp',
59  'ipb_target' => 'blocklist-target',
60  'ipb_expiry' => 'blocklist-expiry',
61  'ipb_by' => 'blocklist-by',
62  'ipb_params' => 'blocklist-params',
63  'ipb_reason' => 'blocklist-reason',
64  ];
65  foreach ( $headers as $key => $val ) {
66  $headers[$key] = $this->msg( $val )->text();
67  }
68  }
69 
70  return $headers;
71  }
72 
73  function formatValue( $name, $value ) {
74  static $msg = null;
75  if ( $msg === null ) {
76  $keys = [
77  'anononlyblock',
78  'createaccountblock',
79  'noautoblockblock',
80  'emailblock',
81  'blocklist-nousertalk',
82  'unblocklink',
83  'change-blocklink',
84  'blocklist-editing',
85  'blocklist-editing-sitewide',
86  ];
87 
88  foreach ( $keys as $key ) {
89  $msg[$key] = $this->msg( $key )->text();
90  }
91  }
92 
94  $row = $this->mCurrentRow;
95 
96  $language = $this->getLanguage();
97 
98  $formatted = '';
99 
100  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
101 
102  switch ( $name ) {
103  case 'ipb_timestamp':
104  $formatted = htmlspecialchars( $language->userTimeAndDate( $value, $this->getUser() ) );
105  break;
106 
107  case 'ipb_target':
108  if ( $row->ipb_auto ) {
109  $formatted = $this->msg( 'autoblockid', $row->ipb_id )->parse();
110  } else {
111  list( $target, $type ) = DatabaseBlock::parseTarget( $row->ipb_address );
112  switch ( $type ) {
113  case DatabaseBlock::TYPE_USER:
114  case DatabaseBlock::TYPE_IP:
115  $formatted = Linker::userLink( $target->getId(), $target );
116  $formatted .= Linker::userToolLinks(
117  $target->getId(),
118  $target,
119  false,
121  );
122  break;
123  case DatabaseBlock::TYPE_RANGE:
124  $formatted = htmlspecialchars( $target );
125  }
126  }
127  break;
128 
129  case 'ipb_expiry':
130  $formatted = htmlspecialchars( $language->formatExpiry(
131  $value,
132  /* User preference timezone */true
133  ) );
134  if ( $this->getUser()->isAllowed( 'block' ) ) {
135  if ( $row->ipb_auto ) {
136  $links[] = $linkRenderer->makeKnownLink(
137  SpecialPage::getTitleFor( 'Unblock' ),
138  $msg['unblocklink'],
139  [],
140  [ 'wpTarget' => "#{$row->ipb_id}" ]
141  );
142  } else {
143  $links[] = $linkRenderer->makeKnownLink(
144  SpecialPage::getTitleFor( 'Unblock', $row->ipb_address ),
145  $msg['unblocklink']
146  );
147  $links[] = $linkRenderer->makeKnownLink(
148  SpecialPage::getTitleFor( 'Block', $row->ipb_address ),
149  $msg['change-blocklink']
150  );
151  }
152  $formatted .= ' ' . Html::rawElement(
153  'span',
154  [ 'class' => 'mw-blocklist-actions' ],
155  $this->msg( 'parentheses' )->rawParams(
156  $language->pipeList( $links ) )->escaped()
157  );
158  }
159  if ( $value !== 'infinity' ) {
160  $timestamp = new MWTimestamp( $value );
161  $formatted .= '<br />' . $this->msg(
162  'ipb-blocklist-duration-left',
163  $language->formatDuration(
164  $timestamp->getTimestamp() - MWTimestamp::time(),
165  // reasonable output
166  [
167  'minutes',
168  'hours',
169  'days',
170  'years',
171  ]
172  )
173  )->escaped();
174  }
175  break;
176 
177  case 'ipb_by':
178  if ( isset( $row->by_user_name ) ) {
179  $formatted = Linker::userLink( $value, $row->by_user_name );
180  $formatted .= Linker::userToolLinks( $value, $row->by_user_name );
181  } else {
182  $formatted = htmlspecialchars( $row->ipb_by_text ); // foreign user?
183  }
184  break;
185 
186  case 'ipb_reason':
187  $value = CommentStore::getStore()->getComment( 'ipb_reason', $row )->text;
188  $formatted = Linker::formatComment( $value );
189  break;
190 
191  case 'ipb_params':
192  $properties = [];
193 
194  if ( $this->getConfig()->get( 'EnablePartialBlocks' ) && $row->ipb_sitewide ) {
195  $properties[] = htmlspecialchars( $msg['blocklist-editing-sitewide'] );
196  }
197 
198  if ( !$row->ipb_sitewide && $this->restrictions ) {
199  $list = $this->getRestrictionListHTML( $row );
200  if ( $list ) {
201  $properties[] = htmlspecialchars( $msg['blocklist-editing'] ) . $list;
202  }
203  }
204 
205  if ( $row->ipb_anon_only ) {
206  $properties[] = htmlspecialchars( $msg['anononlyblock'] );
207  }
208  if ( $row->ipb_create_account ) {
209  $properties[] = htmlspecialchars( $msg['createaccountblock'] );
210  }
211  if ( $row->ipb_user && !$row->ipb_enable_autoblock ) {
212  $properties[] = htmlspecialchars( $msg['noautoblockblock'] );
213  }
214 
215  if ( $row->ipb_block_email ) {
216  $properties[] = htmlspecialchars( $msg['emailblock'] );
217  }
218 
219  if ( !$row->ipb_allow_usertalk ) {
220  $properties[] = htmlspecialchars( $msg['blocklist-nousertalk'] );
221  }
222 
223  $formatted = Html::rawElement(
224  'ul',
225  [],
226  implode( '', array_map( function ( $prop ) {
227  return Html::rawElement(
228  'li',
229  [],
230  $prop
231  );
232  }, $properties ) )
233  );
234  break;
235 
236  default:
237  $formatted = "Unable to format $name";
238  break;
239  }
240 
241  return $formatted;
242  }
243 
251  private function getRestrictionListHTML( stdClass $row ) {
252  $items = [];
253  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
254 
255  foreach ( $this->restrictions as $restriction ) {
256  if ( $restriction->getBlockId() !== (int)$row->ipb_id ) {
257  continue;
258  }
259 
260  switch ( $restriction->getType() ) {
261  case PageRestriction::TYPE:
262  if ( $restriction->getTitle() ) {
263  $items[$restriction->getType()][] = Html::rawElement(
264  'li',
265  [],
266  $linkRenderer->makeLink( $restriction->getTitle() )
267  );
268  }
269  break;
270  case NamespaceRestriction::TYPE:
271  $text = $restriction->getValue() === NS_MAIN
272  ? $this->msg( 'blanknamespace' )->text()
273  : $this->getLanguage()->getFormattedNsText(
274  $restriction->getValue()
275  );
276  $items[$restriction->getType()][] = Html::rawElement(
277  'li',
278  [],
279  $linkRenderer->makeLink(
280  SpecialPage::getTitleValueFor( 'Allpages' ),
281  $text,
282  [],
283  [
284  'namespace' => $restriction->getValue()
285  ]
286  )
287  );
288  break;
289  }
290  }
291 
292  if ( empty( $items ) ) {
293  return '';
294  }
295 
296  $sets = [];
297  foreach ( $items as $key => $value ) {
298  $sets[] = Html::rawElement(
299  'li',
300  [],
301  $this->msg( 'blocklist-editing-' . $key ) . Html::rawElement(
302  'ul',
303  [],
304  implode( '', $value )
305  )
306  );
307  }
308 
309  return Html::rawElement(
310  'ul',
311  [],
312  implode( '', $sets )
313  );
314  }
315 
316  function getQueryInfo() {
317  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
318  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
319 
320  $info = [
321  'tables' => array_merge(
322  [ 'ipblocks' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
323  ),
324  'fields' => [
325  'ipb_id',
326  'ipb_address',
327  'ipb_user',
328  'by_user_name' => 'user_name',
329  'ipb_timestamp',
330  'ipb_auto',
331  'ipb_anon_only',
332  'ipb_create_account',
333  'ipb_enable_autoblock',
334  'ipb_expiry',
335  'ipb_range_start',
336  'ipb_range_end',
337  'ipb_deleted',
338  'ipb_block_email',
339  'ipb_allow_usertalk',
340  'ipb_sitewide',
341  ] + $commentQuery['fields'] + $actorQuery['fields'],
342  'conds' => $this->conds,
343  'join_conds' => [
344  'user' => [ 'LEFT JOIN', 'user_id = ' . $actorQuery['fields']['ipb_by'] ]
345  ] + $commentQuery['joins'] + $actorQuery['joins']
346  ];
347 
348  # Filter out any expired blocks
349  $db = $this->getDatabase();
350  $info['conds'][] = 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() );
351 
352  # Is the user allowed to see hidden blocks?
353  if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
354  $info['conds']['ipb_deleted'] = 0;
355  }
356 
357  return $info;
358  }
359 
365  function getTotalAutoblocks() {
366  $dbr = $this->getDatabase();
367  $res = $dbr->selectField( 'ipblocks',
368  [ 'COUNT(*) AS totalautoblocks' ],
369  [
370  'ipb_auto' => '1',
371  'ipb_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() ),
372  ]
373  );
374  if ( $res ) {
375  return $res;
376  }
377  return 0; // We found nothing
378  }
379 
380  protected function getTableClass() {
381  return parent::getTableClass() . ' mw-blocklist';
382  }
383 
384  function getIndexField() {
385  return 'ipb_timestamp';
386  }
387 
388  function getDefaultSort() {
389  return 'ipb_timestamp';
390  }
391 
392  function isFieldSortable( $name ) {
393  return false;
394  }
395 
401  # Do a link batch query
402  $lb = new LinkBatch;
403  $lb->setCaller( __METHOD__ );
404 
405  $partialBlocks = [];
406  foreach ( $result as $row ) {
407  $lb->add( NS_USER, $row->ipb_address );
408  $lb->add( NS_USER_TALK, $row->ipb_address );
409 
410  if ( isset( $row->by_user_name ) ) {
411  $lb->add( NS_USER, $row->by_user_name );
412  $lb->add( NS_USER_TALK, $row->by_user_name );
413  }
414 
415  if ( !$row->ipb_sitewide ) {
416  $partialBlocks[] = $row->ipb_id;
417  }
418  }
419 
420  if ( $partialBlocks ) {
421  // Mutations to the $row object are not persisted. The restrictions will
422  // need be stored in a separate store.
423  $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
424  $this->restrictions = $blockRestrictionStore->loadByBlockId( $partialBlocks );
425  }
426 
427  $lb->execute();
428  }
429 
430 }
static getTitleValueFor( $name, $subpage=false, $fragment='')
Get a localised TitleValue object for a specified special page name.
Definition: SpecialPage.php:98
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:75
stdClass $mCurrentRow
Definition: TablePager.php:33
setCaller( $caller)
Use ->setCaller( METHOD ) to indicate which code is using this class.
Definition: LinkBatch.php:62
Table-based display with a user-selectable sort order.
Definition: TablePager.php:28
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
const NS_MAIN
Definition: Defines.php:60
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition: hooks.txt:1982
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
$value
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
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getDatabase()
Get the Database object in use.
Definition: IndexPager.php:219
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
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
formatValue( $name, $value)
static newMigration()
Static constructor.
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1160
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null, $useParentheses=true)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition: Linker.php:945
$res
Definition: database.txt:21
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition: Linker.php:38
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 getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
__construct( $page, $conds)
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 userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:900
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 getStore()
preprocessResults( $result)
Do a LinkBatch query to minimise database load when generating all these links.
Restriction [] $restrictions
Array of restrictions.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const NS_USER_TALK
Definition: Defines.php:63
isFieldSortable( $name)
getRestrictionListHTML(stdClass $row)
Get Restriction List HTML.
getTotalAutoblocks()
Get total number of autoblocks at any given time.