Function out query building, to allow easier overriding
[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 SpecialPage {
30
31 // Stored objects
32 protected $opts, $target, $selfTitle;
33
34 // Stored globals
35 protected $skin;
36
37 protected $limits = array( 20, 50, 100, 250, 500 );
38
39 public function __construct() {
40 parent::__construct( 'Whatlinkshere' );
41 global $wgUser;
42 $this->skin = $wgUser->getSkin();
43 }
44
45 function execute( $par ) {
46 global $wgOut, $wgRequest;
47
48 $this->setHeaders();
49
50 $opts = new FormOptions();
51
52 $opts->add( 'target', '' );
53 $opts->add( 'namespace', '', FormOptions::INTNULL );
54 $opts->add( 'limit', 50 );
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
62 $opts->fetchValuesFromRequest( $wgRequest );
63 $opts->validateIntBounds( 'limit', 0, 5000 );
64
65 // Give precedence to subpage syntax
66 if ( isset($par) ) {
67 $opts->setValue( 'target', $par );
68 }
69
70 // Bind to member variable
71 $this->opts = $opts;
72
73 $this->target = Title::newFromURL( $opts->getValue( 'target' ) );
74 if( !$this->target ) {
75 $wgOut->addHTML( $this->whatlinkshereForm() );
76 return;
77 }
78
79 $this->skin->setRelevantTitle( $this->target );
80
81
82 $this->selfTitle = $this->getTitle( $this->target->getPrefixedDBkey() );
83
84 $wgOut->setPageTitle( wfMsg( 'whatlinkshere-title', $this->target->getPrefixedText() ) );
85 $wgOut->setSubtitle( wfMsg( 'whatlinkshere-backlink', $this->skin->link( $this->target, $this->target->getPrefixedText(), array(), array( 'redirect' => 'no' ) ) ) );
86
87 $this->showIndirectLinks( 0, $this->target, $opts->getValue( 'limit' ),
88 $opts->getValue( 'from' ), $opts->getValue( 'back' ) );
89 }
90
91 /**
92 * @param $level int Recursion level
93 * @param $target Title Target title
94 * @param $limit int Number of entries to display
95 * @param $from Title Display from this article ID
96 * @param $back Title Display from this article ID at backwards scrolling
97 * @private
98 */
99 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
100 global $wgOut, $wgMaxRedirectLinksRetrieved;
101 $dbr = wfGetDB( DB_SLAVE );
102 $options = array();
103
104 $hidelinks = $this->opts->getValue( 'hidelinks' );
105 $hideredirs = $this->opts->getValue( 'hideredirs' );
106 $hidetrans = $this->opts->getValue( 'hidetrans' );
107 $hideimages = $target->getNamespace() != NS_FILE || $this->opts->getValue( 'hideimages' );
108
109 $fetchlinks = (!$hidelinks || !$hideredirs);
110
111 // Make the query
112 $plConds = array(
113 'page_id=pl_from',
114 'pl_namespace' => $target->getNamespace(),
115 'pl_title' => $target->getDBkey(),
116 );
117 if( $hideredirs ) {
118 $plConds['page_is_redirect'] = 0;
119 } elseif( $hidelinks ) {
120 $plConds['page_is_redirect'] = 1;
121 }
122
123 $tlConds = array(
124 'page_id=tl_from',
125 'tl_namespace' => $target->getNamespace(),
126 'tl_title' => $target->getDBkey(),
127 );
128
129 $ilConds = array(
130 'page_id=il_from',
131 'il_to' => $target->getDBkey(),
132 );
133
134 $namespace = $this->opts->getValue( 'namespace' );
135 if ( is_int($namespace) ) {
136 $plConds['page_namespace'] = $namespace;
137 $tlConds['page_namespace'] = $namespace;
138 $ilConds['page_namespace'] = $namespace;
139 }
140
141 if ( $from ) {
142 $tlConds[] = "tl_from >= $from";
143 $plConds[] = "pl_from >= $from";
144 $ilConds[] = "il_from >= $from";
145 }
146
147 // Read an extra row as an at-end check
148 $queryLimit = $limit + 1;
149
150 // Enforce join order, sometimes namespace selector may
151 // trigger filesorts which are far less efficient than scanning many entries
152 $options[] = 'STRAIGHT_JOIN';
153
154 $options['LIMIT'] = $queryLimit;
155 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' );
156
157 if( $fetchlinks ) {
158 $options['ORDER BY'] = 'pl_from';
159 $plRes = $dbr->select( array( 'pagelinks', 'page' ), $fields,
160 $plConds, __METHOD__, $options );
161 }
162
163 if( !$hidetrans ) {
164 $options['ORDER BY'] = 'tl_from';
165 $tlRes = $dbr->select( array( 'templatelinks', 'page' ), $fields,
166 $tlConds, __METHOD__, $options );
167 }
168
169 if( !$hideimages ) {
170 $options['ORDER BY'] = 'il_from';
171 $ilRes = $dbr->select( array( 'imagelinks', 'page' ), $fields,
172 $ilConds, __METHOD__, $options );
173 }
174
175 if( ( !$fetchlinks || !$dbr->numRows($plRes) ) && ( $hidetrans || !$dbr->numRows($tlRes) ) && ( $hideimages || !$dbr->numRows($ilRes) ) ) {
176 if ( 0 == $level ) {
177 $wgOut->addHTML( $this->whatlinkshereForm() );
178
179 // Show filters only if there are links
180 if( $hidelinks || $hidetrans || $hideredirs || $hideimages )
181 $wgOut->addHTML( $this->getFilterPanel() );
182
183 $errMsg = is_int($namespace) ? 'nolinkshere-ns' : 'nolinkshere';
184 $wgOut->addWikiMsg( $errMsg, $this->target->getPrefixedText() );
185 }
186 return;
187 }
188
189 // Read the rows into an array and remove duplicates
190 // templatelinks comes second so that the templatelinks row overwrites the
191 // pagelinks row, so we get (inclusion) rather than nothing
192 if( $fetchlinks ) {
193 foreach ( $plRes as $row ) {
194 $row->is_template = 0;
195 $row->is_image = 0;
196 $rows[$row->page_id] = $row;
197 }
198 }
199 if( !$hidetrans ) {
200 foreach ( $tlRes as $row ) {
201 $row->is_template = 1;
202 $row->is_image = 0;
203 $rows[$row->page_id] = $row;
204 }
205 }
206 if( !$hideimages ) {
207 foreach ( $ilRes as $row ) {
208 $row->is_template = 0;
209 $row->is_image = 1;
210 $rows[$row->page_id] = $row;
211 }
212 }
213
214 // Sort by key and then change the keys to 0-based indices
215 ksort( $rows );
216 $rows = array_values( $rows );
217
218 $numRows = count( $rows );
219
220 // Work out the start and end IDs, for prev/next links
221 if ( $numRows > $limit ) {
222 // More rows available after these ones
223 // Get the ID from the last row in the result set
224 $nextId = $rows[$limit]->page_id;
225 // Remove undisplayed rows
226 $rows = array_slice( $rows, 0, $limit );
227 } else {
228 // No more rows after
229 $nextId = false;
230 }
231 $prevId = $from;
232
233 if ( $level == 0 ) {
234 $wgOut->addHTML( $this->whatlinkshereForm() );
235 $wgOut->addHTML( $this->getFilterPanel() );
236 $wgOut->addWikiMsg( 'linkshere', $this->target->getPrefixedText() );
237
238 $prevnext = $this->getPrevNext( $prevId, $nextId );
239 $wgOut->addHTML( $prevnext );
240 }
241
242 $wgOut->addHTML( $this->listStart() );
243 foreach ( $rows as $row ) {
244 $nt = Title::makeTitle( $row->page_namespace, $row->page_title );
245
246 if ( $row->page_is_redirect && $level < 2 ) {
247 $wgOut->addHTML( $this->listItem( $row, $nt, true ) );
248 $this->showIndirectLinks( $level + 1, $nt, $wgMaxRedirectLinksRetrieved );
249 $wgOut->addHTML( Xml::closeElement( 'li' ) );
250 } else {
251 $wgOut->addHTML( $this->listItem( $row, $nt ) );
252 }
253 }
254
255 $wgOut->addHTML( $this->listEnd() );
256
257 if( $level == 0 ) {
258 $wgOut->addHTML( $prevnext );
259 }
260 }
261
262 protected function listStart() {
263 return Xml::openElement( 'ul', array ( 'id' => 'mw-whatlinkshere-list' ) );
264 }
265
266 protected function listItem( $row, $nt, $notClose = false ) {
267 global $wgLang;
268
269 # local message cache
270 static $msgcache = null;
271 if ( $msgcache === null ) {
272 static $msgs = array( 'isredirect', 'istemplate', 'semicolon-separator',
273 'whatlinkshere-links', 'isimage', 'hist' );
274 $msgcache = array();
275 foreach ( $msgs as $msg ) {
276 $msgcache[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) );
277 }
278 }
279
280 if( $row->page_is_redirect ) {
281 $query = array( 'redirect' => 'no' );
282 } else {
283 $query = array();
284 }
285
286 $link = $this->skin->linkKnown(
287 $nt,
288 null,
289 array(),
290 $query
291 );
292
293 // Display properties (redirect or template)
294 $propsText = '';
295 $props = array();
296 if ( $row->page_is_redirect )
297 $props[] = $msgcache['isredirect'];
298 if ( $row->is_template )
299 $props[] = $msgcache['istemplate'];
300 if( $row->is_image )
301 $props[] = $msgcache['isimage'];
302
303 if ( count( $props ) ) {
304 $propsText = '(' . implode( $msgcache['semicolon-separator'], $props ) . ')';
305 }
306
307 # Space for utilities links, with a what-links-here link provided
308 $tools = array();
309 $tools[] = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'] );
310 $tools[] = $this->skin->linkKnown( $nt, $msgcache['hist'], array(), array( 'action' => 'history' ) );
311 $wlh = Xml::wrapClass( '(' . $wgLang->pipeList( $tools ) . ')', 'mw-whatlinkshere-tools' );
312
313 return $notClose ?
314 Xml::openElement( 'li' ) . "$link $propsText $wlh\n" :
315 Xml::tags( 'li', null, "$link $propsText $wlh" ) . "\n";
316 }
317
318 protected function listEnd() {
319 return Xml::closeElement( 'ul' );
320 }
321
322 protected function wlhLink( Title $target, $text ) {
323 static $title = null;
324 if ( $title === null )
325 $title = $this->getTitle();
326
327 return $this->skin->linkKnown(
328 $title,
329 $text,
330 array(),
331 array( 'target' => $target->getPrefixedText() )
332 );
333 }
334
335 function makeSelfLink( $text, $query ) {
336 return $this->skin->linkKnown(
337 $this->selfTitle,
338 $text,
339 array(),
340 $query
341 );
342 }
343
344 function getPrevNext( $prevId, $nextId ) {
345 global $wgLang;
346 $currentLimit = $this->opts->getValue( 'limit' );
347 $fmtLimit = $wgLang->formatNum( $currentLimit );
348 $prev = wfMsgExt( 'whatlinkshere-prev', array( 'parsemag', 'escape' ), $fmtLimit );
349 $next = wfMsgExt( 'whatlinkshere-next', array( 'parsemag', 'escape' ), $fmtLimit );
350
351 $changed = $this->opts->getChangedValues();
352 unset($changed['target']); // Already in the request title
353
354 if ( 0 != $prevId ) {
355 $overrides = array( 'from' => $this->opts->getValue( 'back' ) );
356 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
357 }
358 if ( 0 != $nextId ) {
359 $overrides = array( 'from' => $nextId, 'back' => $prevId );
360 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
361 }
362
363 $limitLinks = array();
364 foreach ( $this->limits as $limit ) {
365 $prettyLimit = $wgLang->formatNum( $limit );
366 $overrides = array( 'limit' => $limit );
367 $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
368 }
369
370 $nums = $wgLang->pipeList( $limitLinks );
371
372 return wfMsgHtml( 'viewprevnext', $prev, $next, $nums );
373 }
374
375 function whatlinkshereForm() {
376 global $wgScript;
377
378 // We get nicer value from the title object
379 $this->opts->consumeValue( 'target' );
380 // Reset these for new requests
381 $this->opts->consumeValues( array( 'back', 'from' ) );
382
383 $target = $this->target ? $this->target->getPrefixedText() : '';
384 $namespace = $this->opts->consumeValue( 'namespace' );
385
386 # Build up the form
387 $f = Xml::openElement( 'form', array( 'action' => $wgScript ) );
388
389 # Values that should not be forgotten
390 $f .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() );
391 foreach ( $this->opts->getUnconsumedValues() as $name => $value ) {
392 $f .= Html::hidden( $name, $value );
393 }
394
395 $f .= Xml::fieldset( wfMsg( 'whatlinkshere' ) );
396
397 # Target input
398 $f .= Xml::inputLabel( wfMsg( 'whatlinkshere-page' ), 'target',
399 'mw-whatlinkshere-target', 40, $target );
400
401 $f .= ' ';
402
403 # Namespace selector
404 $f .= Xml::label( wfMsg( 'namespace' ), 'namespace' ) . '&#160;' .
405 Xml::namespaceSelector( $namespace, '' );
406
407 $f .= ' ';
408
409 # Submit
410 $f .= Xml::submitButton( wfMsg( 'allpagessubmit' ) );
411
412 # Close
413 $f .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ) . "\n";
414
415 return $f;
416 }
417
418 /**
419 * Create filter panel
420 *
421 * @return string HTML fieldset and filter panel with the show/hide links
422 */
423 function getFilterPanel() {
424 global $wgLang;
425 $show = wfMsgHtml( 'show' );
426 $hide = wfMsgHtml( 'hide' );
427
428 $changed = $this->opts->getChangedValues();
429 unset($changed['target']); // Already in the request title
430
431 $links = array();
432 $types = array( 'hidetrans', 'hidelinks', 'hideredirs' );
433 if( $this->target->getNamespace() == NS_FILE )
434 $types[] = 'hideimages';
435
436 // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans', 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
437 // To be sure they will be find by grep
438 foreach( $types as $type ) {
439 $chosen = $this->opts->getValue( $type );
440 $msg = $chosen ? $show : $hide;
441 $overrides = array( $type => !$chosen );
442 $links[] = wfMsgHtml( "whatlinkshere-{$type}", $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) );
443 }
444 return Xml::fieldset( wfMsg( 'whatlinkshere-filters' ), $wgLang->pipeList( $links ) );
445 }
446 }