Special:WhatLinksHere Don't show edit links for non-direct-editing pages
[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 $this->addHelpLink( 'Help:What links here' );
50
51 $opts = new FormOptions();
52
53 $opts->add( 'target', '' );
54 $opts->add( 'namespace', '', FormOptions::INTNULL );
55 $opts->add( 'limit', $this->getConfig()->get( 'QueryPageDefaultLimit' ) );
56 $opts->add( 'from', 0 );
57 $opts->add( 'back', 0 );
58 $opts->add( 'hideredirs', false );
59 $opts->add( 'hidetrans', false );
60 $opts->add( 'hidelinks', false );
61 $opts->add( 'hideimages', false );
62 $opts->add( 'invert', false );
63
64 $opts->fetchValuesFromRequest( $this->getRequest() );
65 $opts->validateIntBounds( 'limit', 0, 5000 );
66
67 // Give precedence to subpage syntax
68 if ( $par !== null ) {
69 $opts->setValue( 'target', $par );
70 }
71
72 // Bind to member variable
73 $this->opts = $opts;
74
75 $this->target = Title::newFromURL( $opts->getValue( 'target' ) );
76 if ( !$this->target ) {
77 if ( !$this->including() ) {
78 $out->addHTML( $this->whatlinkshereForm() );
79 }
80
81 return;
82 }
83
84 $this->getSkin()->setRelevantTitle( $this->target );
85
86 $this->selfTitle = $this->getPageTitle( $this->target->getPrefixedDBkey() );
87
88 $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target->getPrefixedText() ) );
89 $out->addBacklinkSubtitle( $this->target );
90 $this->showIndirectLinks(
91 0,
92 $this->target,
93 $opts->getValue( 'limit' ),
94 $opts->getValue( 'from' ),
95 $opts->getValue( 'back' )
96 );
97 }
98
99 /**
100 * @param int $level Recursion level
101 * @param Title $target Target title
102 * @param int $limit Number of entries to display
103 * @param int $from Display from this article ID (default: 0)
104 * @param int $back Display from this article ID at backwards scrolling (default: 0)
105 */
106 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
107 $out = $this->getOutput();
108 $dbr = wfGetDB( DB_SLAVE );
109
110 $hidelinks = $this->opts->getValue( 'hidelinks' );
111 $hideredirs = $this->opts->getValue( 'hideredirs' );
112 $hidetrans = $this->opts->getValue( 'hidetrans' );
113 $hideimages = $target->getNamespace() != NS_FILE || $this->opts->getValue( 'hideimages' );
114
115 $fetchlinks = ( !$hidelinks || !$hideredirs );
116
117 // Build query conds in concert for all three tables...
118 $conds['pagelinks'] = array(
119 'pl_namespace' => $target->getNamespace(),
120 'pl_title' => $target->getDBkey(),
121 );
122 $conds['templatelinks'] = array(
123 'tl_namespace' => $target->getNamespace(),
124 'tl_title' => $target->getDBkey(),
125 );
126 $conds['imagelinks'] = array(
127 'il_to' => $target->getDBkey(),
128 );
129
130 $useLinkNamespaceDBFields = $this->getConfig()->get( 'UseLinkNamespaceDBFields' );
131 $namespace = $this->opts->getValue( 'namespace' );
132 $invert = $this->opts->getValue( 'invert' );
133 $nsComparison = ( $invert ? '!= ' : '= ' ) . $dbr->addQuotes( $namespace );
134 if ( is_int( $namespace ) ) {
135 if ( $useLinkNamespaceDBFields ) {
136 $conds['pagelinks'][] = "pl_from_namespace $nsComparison";
137 $conds['templatelinks'][] = "tl_from_namespace $nsComparison";
138 $conds['imagelinks'][] = "il_from_namespace $nsComparison";
139 } else {
140 $conds['pagelinks'][] = "page_namespace $nsComparison";
141 $conds['templatelinks'][] = "page_namespace $nsComparison";
142 $conds['imagelinks'][] = "page_namespace $nsComparison";
143 }
144 }
145
146 if ( $from ) {
147 $conds['templatelinks'][] = "tl_from >= $from";
148 $conds['pagelinks'][] = "pl_from >= $from";
149 $conds['imagelinks'][] = "il_from >= $from";
150 }
151
152 if ( $hideredirs ) {
153 $conds['pagelinks']['rd_from'] = null;
154 } elseif ( $hidelinks ) {
155 $conds['pagelinks'][] = 'rd_from is NOT NULL';
156 }
157
158 $queryFunc = function ( $dbr, $table, $fromCol ) use (
159 $conds, $target, $limit, $useLinkNamespaceDBFields
160 ) {
161 // Read an extra row as an at-end check
162 $queryLimit = $limit + 1;
163 $on = array(
164 "rd_from = $fromCol",
165 'rd_title' => $target->getDBkey(),
166 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'
167 );
168 if ( $useLinkNamespaceDBFields ) { // migration check
169 $on['rd_namespace'] = $target->getNamespace();
170 }
171 // Inner LIMIT is 2X in case of stale backlinks with wrong namespaces
172 $subQuery = $dbr->selectSqlText(
173 array( $table, 'page', 'redirect' ),
174 array( $fromCol, 'rd_from' ),
175 $conds[$table],
176 __CLASS__ . '::showIndirectLinks',
177 array( 'ORDER BY' => $fromCol, 'LIMIT' => 2 * $queryLimit ),
178 array(
179 'page' => array( 'INNER JOIN', "$fromCol = page_id" ),
180 'redirect' => array( 'LEFT JOIN', $on )
181 )
182 );
183 return $dbr->select(
184 array( 'page', 'temp_backlink_range' => "($subQuery)" ),
185 array( 'page_id', 'page_namespace', 'page_title', 'rd_from', 'page_is_redirect' ),
186 array(),
187 __CLASS__ . '::showIndirectLinks',
188 array( 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ),
189 array( 'page' => array( 'INNER JOIN', "$fromCol = page_id" ) )
190 );
191 };
192
193 if ( $fetchlinks ) {
194 $plRes = $queryFunc( $dbr, 'pagelinks', 'pl_from' );
195 }
196
197 if ( !$hidetrans ) {
198 $tlRes = $queryFunc( $dbr, 'templatelinks', 'tl_from' );
199 }
200
201 if ( !$hideimages ) {
202 $ilRes = $queryFunc( $dbr, 'imagelinks', 'il_from' );
203 }
204
205 if ( ( !$fetchlinks || !$plRes->numRows() )
206 && ( $hidetrans || !$tlRes->numRows() )
207 && ( $hideimages || !$ilRes->numRows() )
208 ) {
209 if ( 0 == $level ) {
210 if ( !$this->including() ) {
211 $out->addHTML( $this->whatlinkshereForm() );
212
213 // Show filters only if there are links
214 if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) {
215 $out->addHTML( $this->getFilterPanel() );
216 }
217 $errMsg = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
218 $out->addWikiMsg( $errMsg, $this->target->getPrefixedText() );
219 $out->setStatusCode( 404 );
220 }
221 }
222
223 return;
224 }
225
226 // Read the rows into an array and remove duplicates
227 // templatelinks comes second so that the templatelinks row overwrites the
228 // pagelinks row, so we get (inclusion) rather than nothing
229 if ( $fetchlinks ) {
230 foreach ( $plRes as $row ) {
231 $row->is_template = 0;
232 $row->is_image = 0;
233 $rows[$row->page_id] = $row;
234 }
235 }
236 if ( !$hidetrans ) {
237 foreach ( $tlRes as $row ) {
238 $row->is_template = 1;
239 $row->is_image = 0;
240 $rows[$row->page_id] = $row;
241 }
242 }
243 if ( !$hideimages ) {
244 foreach ( $ilRes as $row ) {
245 $row->is_template = 0;
246 $row->is_image = 1;
247 $rows[$row->page_id] = $row;
248 }
249 }
250
251 // Sort by key and then change the keys to 0-based indices
252 ksort( $rows );
253 $rows = array_values( $rows );
254
255 $numRows = count( $rows );
256
257 // Work out the start and end IDs, for prev/next links
258 if ( $numRows > $limit ) {
259 // More rows available after these ones
260 // Get the ID from the last row in the result set
261 $nextId = $rows[$limit]->page_id;
262 // Remove undisplayed rows
263 $rows = array_slice( $rows, 0, $limit );
264 } else {
265 // No more rows after
266 $nextId = false;
267 }
268 $prevId = $from;
269
270 // use LinkBatch to make sure, that all required data (associated with Titles)
271 // is loaded in one query
272 $lb = new LinkBatch();
273 foreach ( $rows as $row ) {
274 $lb->add( $row->page_namespace, $row->page_title );
275 }
276 $lb->execute();
277
278 if ( $level == 0 ) {
279 if ( !$this->including() ) {
280 $out->addHTML( $this->whatlinkshereForm() );
281 $out->addHTML( $this->getFilterPanel() );
282 $out->addWikiMsg( 'linkshere', $this->target->getPrefixedText() );
283
284 $prevnext = $this->getPrevNext( $prevId, $nextId );
285 $out->addHTML( $prevnext );
286 }
287 }
288 $out->addHTML( $this->listStart( $level ) );
289 foreach ( $rows as $row ) {
290 $nt = Title::makeTitle( $row->page_namespace, $row->page_title );
291
292 if ( $row->rd_from && $level < 2 ) {
293 $out->addHTML( $this->listItem( $row, $nt, $target, true ) );
294 $this->showIndirectLinks(
295 $level + 1,
296 $nt,
297 $this->getConfig()->get( 'MaxRedirectLinksRetrieved' )
298 );
299 $out->addHTML( Xml::closeElement( 'li' ) );
300 } else {
301 $out->addHTML( $this->listItem( $row, $nt, $target ) );
302 }
303 }
304
305 $out->addHTML( $this->listEnd() );
306
307 if ( $level == 0 ) {
308 if ( !$this->including() ) {
309 $out->addHTML( $prevnext );
310 }
311 }
312 }
313
314 protected function listStart( $level ) {
315 return Xml::openElement( 'ul', ( $level ? array() : array( 'id' => 'mw-whatlinkshere-list' ) ) );
316 }
317
318 protected function listItem( $row, $nt, $target, $notClose = false ) {
319 $dirmark = $this->getLanguage()->getDirMark();
320
321 # local message cache
322 static $msgcache = null;
323 if ( $msgcache === null ) {
324 static $msgs = array( 'isredirect', 'istemplate', 'semicolon-separator',
325 'whatlinkshere-links', 'isimage', 'edit' );
326 $msgcache = array();
327 foreach ( $msgs as $msg ) {
328 $msgcache[$msg] = $this->msg( $msg )->escaped();
329 }
330 }
331
332 if ( $row->rd_from ) {
333 $query = array( 'redirect' => 'no' );
334 } else {
335 $query = array();
336 }
337
338 $link = Linker::linkKnown(
339 $nt,
340 null,
341 $row->page_is_redirect ? array( 'class' => 'mw-redirect' ) : array(),
342 $query
343 );
344
345 // Display properties (redirect or template)
346 $propsText = '';
347 $props = array();
348 if ( $row->rd_from ) {
349 $props[] = $msgcache['isredirect'];
350 }
351 if ( $row->is_template ) {
352 $props[] = $msgcache['istemplate'];
353 }
354 if ( $row->is_image ) {
355 $props[] = $msgcache['isimage'];
356 }
357
358 Hooks::run( 'WhatLinksHereProps', array( $row, $nt, $target, &$props ) );
359
360 if ( count( $props ) ) {
361 $propsText = $this->msg( 'parentheses' )
362 ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
363 }
364
365 # Space for utilities links, with a what-links-here link provided
366 $wlhLink = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'], $msgcache['edit'] );
367 $wlh = Xml::wrapClass(
368 $this->msg( 'parentheses' )->rawParams( $wlhLink )->escaped(),
369 'mw-whatlinkshere-tools'
370 );
371
372 return $notClose ?
373 Xml::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
374 Xml::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
375 }
376
377 protected function listEnd() {
378 return Xml::closeElement( 'ul' );
379 }
380
381 protected function wlhLink( Title $target, $text, $editText ) {
382 static $title = null;
383 if ( $title === null ) {
384 $title = $this->getPageTitle();
385 }
386
387 // always show a "<- Links" link
388 $links = array(
389 'links' => Linker::linkKnown(
390 $title,
391 $text,
392 array(),
393 array( 'target' => $target->getPrefixedText() )
394 ),
395 );
396
397 // if the page is editable, add an edit link
398 if (
399 // check user permissions
400 $this->getUser()->isAllowed( 'edit' ) &&
401 // check, if the content model is editable through action=edit
402 ContentHandler::getForTitle( $target )->supportsDirectEditing()
403 ) {
404 $links['edit'] = Linker::linkKnown(
405 $target,
406 $editText,
407 array(),
408 array( 'action' => 'edit' )
409 );
410 }
411
412 // build the links html
413 return $this->getLanguage()->pipeList( $links );
414 }
415
416 function makeSelfLink( $text, $query ) {
417 return Linker::linkKnown(
418 $this->selfTitle,
419 $text,
420 array(),
421 $query
422 );
423 }
424
425 function getPrevNext( $prevId, $nextId ) {
426 $currentLimit = $this->opts->getValue( 'limit' );
427 $prev = $this->msg( 'whatlinkshere-prev' )->numParams( $currentLimit )->escaped();
428 $next = $this->msg( 'whatlinkshere-next' )->numParams( $currentLimit )->escaped();
429
430 $changed = $this->opts->getChangedValues();
431 unset( $changed['target'] ); // Already in the request title
432
433 if ( 0 != $prevId ) {
434 $overrides = array( 'from' => $this->opts->getValue( 'back' ) );
435 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
436 }
437 if ( 0 != $nextId ) {
438 $overrides = array( 'from' => $nextId, 'back' => $prevId );
439 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
440 }
441
442 $limitLinks = array();
443 $lang = $this->getLanguage();
444 foreach ( $this->limits as $limit ) {
445 $prettyLimit = htmlspecialchars( $lang->formatNum( $limit ) );
446 $overrides = array( 'limit' => $limit );
447 $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
448 }
449
450 $nums = $lang->pipeList( $limitLinks );
451
452 return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
453 }
454
455 function whatlinkshereForm() {
456 // We get nicer value from the title object
457 $this->opts->consumeValue( 'target' );
458 // Reset these for new requests
459 $this->opts->consumeValues( array( 'back', 'from' ) );
460
461 $target = $this->target ? $this->target->getPrefixedText() : '';
462 $namespace = $this->opts->consumeValue( 'namespace' );
463 $nsinvert = $this->opts->consumeValue( 'invert' );
464
465 # Build up the form
466 $f = Xml::openElement( 'form', array( 'action' => wfScript() ) );
467
468 # Values that should not be forgotten
469 $f .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
470 foreach ( $this->opts->getUnconsumedValues() as $name => $value ) {
471 $f .= Html::hidden( $name, $value );
472 }
473
474 $f .= Xml::fieldset( $this->msg( 'whatlinkshere' )->text() );
475
476 # Target input (.mw-searchInput enables suggestions)
477 $f .= Xml::inputLabel( $this->msg( 'whatlinkshere-page' )->text(), 'target',
478 'mw-whatlinkshere-target', 40, $target, array( 'class' => 'mw-searchInput' ) );
479
480 $f .= ' ';
481
482 # Namespace selector
483 $f .= Html::namespaceSelector(
484 array(
485 'selected' => $namespace,
486 'all' => '',
487 'label' => $this->msg( 'namespace' )->text()
488 ), array(
489 'name' => 'namespace',
490 'id' => 'namespace',
491 'class' => 'namespaceselector',
492 )
493 );
494
495 $f .= '&#160;' .
496 Xml::checkLabel(
497 $this->msg( 'invert' )->text(),
498 'invert',
499 'nsinvert',
500 $nsinvert,
501 array( 'title' => $this->msg( 'tooltip-whatlinkshere-invert' )->text() )
502 );
503
504 $f .= ' ';
505
506 # Submit
507 $f .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
508
509 # Close
510 $f .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ) . "\n";
511
512 return $f;
513 }
514
515 /**
516 * Create filter panel
517 *
518 * @return string HTML fieldset and filter panel with the show/hide links
519 */
520 function getFilterPanel() {
521 $show = $this->msg( 'show' )->escaped();
522 $hide = $this->msg( 'hide' )->escaped();
523
524 $changed = $this->opts->getChangedValues();
525 unset( $changed['target'] ); // Already in the request title
526
527 $links = array();
528 $types = array( 'hidetrans', 'hidelinks', 'hideredirs' );
529 if ( $this->target->getNamespace() == NS_FILE ) {
530 $types[] = 'hideimages';
531 }
532
533 // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans',
534 // 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
535 // To be sure they will be found by grep
536 foreach ( $types as $type ) {
537 $chosen = $this->opts->getValue( $type );
538 $msg = $chosen ? $show : $hide;
539 $overrides = array( $type => !$chosen );
540 $links[] = $this->msg( "whatlinkshere-{$type}" )->rawParams(
541 $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) )->escaped();
542 }
543
544 return Xml::fieldset(
545 $this->msg( 'whatlinkshere-filters' )->text(),
546 $this->getLanguage()->pipeList( $links )
547 );
548 }
549
550 /**
551 * Return an array of subpages beginning with $search that this special page will accept.
552 *
553 * @param string $search Prefix to search for
554 * @param int $limit Maximum number of results to return (usually 10)
555 * @param int $offset Number of results to skip (usually 0)
556 * @return string[] Matching subpages
557 */
558 public function prefixSearchSubpages( $search, $limit, $offset ) {
559 if ( $search === '' ) {
560 return array();
561 }
562 // Autocomplete subpage the same as a normal search
563 $prefixSearcher = new StringPrefixSearch;
564 $result = $prefixSearcher->search( $search, $limit, array(), $offset );
565 return $result;
566 }
567
568 protected function getGroupName() {
569 return 'pagetools';
570 }
571 }