Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / specials / SpecialWhatlinkshere.php
blob28be790911519aa84ed65309aa469db3b67e6558
1 <?php
2 /**
3 * Implements Special:Whatlinkshere
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @todo Use some variant of Pager or something; the pagination here is lousy.
24 /**
25 * Implements Special:Whatlinkshere
27 * @ingroup SpecialPage
29 class SpecialWhatLinksHere extends IncludableSpecialPage {
30 /** @var FormOptions */
31 protected $opts;
33 protected $selfTitle;
35 /** @var Title */
36 protected $target;
38 protected $limits = array( 20, 50, 100, 250, 500 );
40 public function __construct() {
41 parent::__construct( 'Whatlinkshere' );
44 function execute( $par ) {
45 $out = $this->getOutput();
47 $this->setHeaders();
48 $this->outputHeader();
50 $opts = new FormOptions();
52 $opts->add( 'target', '' );
53 $opts->add( 'namespace', '', FormOptions::INTNULL );
54 $opts->add( 'limit', $this->getConfig()->get( 'QueryPageDefaultLimit' ) );
55 $opts->add( 'from', 0 );
56 $opts->add( 'back', 0 );
57 $opts->add( 'hideredirs', false );
58 $opts->add( 'hidetrans', false );
59 $opts->add( 'hidelinks', false );
60 $opts->add( 'hideimages', false );
61 $opts->add( 'invert', false );
63 $opts->fetchValuesFromRequest( $this->getRequest() );
64 $opts->validateIntBounds( 'limit', 0, 5000 );
66 // Give precedence to subpage syntax
67 if ( $par !== null ) {
68 $opts->setValue( 'target', $par );
71 // Bind to member variable
72 $this->opts = $opts;
74 $this->target = Title::newFromURL( $opts->getValue( 'target' ) );
75 if ( !$this->target ) {
76 $out->addHTML( $this->whatlinkshereForm() );
78 return;
81 $this->getSkin()->setRelevantTitle( $this->target );
83 $this->selfTitle = $this->getPageTitle( $this->target->getPrefixedDBkey() );
85 $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target->getPrefixedText() ) );
86 $out->addBacklinkSubtitle( $this->target );
87 $this->showIndirectLinks(
89 $this->target,
90 $opts->getValue( 'limit' ),
91 $opts->getValue( 'from' ),
92 $opts->getValue( 'back' )
96 /**
97 * @param int $level Recursion level
98 * @param Title $target Target title
99 * @param int $limit Number of entries to display
100 * @param int $from Display from this article ID (default: 0)
101 * @param int $back Display from this article ID at backwards scrolling (default: 0)
103 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
104 $out = $this->getOutput();
105 $dbr = wfGetDB( DB_SLAVE );
107 $hidelinks = $this->opts->getValue( 'hidelinks' );
108 $hideredirs = $this->opts->getValue( 'hideredirs' );
109 $hidetrans = $this->opts->getValue( 'hidetrans' );
110 $hideimages = $target->getNamespace() != NS_FILE || $this->opts->getValue( 'hideimages' );
112 $fetchlinks = ( !$hidelinks || !$hideredirs );
114 // Build query conds in concert for all three tables...
115 $conds['pagelinks'] = array(
116 'pl_namespace' => $target->getNamespace(),
117 'pl_title' => $target->getDBkey(),
119 $conds['templatelinks'] = array(
120 'tl_namespace' => $target->getNamespace(),
121 'tl_title' => $target->getDBkey(),
123 $conds['imagelinks'] = array(
124 'il_to' => $target->getDBkey(),
127 $useLinkNamespaceDBFields = $this->getConfig()->get( 'UseLinkNamespaceDBFields' );
128 $namespace = $this->opts->getValue( 'namespace' );
129 $invert = $this->opts->getValue( 'invert' );
130 $nsComparison = ( $invert ? '!= ' : '= ' ) . $dbr->addQuotes( $namespace );
131 if ( is_int( $namespace ) ) {
132 if ( $useLinkNamespaceDBFields ) {
133 $conds['pagelinks'][] = "pl_from_namespace $nsComparison";
134 $conds['templatelinks'][] = "tl_from_namespace $nsComparison";
135 $conds['imagelinks'][] = "il_from_namespace $nsComparison";
136 } else {
137 $conds['pagelinks'][] = "page_namespace $nsComparison";
138 $conds['templatelinks'][] = "page_namespace $nsComparison";
139 $conds['imagelinks'][] = "page_namespace $nsComparison";
143 if ( $from ) {
144 $conds['templatelinks'][] = "tl_from >= $from";
145 $conds['pagelinks'][] = "pl_from >= $from";
146 $conds['imagelinks'][] = "il_from >= $from";
149 if ( $hideredirs ) {
150 $conds['pagelinks']['rd_from'] = null;
151 } elseif ( $hidelinks ) {
152 $conds['pagelinks'][] = 'rd_from is NOT NULL';
155 $queryFunc = function ( $dbr, $table, $fromCol ) use ( $conds, $target, $limit, $useLinkNamespaceDBFields ) {
156 // Read an extra row as an at-end check
157 $queryLimit = $limit + 1;
158 $on = array(
159 "rd_from = $fromCol",
160 'rd_title' => $target->getDBkey(),
161 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'
163 if ( $useLinkNamespaceDBFields ) { // migration check
164 $on['rd_namespace'] = $target->getNamespace();
166 // Inner LIMIT is 2X in case of stale backlinks with wrong namespaces
167 $subQuery = $dbr->selectSqlText(
168 array( $table, 'page', 'redirect' ),
169 array( $fromCol, 'rd_from' ),
170 $conds[$table],
171 __CLASS__ . '::showIndirectLinks',
172 array( 'ORDER BY' => $fromCol, 'LIMIT' => 2 * $queryLimit ),
173 array(
174 'page' => array( 'INNER JOIN', "$fromCol = page_id" ),
175 'redirect' => array( 'LEFT JOIN', $on )
178 return $dbr->select(
179 array( 'page', 'temp_backlink_range' => "($subQuery)" ),
180 array( 'page_id', 'page_namespace', 'page_title', 'rd_from', 'page_is_redirect' ),
181 array(),
182 __CLASS__ . '::showIndirectLinks',
183 array( 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ),
184 array( 'page' => array( 'INNER JOIN', "$fromCol = page_id" ) )
188 if ( $fetchlinks ) {
189 $plRes = $queryFunc( $dbr, 'pagelinks', 'pl_from' );
192 if ( !$hidetrans ) {
193 $tlRes = $queryFunc( $dbr, 'templatelinks', 'tl_from' );
196 if ( !$hideimages ) {
197 $ilRes = $queryFunc( $dbr, 'imagelinks', 'il_from' );
200 if ( ( !$fetchlinks || !$plRes->numRows() )
201 && ( $hidetrans || !$tlRes->numRows() )
202 && ( $hideimages || !$ilRes->numRows() )
204 if ( 0 == $level ) {
205 if ( !$this->including() ) {
206 $out->addHTML( $this->whatlinkshereForm() );
208 // Show filters only if there are links
209 if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) {
210 $out->addHTML( $this->getFilterPanel() );
212 $errMsg = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
213 $out->addWikiMsg( $errMsg, $this->target->getPrefixedText() );
214 $out->setStatusCode( 404 );
218 return;
221 // Read the rows into an array and remove duplicates
222 // templatelinks comes second so that the templatelinks row overwrites the
223 // pagelinks row, so we get (inclusion) rather than nothing
224 if ( $fetchlinks ) {
225 foreach ( $plRes as $row ) {
226 $row->is_template = 0;
227 $row->is_image = 0;
228 $rows[$row->page_id] = $row;
231 if ( !$hidetrans ) {
232 foreach ( $tlRes as $row ) {
233 $row->is_template = 1;
234 $row->is_image = 0;
235 $rows[$row->page_id] = $row;
238 if ( !$hideimages ) {
239 foreach ( $ilRes as $row ) {
240 $row->is_template = 0;
241 $row->is_image = 1;
242 $rows[$row->page_id] = $row;
246 // Sort by key and then change the keys to 0-based indices
247 ksort( $rows );
248 $rows = array_values( $rows );
250 $numRows = count( $rows );
252 // Work out the start and end IDs, for prev/next links
253 if ( $numRows > $limit ) {
254 // More rows available after these ones
255 // Get the ID from the last row in the result set
256 $nextId = $rows[$limit]->page_id;
257 // Remove undisplayed rows
258 $rows = array_slice( $rows, 0, $limit );
259 } else {
260 // No more rows after
261 $nextId = false;
263 $prevId = $from;
265 if ( $level == 0 ) {
266 if ( !$this->including() ) {
267 $out->addHTML( $this->whatlinkshereForm() );
268 $out->addHTML( $this->getFilterPanel() );
269 $out->addWikiMsg( 'linkshere', $this->target->getPrefixedText() );
271 $prevnext = $this->getPrevNext( $prevId, $nextId );
272 $out->addHTML( $prevnext );
275 $out->addHTML( $this->listStart( $level ) );
276 foreach ( $rows as $row ) {
277 $nt = Title::makeTitle( $row->page_namespace, $row->page_title );
279 if ( $row->rd_from && $level < 2 ) {
280 $out->addHTML( $this->listItem( $row, $nt, $target, true ) );
281 $this->showIndirectLinks( $level + 1, $nt, $this->getConfig()->get( 'MaxRedirectLinksRetrieved' ) );
282 $out->addHTML( Xml::closeElement( 'li' ) );
283 } else {
284 $out->addHTML( $this->listItem( $row, $nt, $target ) );
288 $out->addHTML( $this->listEnd() );
290 if ( $level == 0 ) {
291 if ( !$this->including() ) {
292 $out->addHTML( $prevnext );
297 protected function listStart( $level ) {
298 return Xml::openElement( 'ul', ( $level ? array() : array( 'id' => 'mw-whatlinkshere-list' ) ) );
301 protected function listItem( $row, $nt, $target, $notClose = false ) {
302 $dirmark = $this->getLanguage()->getDirMark();
304 # local message cache
305 static $msgcache = null;
306 if ( $msgcache === null ) {
307 static $msgs = array( 'isredirect', 'istemplate', 'semicolon-separator',
308 'whatlinkshere-links', 'isimage' );
309 $msgcache = array();
310 foreach ( $msgs as $msg ) {
311 $msgcache[$msg] = $this->msg( $msg )->escaped();
315 if ( $row->rd_from ) {
316 $query = array( 'redirect' => 'no' );
317 } else {
318 $query = array();
321 $link = Linker::linkKnown(
322 $nt,
323 null,
324 $row->page_is_redirect ? array( 'class' => 'mw-redirect' ) : array(),
325 $query
328 // Display properties (redirect or template)
329 $propsText = '';
330 $props = array();
331 if ( $row->rd_from ) {
332 $props[] = $msgcache['isredirect'];
334 if ( $row->is_template ) {
335 $props[] = $msgcache['istemplate'];
337 if ( $row->is_image ) {
338 $props[] = $msgcache['isimage'];
341 Hooks::run( 'WhatLinksHereProps', array( $row, $nt, $target, &$props ) );
343 if ( count( $props ) ) {
344 $propsText = $this->msg( 'parentheses' )
345 ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
348 # Space for utilities links, with a what-links-here link provided
349 $wlhLink = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'] );
350 $wlh = Xml::wrapClass(
351 $this->msg( 'parentheses' )->rawParams( $wlhLink )->escaped(),
352 'mw-whatlinkshere-tools'
355 return $notClose ?
356 Xml::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
357 Xml::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
360 protected function listEnd() {
361 return Xml::closeElement( 'ul' );
364 protected function wlhLink( Title $target, $text ) {
365 static $title = null;
366 if ( $title === null ) {
367 $title = $this->getPageTitle();
370 return Linker::linkKnown(
371 $title,
372 $text,
373 array(),
374 array( 'target' => $target->getPrefixedText() )
378 function makeSelfLink( $text, $query ) {
379 return Linker::linkKnown(
380 $this->selfTitle,
381 $text,
382 array(),
383 $query
387 function getPrevNext( $prevId, $nextId ) {
388 $currentLimit = $this->opts->getValue( 'limit' );
389 $prev = $this->msg( 'whatlinkshere-prev' )->numParams( $currentLimit )->escaped();
390 $next = $this->msg( 'whatlinkshere-next' )->numParams( $currentLimit )->escaped();
392 $changed = $this->opts->getChangedValues();
393 unset( $changed['target'] ); // Already in the request title
395 if ( 0 != $prevId ) {
396 $overrides = array( 'from' => $this->opts->getValue( 'back' ) );
397 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
399 if ( 0 != $nextId ) {
400 $overrides = array( 'from' => $nextId, 'back' => $prevId );
401 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
404 $limitLinks = array();
405 $lang = $this->getLanguage();
406 foreach ( $this->limits as $limit ) {
407 $prettyLimit = htmlspecialchars( $lang->formatNum( $limit ) );
408 $overrides = array( 'limit' => $limit );
409 $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
412 $nums = $lang->pipeList( $limitLinks );
414 return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
417 function whatlinkshereForm() {
418 // We get nicer value from the title object
419 $this->opts->consumeValue( 'target' );
420 // Reset these for new requests
421 $this->opts->consumeValues( array( 'back', 'from' ) );
423 $target = $this->target ? $this->target->getPrefixedText() : '';
424 $namespace = $this->opts->consumeValue( 'namespace' );
425 $nsinvert = $this->opts->consumeValue( 'invert' );
427 # Build up the form
428 $f = Xml::openElement( 'form', array( 'action' => wfScript() ) );
430 # Values that should not be forgotten
431 $f .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
432 foreach ( $this->opts->getUnconsumedValues() as $name => $value ) {
433 $f .= Html::hidden( $name, $value );
436 $f .= Xml::fieldset( $this->msg( 'whatlinkshere' )->text() );
438 # Target input (.mw-searchInput enables suggestions)
439 $f .= Xml::inputLabel( $this->msg( 'whatlinkshere-page' )->text(), 'target',
440 'mw-whatlinkshere-target', 40, $target, array( 'class' => 'mw-searchInput' ) );
442 $f .= ' ';
444 # Namespace selector
445 $f .= Html::namespaceSelector(
446 array(
447 'selected' => $namespace,
448 'all' => '',
449 'label' => $this->msg( 'namespace' )->text()
450 ), array(
451 'name' => 'namespace',
452 'id' => 'namespace',
453 'class' => 'namespaceselector',
457 $f .= '&#160;' .
458 Xml::checkLabel(
459 $this->msg( 'invert' )->text(),
460 'invert',
461 'nsinvert',
462 $nsinvert,
463 array( 'title' => $this->msg( 'tooltip-whatlinkshere-invert' )->text() )
466 $f .= ' ';
468 # Submit
469 $f .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
471 # Close
472 $f .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ) . "\n";
474 return $f;
478 * Create filter panel
480 * @return string HTML fieldset and filter panel with the show/hide links
482 function getFilterPanel() {
483 $show = $this->msg( 'show' )->escaped();
484 $hide = $this->msg( 'hide' )->escaped();
486 $changed = $this->opts->getChangedValues();
487 unset( $changed['target'] ); // Already in the request title
489 $links = array();
490 $types = array( 'hidetrans', 'hidelinks', 'hideredirs' );
491 if ( $this->target->getNamespace() == NS_FILE ) {
492 $types[] = 'hideimages';
495 // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans',
496 // 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
497 // To be sure they will be found by grep
498 foreach ( $types as $type ) {
499 $chosen = $this->opts->getValue( $type );
500 $msg = $chosen ? $show : $hide;
501 $overrides = array( $type => !$chosen );
502 $links[] = $this->msg( "whatlinkshere-{$type}" )->rawParams(
503 $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) )->escaped();
506 return Xml::fieldset(
507 $this->msg( 'whatlinkshere-filters' )->text(),
508 $this->getLanguage()->pipeList( $links )
513 * Return an array of subpages beginning with $search that this special page will accept.
515 * @param string $search Prefix to search for
516 * @param int $limit Maximum number of results to return (usually 10)
517 * @param int $offset Number of results to skip (usually 0)
518 * @return string[] Matching subpages
520 public function prefixSearchSubpages( $search, $limit, $offset ) {
521 if ( $search === '' ) {
522 return array();
524 // Autocomplete subpage the same as a normal search
525 $prefixSearcher = new StringPrefixSearch;
526 $result = $prefixSearcher->search( $search, $limit, array(), $offset );
527 return $result;
530 protected function getGroupName() {
531 return 'pagetools';