HTMLForm: Separate VForm code to a subclass
[lhc/web/wiklou.git] / includes / specials / SpecialWhatlinkshere.php
1 <?php
2 /**
3 * Implements Special:Whatlinkshere
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @todo Use some variant of Pager or something; the pagination here is lousy.
22 */
23
24 /**
25 * Implements Special:Whatlinkshere
26 *
27 * @ingroup SpecialPage
28 */
29 class SpecialWhatLinksHere extends IncludableSpecialPage {
30 /** @var FormOptions */
31 protected $opts;
32
33 protected $selfTitle;
34
35 /** @var Title */
36 protected $target;
37
38 protected $limits = array( 20, 50, 100, 250, 500 );
39
40 public function __construct() {
41 parent::__construct( 'Whatlinkshere' );
42 }
43
44 function execute( $par ) {
45 $out = $this->getOutput();
46
47 $this->setHeaders();
48 $this->outputHeader();
49
50 $opts = new FormOptions();
51
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 );
62
63 $opts->fetchValuesFromRequest( $this->getRequest() );
64 $opts->validateIntBounds( 'limit', 0, 5000 );
65
66 // Give precedence to subpage syntax
67 if ( $par !== null ) {
68 $opts->setValue( 'target', $par );
69 }
70
71 // Bind to member variable
72 $this->opts = $opts;
73
74 $this->target = Title::newFromURL( $opts->getValue( 'target' ) );
75 if ( !$this->target ) {
76 $out->addHTML( $this->whatlinkshereForm() );
77
78 return;
79 }
80
81 $this->getSkin()->setRelevantTitle( $this->target );
82
83 $this->selfTitle = $this->getPageTitle( $this->target->getPrefixedDBkey() );
84
85 $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target->getPrefixedText() ) );
86 $out->addBacklinkSubtitle( $this->target );
87 $this->showIndirectLinks(
88 0,
89 $this->target,
90 $opts->getValue( 'limit' ),
91 $opts->getValue( 'from' ),
92 $opts->getValue( 'back' )
93 );
94 }
95
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)
102 */
103 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
104 $out = $this->getOutput();
105 $dbr = wfGetDB( DB_SLAVE );
106
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' );
111
112 $fetchlinks = ( !$hidelinks || !$hideredirs );
113
114 // Build query conds in concert for all three tables...
115 $conds['pagelinks'] = array(
116 'pl_namespace' => $target->getNamespace(),
117 'pl_title' => $target->getDBkey(),
118 );
119 $conds['templatelinks'] = array(
120 'tl_namespace' => $target->getNamespace(),
121 'tl_title' => $target->getDBkey(),
122 );
123 $conds['imagelinks'] = array(
124 'il_to' => $target->getDBkey(),
125 );
126
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";
140 }
141 }
142
143 if ( $from ) {
144 $conds['templatelinks'][] = "tl_from >= $from";
145 $conds['pagelinks'][] = "pl_from >= $from";
146 $conds['imagelinks'][] = "il_from >= $from";
147 }
148
149 if ( $hideredirs ) {
150 $conds['pagelinks']['rd_from'] = null;
151 } elseif ( $hidelinks ) {
152 $conds['pagelinks'][] = 'rd_from is NOT NULL';
153 }
154
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'
162 );
163 if ( $useLinkNamespaceDBFields ) { // migration check
164 $on['rd_namespace'] = $target->getNamespace();
165 }
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 )
176 )
177 );
178 return $dbr->select(
179 array( 'page', 'temp_backlink_range' => "($subQuery)" ),
180 array( 'page_id', 'page_namespace', 'page_title', 'rd_from' ),
181 array(),
182 __CLASS__ . '::showIndirectLinks',
183 array( 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ),
184 array( 'page' => array( 'INNER JOIN', "$fromCol = page_id" ) )
185 );
186 };
187
188 if ( $fetchlinks ) {
189 $plRes = $queryFunc( $dbr, 'pagelinks', 'pl_from' );
190 }
191
192 if ( !$hidetrans ) {
193 $tlRes = $queryFunc( $dbr, 'templatelinks', 'tl_from' );
194 }
195
196 if ( !$hideimages ) {
197 $ilRes = $queryFunc( $dbr, 'imagelinks', 'il_from' );
198 }
199
200 if ( ( !$fetchlinks || !$plRes->numRows() )
201 && ( $hidetrans || !$tlRes->numRows() )
202 && ( $hideimages || !$ilRes->numRows() )
203 ) {
204 if ( 0 == $level ) {
205 if ( !$this->including() ) {
206 $out->addHTML( $this->whatlinkshereForm() );
207
208 // Show filters only if there are links
209 if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) {
210 $out->addHTML( $this->getFilterPanel() );
211 }
212 $errMsg = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
213 $out->addWikiMsg( $errMsg, $this->target->getPrefixedText() );
214 $out->setStatusCode( 404 );
215 }
216 }
217
218 return;
219 }
220
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;
229 }
230 }
231 if ( !$hidetrans ) {
232 foreach ( $tlRes as $row ) {
233 $row->is_template = 1;
234 $row->is_image = 0;
235 $rows[$row->page_id] = $row;
236 }
237 }
238 if ( !$hideimages ) {
239 foreach ( $ilRes as $row ) {
240 $row->is_template = 0;
241 $row->is_image = 1;
242 $rows[$row->page_id] = $row;
243 }
244 }
245
246 // Sort by key and then change the keys to 0-based indices
247 ksort( $rows );
248 $rows = array_values( $rows );
249
250 $numRows = count( $rows );
251
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;
262 }
263 $prevId = $from;
264
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() );
270
271 $prevnext = $this->getPrevNext( $prevId, $nextId );
272 $out->addHTML( $prevnext );
273 }
274 }
275 $out->addHTML( $this->listStart( $level ) );
276 foreach ( $rows as $row ) {
277 $nt = Title::makeTitle( $row->page_namespace, $row->page_title );
278
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 ) );
285 }
286 }
287
288 $out->addHTML( $this->listEnd() );
289
290 if ( $level == 0 ) {
291 if ( !$this->including() ) {
292 $out->addHTML( $prevnext );
293 }
294 }
295 }
296
297 protected function listStart( $level ) {
298 return Xml::openElement( 'ul', ( $level ? array() : array( 'id' => 'mw-whatlinkshere-list' ) ) );
299 }
300
301 protected function listItem( $row, $nt, $target, $notClose = false ) {
302 $dirmark = $this->getLanguage()->getDirMark();
303
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();
312 }
313 }
314
315 if ( $row->rd_from ) {
316 $query = array( 'redirect' => 'no' );
317 } else {
318 $query = array();
319 }
320
321 $link = Linker::linkKnown(
322 $nt,
323 null,
324 array(),
325 $query
326 );
327
328 // Display properties (redirect or template)
329 $propsText = '';
330 $props = array();
331 if ( $row->rd_from ) {
332 $props[] = $msgcache['isredirect'];
333 }
334 if ( $row->is_template ) {
335 $props[] = $msgcache['istemplate'];
336 }
337 if ( $row->is_image ) {
338 $props[] = $msgcache['isimage'];
339 }
340
341 Hooks::run( 'WhatLinksHereProps', array( $row, $nt, $target, &$props ) );
342
343 if ( count( $props ) ) {
344 $propsText = $this->msg( 'parentheses' )
345 ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
346 }
347
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'
353 );
354
355 return $notClose ?
356 Xml::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
357 Xml::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
358 }
359
360 protected function listEnd() {
361 return Xml::closeElement( 'ul' );
362 }
363
364 protected function wlhLink( Title $target, $text ) {
365 static $title = null;
366 if ( $title === null ) {
367 $title = $this->getPageTitle();
368 }
369
370 return Linker::linkKnown(
371 $title,
372 $text,
373 array(),
374 array( 'target' => $target->getPrefixedText() )
375 );
376 }
377
378 function makeSelfLink( $text, $query ) {
379 return Linker::linkKnown(
380 $this->selfTitle,
381 $text,
382 array(),
383 $query
384 );
385 }
386
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();
391
392 $changed = $this->opts->getChangedValues();
393 unset( $changed['target'] ); // Already in the request title
394
395 if ( 0 != $prevId ) {
396 $overrides = array( 'from' => $this->opts->getValue( 'back' ) );
397 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
398 }
399 if ( 0 != $nextId ) {
400 $overrides = array( 'from' => $nextId, 'back' => $prevId );
401 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
402 }
403
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 ) );
410 }
411
412 $nums = $lang->pipeList( $limitLinks );
413
414 return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
415 }
416
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' ) );
422
423 $target = $this->target ? $this->target->getPrefixedText() : '';
424 $namespace = $this->opts->consumeValue( 'namespace' );
425 $nsinvert = $this->opts->consumeValue( 'invert' );
426
427 # Build up the form
428 $f = Xml::openElement( 'form', array( 'action' => wfScript() ) );
429
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 );
434 }
435
436 $f .= Xml::fieldset( $this->msg( 'whatlinkshere' )->text() );
437
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' ) );
441
442 $f .= ' ';
443
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',
454 )
455 );
456
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() )
464 );
465
466 $f .= ' ';
467
468 # Submit
469 $f .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
470
471 # Close
472 $f .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ) . "\n";
473
474 return $f;
475 }
476
477 /**
478 * Create filter panel
479 *
480 * @return string HTML fieldset and filter panel with the show/hide links
481 */
482 function getFilterPanel() {
483 $show = $this->msg( 'show' )->escaped();
484 $hide = $this->msg( 'hide' )->escaped();
485
486 $changed = $this->opts->getChangedValues();
487 unset( $changed['target'] ); // Already in the request title
488
489 $links = array();
490 $types = array( 'hidetrans', 'hidelinks', 'hideredirs' );
491 if ( $this->target->getNamespace() == NS_FILE ) {
492 $types[] = 'hideimages';
493 }
494
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();
504 }
505
506 return Xml::fieldset(
507 $this->msg( 'whatlinkshere-filters' )->text(),
508 $this->getLanguage()->pipeList( $links )
509 );
510 }
511
512 /**
513 * Return an array of subpages beginning with $search that this special page will accept.
514 *
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
519 */
520 public function prefixSearchSubpages( $search, $limit, $offset ) {
521 if ( $search === '' ) {
522 return array();
523 }
524 // Autocomplete subpage the same as a normal search
525 $prefixSearcher = new StringPrefixSearch;
526 $result = $prefixSearcher->search( $search, $limit, array(), $offset );
527 return $result;
528 }
529
530 protected function getGroupName() {
531 return 'pagetools';
532 }
533 }