MediaWiki REL1_33
BlockListPager.php
Go to the documentation of this file.
1<?php
30
32
33 protected $conds;
34
40 protected $restrictions = [];
41
46 public function __construct( $page, $conds ) {
47 $this->conds = $conds;
48 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
49 parent::__construct( $page->getContext() );
50 }
51
52 function getFieldNames() {
53 static $headers = null;
54
55 if ( $headers === null ) {
56 $headers = [
57 'ipb_timestamp' => 'blocklist-timestamp',
58 'ipb_target' => 'blocklist-target',
59 'ipb_expiry' => 'blocklist-expiry',
60 'ipb_by' => 'blocklist-by',
61 'ipb_params' => 'blocklist-params',
62 'ipb_reason' => 'blocklist-reason',
63 ];
64 foreach ( $headers as $key => $val ) {
65 $headers[$key] = $this->msg( $val )->text();
66 }
67 }
68
69 return $headers;
70 }
71
72 function formatValue( $name, $value ) {
73 static $msg = null;
74 if ( $msg === null ) {
75 $keys = [
76 'anononlyblock',
77 'createaccountblock',
78 'noautoblockblock',
79 'emailblock',
80 'blocklist-nousertalk',
81 'unblocklink',
82 'change-blocklink',
83 'blocklist-editing',
84 'blocklist-editing-sitewide',
85 ];
86
87 foreach ( $keys as $key ) {
88 $msg[$key] = $this->msg( $key )->text();
89 }
90 }
91
93 $row = $this->mCurrentRow;
94
95 $language = $this->getLanguage();
96
97 $formatted = '';
98
99 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
100
101 switch ( $name ) {
102 case 'ipb_timestamp':
103 $formatted = htmlspecialchars( $language->userTimeAndDate( $value, $this->getUser() ) );
104 break;
105
106 case 'ipb_target':
107 if ( $row->ipb_auto ) {
108 $formatted = $this->msg( 'autoblockid', $row->ipb_id )->parse();
109 } else {
110 list( $target, $type ) = Block::parseTarget( $row->ipb_address );
111 switch ( $type ) {
112 case Block::TYPE_USER:
113 case Block::TYPE_IP:
114 $formatted = Linker::userLink( $target->getId(), $target );
115 $formatted .= Linker::userToolLinks(
116 $target->getId(),
117 $target,
118 false,
120 );
121 break;
123 $formatted = htmlspecialchars( $target );
124 }
125 }
126 break;
127
128 case 'ipb_expiry':
129 $formatted = htmlspecialchars( $language->formatExpiry(
130 $value,
131 /* User preference timezone */true
132 ) );
133 if ( $this->getUser()->isAllowed( 'block' ) ) {
134 if ( $row->ipb_auto ) {
135 $links[] = $linkRenderer->makeKnownLink(
136 SpecialPage::getTitleFor( 'Unblock' ),
137 $msg['unblocklink'],
138 [],
139 [ 'wpTarget' => "#{$row->ipb_id}" ]
140 );
141 } else {
142 $links[] = $linkRenderer->makeKnownLink(
143 SpecialPage::getTitleFor( 'Unblock', $row->ipb_address ),
144 $msg['unblocklink']
145 );
146 $links[] = $linkRenderer->makeKnownLink(
147 SpecialPage::getTitleFor( 'Block', $row->ipb_address ),
148 $msg['change-blocklink']
149 );
150 }
151 $formatted .= ' ' . Html::rawElement(
152 'span',
153 [ 'class' => 'mw-blocklist-actions' ],
154 $this->msg( 'parentheses' )->rawParams(
155 $language->pipeList( $links ) )->escaped()
156 );
157 }
158 if ( $value !== 'infinity' ) {
159 $timestamp = new MWTimestamp( $value );
160 $formatted .= '<br />' . $this->msg(
161 'ipb-blocklist-duration-left',
162 $language->formatDuration(
163 $timestamp->getTimestamp() - MWTimestamp::time(),
164 // reasonable output
165 [
166 'minutes',
167 'hours',
168 'days',
169 'years',
170 ]
171 )
172 )->escaped();
173 }
174 break;
175
176 case 'ipb_by':
177 if ( isset( $row->by_user_name ) ) {
178 $formatted = Linker::userLink( $value, $row->by_user_name );
179 $formatted .= Linker::userToolLinks( $value, $row->by_user_name );
180 } else {
181 $formatted = htmlspecialchars( $row->ipb_by_text ); // foreign user?
182 }
183 break;
184
185 case 'ipb_reason':
186 $value = CommentStore::getStore()->getComment( 'ipb_reason', $row )->text;
187 $formatted = Linker::formatComment( $value );
188 break;
189
190 case 'ipb_params':
191 $properties = [];
192
193 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) && $row->ipb_sitewide ) {
194 $properties[] = htmlspecialchars( $msg['blocklist-editing-sitewide'] );
195 }
196
197 if ( !$row->ipb_sitewide && $this->restrictions ) {
198 $list = $this->getRestrictionListHTML( $row );
199 if ( $list ) {
200 $properties[] = htmlspecialchars( $msg['blocklist-editing'] ) . $list;
201 }
202 }
203
204 if ( $row->ipb_anon_only ) {
205 $properties[] = htmlspecialchars( $msg['anononlyblock'] );
206 }
207 if ( $row->ipb_create_account ) {
208 $properties[] = htmlspecialchars( $msg['createaccountblock'] );
209 }
210 if ( $row->ipb_user && !$row->ipb_enable_autoblock ) {
211 $properties[] = htmlspecialchars( $msg['noautoblockblock'] );
212 }
213
214 if ( $row->ipb_block_email ) {
215 $properties[] = htmlspecialchars( $msg['emailblock'] );
216 }
217
218 if ( !$row->ipb_allow_usertalk ) {
219 $properties[] = htmlspecialchars( $msg['blocklist-nousertalk'] );
220 }
221
222 $formatted = Html::rawElement(
223 'ul',
224 [],
225 implode( '', array_map( function ( $prop ) {
226 return Html::rawElement(
227 'li',
228 [],
229 $prop
230 );
231 }, $properties ) )
232 );
233 break;
234
235 default:
236 $formatted = "Unable to format $name";
237 break;
238 }
239
240 return $formatted;
241 }
242
250 private function getRestrictionListHTML( stdClass $row ) {
251 $items = [];
252
253 foreach ( $this->restrictions as $restriction ) {
254 if ( $restriction->getBlockId() !== (int)$row->ipb_id ) {
255 continue;
256 }
257
258 switch ( $restriction->getType() ) {
259 case PageRestriction::TYPE:
260 if ( $restriction->getTitle() ) {
261 $items[$restriction->getType()][] = Html::rawElement(
262 'li',
263 [],
264 Linker::link( $restriction->getTitle() )
265 );
266 }
267 break;
268 case NamespaceRestriction::TYPE:
269 $text = $restriction->getValue() === NS_MAIN
270 ? $this->msg( 'blanknamespace' )
271 : $this->getLanguage()->getFormattedNsText(
272 $restriction->getValue()
273 );
274 $items[$restriction->getType()][] = Html::rawElement(
275 'li',
276 [],
278 SpecialPage::getTitleValueFor( 'Allpages' ),
279 $text,
280 [],
281 [
282 'namespace' => $restriction->getValue()
283 ]
284 )
285 );
286 break;
287 }
288 }
289
290 if ( empty( $items ) ) {
291 return '';
292 }
293
294 $sets = [];
295 foreach ( $items as $key => $value ) {
296 $sets[] = Html::rawElement(
297 'li',
298 [],
299 $this->msg( 'blocklist-editing-' . $key ) . Html::rawElement(
300 'ul',
301 [],
302 implode( '', $value )
303 )
304 );
305 }
306
307 return Html::rawElement(
308 'ul',
309 [],
310 implode( '', $sets )
311 );
312 }
313
314 function getQueryInfo() {
315 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
316 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
317
318 $info = [
319 'tables' => array_merge(
320 [ 'ipblocks' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
321 ),
322 'fields' => [
323 'ipb_id',
324 'ipb_address',
325 'ipb_user',
326 'by_user_name' => 'user_name',
327 'ipb_timestamp',
328 'ipb_auto',
329 'ipb_anon_only',
330 'ipb_create_account',
331 'ipb_enable_autoblock',
332 'ipb_expiry',
333 'ipb_range_start',
334 'ipb_range_end',
335 'ipb_deleted',
336 'ipb_block_email',
337 'ipb_allow_usertalk',
338 'ipb_sitewide',
339 ] + $commentQuery['fields'] + $actorQuery['fields'],
340 'conds' => $this->conds,
341 'join_conds' => [
342 'user' => [ 'LEFT JOIN', 'user_id = ' . $actorQuery['fields']['ipb_by'] ]
343 ] + $commentQuery['joins'] + $actorQuery['joins']
344 ];
345
346 # Filter out any expired blocks
347 $db = $this->getDatabase();
348 $info['conds'][] = 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() );
349
350 # Is the user allowed to see hidden blocks?
351 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
352 $info['conds']['ipb_deleted'] = 0;
353 }
354
355 return $info;
356 }
357
364 $dbr = $this->getDatabase();
365 $res = $dbr->selectField( 'ipblocks',
366 [ 'COUNT(*) AS totalautoblocks' ],
367 [
368 'ipb_auto' => '1',
369 'ipb_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() ),
370 ]
371 );
372 if ( $res ) {
373 return $res;
374 }
375 return 0; // We found nothing
376 }
377
378 protected function getTableClass() {
379 return parent::getTableClass() . ' mw-blocklist';
380 }
381
382 function getIndexField() {
383 return 'ipb_timestamp';
384 }
385
386 function getDefaultSort() {
387 return 'ipb_timestamp';
388 }
389
390 function isFieldSortable( $name ) {
391 return false;
392 }
393
399 # Do a link batch query
400 $lb = new LinkBatch;
401 $lb->setCaller( __METHOD__ );
402
403 $partialBlocks = [];
404 foreach ( $result as $row ) {
405 $lb->add( NS_USER, $row->ipb_address );
406 $lb->add( NS_USER_TALK, $row->ipb_address );
407
408 if ( isset( $row->by_user_name ) ) {
409 $lb->add( NS_USER, $row->by_user_name );
410 $lb->add( NS_USER_TALK, $row->by_user_name );
411 }
412
413 if ( !$row->ipb_sitewide ) {
414 $partialBlocks[] = $row->ipb_id;
415 }
416 }
417
418 if ( $partialBlocks ) {
419 // Mutations to the $row object are not persisted. The restrictions will
420 // need be stored in a separate store.
421 $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
422 $this->restrictions = $blockRestrictionStore->loadByBlockId( $partialBlocks );
423 }
424
425 $lb->execute();
426 }
427
428}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getQueryInfo()
This function should be overridden to provide all parameters needed for the main paged query.
isFieldSortable( $name)
Return true if the named field should be sortable by the UI, false otherwise.
__construct( $page, $conds)
getTableClass()
TablePager relies on mw-datatable for styling, see T214208.
getFieldNames()
An array mapping database field names to a textual description of the field name, for use in the tabl...
preprocessResults( $result)
Do a LinkBatch query to minimise database load when generating all these links.
getRestrictionListHTML(stdClass $row)
Get Restriction List HTML.
formatValue( $name, $value)
Format a table cell.
Restriction[] $restrictions
Array of restrictions.
getTotalAutoblocks()
Get total number of autoblocks at any given time.
getDefaultSort()
The database field name used as a default sort order.
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition Block.php:1625
const TYPE_RANGE
Definition Block.php:98
const TYPE_USER
Definition Block.php:96
const TYPE_IP
Definition Block.php:97
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getDatabase()
Get the Database object in use.
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:34
setCaller( $caller)
Use ->setCaller( METHOD ) to indicate which code is using this class.
Definition LinkBatch.php:62
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition Linker.php:84
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition Linker.php:892
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition Linker.php:38
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:931
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:1122
Library for creating and parsing MW-style timestamps.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Table-based display with a user-selectable sort order.
stdClass $mCurrentRow
$res
Definition database.txt:21
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
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
const NS_USER
Definition Defines.php:75
const NS_MAIN
Definition Defines.php:73
const NS_USER_TALK
Definition Defines.php:76
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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:1991
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
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:2054
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:37
Result wrapper for grabbing data queried from an IDatabase object.