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 ) = Block::parseTarget( $row->ipb_address );
112  switch ( $type ) {
113  case Block::TYPE_USER:
114  case Block::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 Block::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 
254  foreach ( $this->restrictions as $restriction ) {
255  if ( $restriction->getBlockId() !== (int)$row->ipb_id ) {
256  continue;
257  }
258 
259  switch ( $restriction->getType() ) {
260  case PageRestriction::TYPE:
261  if ( $restriction->getTitle() ) {
262  $items[$restriction->getType()][] = Html::rawElement(
263  'li',
264  [],
265  Linker::link( $restriction->getTitle() )
266  );
267  }
268  break;
269  case NamespaceRestriction::TYPE:
270  $text = $restriction->getValue() === NS_MAIN
271  ? $this->msg( 'blanknamespace' )
272  : $this->getLanguage()->getFormattedNsText(
273  $restriction->getValue()
274  );
275  $items[$restriction->getType()][] = Html::rawElement(
276  'li',
277  [],
278  Linker::link(
279  SpecialPage::getTitleValueFor( 'Allpages' ),
280  $text,
281  [],
282  [
283  'namespace' => $restriction->getValue()
284  ]
285  )
286  );
287  break;
288  }
289  }
290 
291  if ( empty( $items ) ) {
292  return '';
293  }
294 
295  $sets = [];
296  foreach ( $items as $key => $value ) {
297  $sets[] = Html::rawElement(
298  'li',
299  [],
300  $this->msg( 'blocklist-editing-' . $key ) . Html::rawElement(
301  'ul',
302  [],
303  implode( '', $value )
304  )
305  );
306  }
307 
308  return Html::rawElement(
309  'ul',
310  [],
311  implode( '', $sets )
312  );
313  }
314 
315  function getQueryInfo() {
316  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
317  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
318 
319  $info = [
320  'tables' => array_merge(
321  [ 'ipblocks' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
322  ),
323  'fields' => [
324  'ipb_id',
325  'ipb_address',
326  'ipb_user',
327  'by_user_name' => 'user_name',
328  'ipb_timestamp',
329  'ipb_auto',
330  'ipb_anon_only',
331  'ipb_create_account',
332  'ipb_enable_autoblock',
333  'ipb_expiry',
334  'ipb_range_start',
335  'ipb_range_end',
336  'ipb_deleted',
337  'ipb_block_email',
338  'ipb_allow_usertalk',
339  'ipb_sitewide',
340  ] + $commentQuery['fields'] + $actorQuery['fields'],
341  'conds' => $this->conds,
342  'join_conds' => [
343  'user' => [ 'LEFT JOIN', 'user_id = ' . $actorQuery['fields']['ipb_by'] ]
344  ] + $commentQuery['joins'] + $actorQuery['joins']
345  ];
346 
347  # Filter out any expired blocks
348  $db = $this->getDatabase();
349  $info['conds'][] = 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() );
350 
351  # Is the user allowed to see hidden blocks?
352  if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
353  $info['conds']['ipb_deleted'] = 0;
354  }
355 
356  return $info;
357  }
358 
364  function getTotalAutoblocks() {
365  $dbr = $this->getDatabase();
366  $res = $dbr->selectField( 'ipblocks',
367  [ 'COUNT(*) AS totalautoblocks' ],
368  [
369  'ipb_auto' => '1',
370  'ipb_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() ),
371  ]
372  );
373  if ( $res ) {
374  return $res;
375  }
376  return 0; // We found nothing
377  }
378 
379  protected function getTableClass() {
380  return parent::getTableClass() . ' mw-blocklist';
381  }
382 
383  function getIndexField() {
384  return 'ipb_timestamp';
385  }
386 
387  function getDefaultSort() {
388  return 'ipb_timestamp';
389  }
390 
391  function isFieldSortable( $name ) {
392  return false;
393  }
394 
400  # Do a link batch query
401  $lb = new LinkBatch;
402  $lb->setCaller( __METHOD__ );
403 
404  $partialBlocks = [];
405  foreach ( $result as $row ) {
406  $lb->add( NS_USER, $row->ipb_address );
407  $lb->add( NS_USER_TALK, $row->ipb_address );
408 
409  if ( isset( $row->by_user_name ) ) {
410  $lb->add( NS_USER, $row->by_user_name );
411  $lb->add( NS_USER_TALK, $row->by_user_name );
412  }
413 
414  if ( !$row->ipb_sitewide ) {
415  $partialBlocks[] = $row->ipb_id;
416  }
417  }
418 
419  if ( $partialBlocks ) {
420  // Mutations to the $row object are not persisted. The restrictions will
421  // need be stored in a separate store.
422  $this->restrictions = BlockRestriction::loadByBlockId( $partialBlocks );
423  }
424 
425  $lb->execute();
426  }
427 
428 }
static getTitleValueFor( $name, $subpage=false, $fragment='')
Get a localised TitleValue object for a specified special page name.
Definition: SpecialPage.php:97
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:73
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 TYPE_RANGE
Definition: Block.php:98
const NS_MAIN
Definition: Defines.php:64
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
const TYPE_IP
Definition: Block.php:97
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()
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1619
getDatabase()
Get the Database object in use.
Definition: IndexPager.php:217
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:1126
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:935
$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:82
__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:896
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.
const TYPE_USER
Definition: Block.php:96
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:84
const NS_USER_TALK
Definition: Defines.php:67
isFieldSortable( $name)
getRestrictionListHTML(stdClass $row)
Get Restriction List HTML.
getTotalAutoblocks()
Get total number of autoblocks at any given time.