Remove various unused parameters
[lhc/web/wiklou.git] / includes / api / ApiQueryBacklinks.php
1 <?php
2
3 /*
4 * Created on Oct 16, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( "ApiQueryBase.php" );
29 }
30
31 /**
32 * This is a three-in-one module to query:
33 * * backlinks - links pointing to the given page,
34 * * embeddedin - what pages transclude the given page within themselves,
35 * * imageusage - what pages use the given image
36 *
37 * @ingroup API
38 */
39 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
40
41 private $params, $rootTitle, $contID, $redirID, $redirect;
42 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
43 private $pageMap, $resultArr;
44
45 // output element name, database column field prefix, database table
46 private $backlinksSettings = array(
47 'backlinks' => array(
48 'code' => 'bl',
49 'prefix' => 'pl',
50 'linktbl' => 'pagelinks'
51 ),
52 'embeddedin' => array(
53 'code' => 'ei',
54 'prefix' => 'tl',
55 'linktbl' => 'templatelinks'
56 ),
57 'imageusage' => array(
58 'code' => 'iu',
59 'prefix' => 'il',
60 'linktbl' => 'imagelinks'
61 )
62 );
63
64 public function __construct( $query, $moduleName ) {
65 extract( $this->backlinksSettings[$moduleName] );
66 $this->resultArr = array();
67
68 parent::__construct( $query, $moduleName, $code );
69 $this->bl_ns = $prefix . '_namespace';
70 $this->bl_from = $prefix . '_from';
71 $this->bl_table = $linktbl;
72 $this->bl_code = $code;
73
74 $this->hasNS = $moduleName !== 'imageusage';
75 if ( $this->hasNS ) {
76 $this->bl_title = $prefix . '_title';
77 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
78 $this->bl_fields = array(
79 $this->bl_ns,
80 $this->bl_title
81 );
82 } else {
83 $this->bl_title = $prefix . '_to';
84 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
85 $this->bl_fields = array(
86 $this->bl_title
87 );
88 }
89 }
90
91 public function execute() {
92 $this->run();
93 }
94
95 public function executeGenerator( $resultPageSet ) {
96 $this->run( $resultPageSet );
97 }
98
99 private function prepareFirstQuery( $resultPageSet = null ) {
100 /* SELECT page_id, page_title, page_namespace, page_is_redirect
101 * FROM pagelinks, page WHERE pl_from=page_id
102 * AND pl_title='Foo' AND pl_namespace=0
103 * LIMIT 11 ORDER BY pl_from
104 */
105 $db = $this->getDB();
106 $this->addTables( array( $this->bl_table, 'page' ) );
107 $this->addWhere( "{$this->bl_from}=page_id" );
108 if ( is_null( $resultPageSet ) ) {
109 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
110 } else {
111 $this->addFields( $resultPageSet->getPageTableFields() );
112 }
113
114 $this->addFields( 'page_is_redirect' );
115 $this->addWhereFld( $this->bl_title, $this->rootTitle->getDBkey() );
116
117 if ( $this->hasNS ) {
118 $this->addWhereFld( $this->bl_ns, $this->rootTitle->getNamespace() );
119 }
120 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
121
122 if ( !is_null( $this->contID ) ) {
123 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
124 }
125
126 if ( $this->params['filterredir'] == 'redirects' ) {
127 $this->addWhereFld( 'page_is_redirect', 1 );
128 } elseif ( $this->params['filterredir'] == 'nonredirects' && !$this->redirect ) {
129 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
130 $this->addWhereFld( 'page_is_redirect', 0 );
131 }
132
133 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
134 $this->addOption( 'ORDER BY', $this->bl_from );
135 $this->addOption( 'STRAIGHT_JOIN' );
136 }
137
138 private function prepareSecondQuery( $resultPageSet = null ) {
139 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
140 FROM pagelinks, page WHERE pl_from=page_id
141 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
142 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
143 */
144 $db = $this->getDB();
145 $this->addTables( array( 'page', $this->bl_table ) );
146 $this->addWhere( "{$this->bl_from}=page_id" );
147
148 if ( is_null( $resultPageSet ) ) {
149 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
150 } else {
151 $this->addFields( $resultPageSet->getPageTableFields() );
152 }
153
154 $this->addFields( $this->bl_title );
155 if ( $this->hasNS ) {
156 $this->addFields( $this->bl_ns );
157 }
158
159 // We can't use LinkBatch here because $this->hasNS may be false
160 $titleWhere = array();
161 foreach ( $this->redirTitles as $t ) {
162 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
163 ( $this->hasNS ? " AND {$this->bl_ns} = '{$t->getNamespace()}'" : '' );
164 }
165 $this->addWhere( $db->makeList( $titleWhere, LIST_OR ) );
166 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
167
168 if ( !is_null( $this->redirID ) ) {
169 $first = $this->redirTitles[0];
170 $title = $db->strencode( $first->getDBkey() );
171 $ns = $first->getNamespace();
172 $from = $this->redirID;
173 if ( $this->hasNS ) {
174 $this->addWhere( "{$this->bl_ns} > $ns OR " .
175 "({$this->bl_ns} = $ns AND " .
176 "({$this->bl_title} > '$title' OR " .
177 "({$this->bl_title} = '$title' AND " .
178 "{$this->bl_from} >= $from)))" );
179 } else {
180 $this->addWhere( "{$this->bl_title} > '$title' OR " .
181 "({$this->bl_title} = '$title' AND " .
182 "{$this->bl_from} >= $from)" );
183 }
184 }
185 if ( $this->params['filterredir'] == 'redirects' ) {
186 $this->addWhereFld( 'page_is_redirect', 1 );
187 } elseif ( $this->params['filterredir'] == 'nonredirects' ) {
188 $this->addWhereFld( 'page_is_redirect', 0 );
189 }
190
191 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
192 $this->addOption( 'ORDER BY', $this->bl_sort );
193 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
194 }
195
196 private function run( $resultPageSet = null ) {
197 $this->params = $this->extractRequestParams( false );
198 $this->redirect = isset( $this->params['redirect'] ) && $this->params['redirect'];
199 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1 / 2 : ApiBase::LIMIT_BIG1 );
200 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2 / 2 : ApiBase::LIMIT_BIG2 );
201 if ( $this->params['limit'] == 'max' ) {
202 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
203 $this->getResult()->addValue( 'limits', $this->getModuleName(), $this->params['limit'] );
204 }
205
206 $this->processContinue();
207 $this->prepareFirstQuery( $resultPageSet );
208
209 $db = $this->getDB();
210 $res = $this->select( __METHOD__ . '::firstQuery' );
211
212 $count = 0;
213 $this->pageMap = array(); // Maps ns and title to pageid
214 $this->continueStr = null;
215 $this->redirTitles = array();
216 foreach ( $res as $row ) {
217 if ( ++ $count > $this->params['limit'] ) {
218 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
219 // Continue string preserved in case the redirect query doesn't pass the limit
220 $this->continueStr = $this->getContinueStr( $row->page_id );
221 break;
222 }
223
224 if ( is_null( $resultPageSet ) ) {
225 $this->extractRowInfo( $row );
226 } else {
227 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
228 if ( $row->page_is_redirect ) {
229 $this->redirTitles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
230 }
231
232 $resultPageSet->processDbRow( $row );
233 }
234 }
235
236 if ( $this->redirect && count( $this->redirTitles ) ) {
237 $this->resetQueryParams();
238 $this->prepareSecondQuery( $resultPageSet );
239 $res = $this->select( __METHOD__ . '::secondQuery' );
240 $count = 0;
241 foreach ( $res as $row ) {
242 if ( ++$count > $this->params['limit'] ) {
243 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
244 // We need to keep the parent page of this redir in
245 if ( $this->hasNS ) {
246 $parentID = $this->pageMap[$row-> { $this->bl_ns } ][$row-> { $this->bl_title } ];
247 } else {
248 $parentID = $this->pageMap[NS_IMAGE][$row-> { $this->bl_title } ];
249 }
250 $this->continueStr = $this->getContinueRedirStr( $parentID, $row->page_id );
251 break;
252 }
253
254 if ( is_null( $resultPageSet ) ) {
255 $this->extractRedirRowInfo( $row );
256 } else {
257 $resultPageSet->processDbRow( $row );
258 }
259 }
260 }
261 if ( is_null( $resultPageSet ) ) {
262 // Try to add the result data in one go and pray that it fits
263 $fit = $this->getResult()->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr ) );
264 if ( !$fit ) {
265 // It didn't fit. Add elements one by one until the
266 // result is full.
267 foreach ( $this->resultArr as $pageID => $arr ) {
268 // Add the basic entry without redirlinks first
269 $fit = $this->getResult()->addValue(
270 array( 'query', $this->getModuleName() ),
271 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
272 if ( !$fit ) {
273 $this->continueStr = $this->getContinueStr( $pageID );
274 break;
275 }
276
277 $hasRedirs = false;
278 foreach ( (array)@$arr['redirlinks'] as $key => $redir ) {
279 $fit = $this->getResult()->addValue(
280 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
281 $key, $redir );
282 if ( !$fit ) {
283 $this->continueStr = $this->getContinueRedirStr( $pageID, $redir['pageid'] );
284 break;
285 }
286 $hasRedirs = true;
287 }
288 if ( $hasRedirs ) {
289 $this->getResult()->setIndexedTagName_internal(
290 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
291 $this->bl_code );
292 }
293 if ( !$fit ) {
294 break;
295 }
296 }
297 }
298
299 $this->getResult()->setIndexedTagName_internal(
300 array( 'query', $this->getModuleName() ),
301 $this->bl_code
302 );
303 }
304 if ( !is_null( $this->continueStr ) ) {
305 $this->setContinueEnumParameter( 'continue', $this->continueStr );
306 }
307 }
308
309 private function extractRowInfo( $row ) {
310 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
311 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
312 $a = array( 'pageid' => intval( $row->page_id ) );
313 ApiQueryBase::addTitleInfo( $a, $t );
314 if ( $row->page_is_redirect ) {
315 $a['redirect'] = '';
316 $this->redirTitles[] = $t;
317 }
318 // Put all the results in an array first
319 $this->resultArr[$a['pageid']] = $a;
320 }
321
322 private function extractRedirRowInfo( $row ) {
323 $a['pageid'] = intval( $row->page_id );
324 ApiQueryBase::addTitleInfo( $a, Title::makeTitle( $row->page_namespace, $row->page_title ) );
325 if ( $row->page_is_redirect ) {
326 $a['redirect'] = '';
327 }
328 $ns = $this->hasNS ? $row-> { $this->bl_ns } : NS_FILE;
329 $parentID = $this->pageMap[$ns][$row-> { $this->bl_title } ];
330 // Put all the results in an array first
331 $this->resultArr[$parentID]['redirlinks'][] = $a;
332 $this->getResult()->setIndexedTagName( $this->resultArr[$parentID]['redirlinks'], $this->bl_code );
333 }
334
335 protected function processContinue() {
336 if ( !is_null( $this->params['continue'] ) ) {
337 $this->parseContinueParam();
338 } else {
339 if ( $this->params['title'] !== '' ) {
340 $title = Title::newFromText( $this->params['title'] );
341 if ( !$title ) {
342 $this->dieUsageMsg( array( 'invalidtitle', $this->params['title'] ) );
343 } else {
344 $this->rootTitle = $title;
345 }
346 } else {
347 $this->dieUsageMsg( array( 'missingparam', 'title' ) );
348 }
349 }
350
351 // only image titles are allowed for the root in imageinfo mode
352 if ( !$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE ) {
353 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
354 }
355 }
356
357 protected function parseContinueParam() {
358 $continueList = explode( '|', $this->params['continue'] );
359 // expected format:
360 // ns | key | id1 [| id2]
361 // ns+key: root title
362 // id1: first-level page ID to continue from
363 // id2: second-level page ID to continue from
364
365 // null stuff out now so we know what's set and what isn't
366 $this->rootTitle = $this->contID = $this->redirID = null;
367 $rootNs = intval( $continueList[0] );
368 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
369 // Illegal continue parameter
370 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
371 }
372 $this->rootTitle = Title::makeTitleSafe( $rootNs, $continueList[1] );
373
374 if ( !$this->rootTitle ) {
375 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
376 }
377 $contID = intval( $continueList[2] );
378
379 if ( $contID === 0 && $continueList[2] !== '0' ) {
380 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
381 }
382 $this->contID = $contID;
383 $redirID = intval( @$continueList[3] );
384
385 if ( $redirID === 0 && @$continueList[3] !== '0' ) {
386 // This one isn't required
387 return;
388 }
389 $this->redirID = $redirID;
390
391 }
392
393 protected function getContinueStr( $lastPageID ) {
394 return $this->rootTitle->getNamespace() .
395 '|' . $this->rootTitle->getDBkey() .
396 '|' . $lastPageID;
397 }
398
399 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
400 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
401 }
402
403 public function getAllowedParams() {
404 $retval = array(
405 'title' => null,
406 'continue' => null,
407 'namespace' => array(
408 ApiBase::PARAM_ISMULTI => true,
409 ApiBase::PARAM_TYPE => 'namespace'
410 ),
411 'filterredir' => array(
412 ApiBase::PARAM_DFLT => 'all',
413 ApiBase::PARAM_TYPE => array(
414 'all',
415 'redirects',
416 'nonredirects'
417 )
418 ),
419 'limit' => array(
420 ApiBase::PARAM_DFLT => 10,
421 ApiBase::PARAM_TYPE => 'limit',
422 ApiBase::PARAM_MIN => 1,
423 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
424 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
425 )
426 );
427 if ( $this->getModuleName() == 'embeddedin' ) {
428 return $retval;
429 }
430 $retval['redirect'] = false;
431 return $retval;
432 }
433
434 public function getParamDescription() {
435 $retval = array(
436 'title' => 'Title to search',
437 'continue' => 'When more results are available, use this to continue',
438 'namespace' => 'The namespace to enumerate',
439 );
440 if ( $this->getModuleName() != 'embeddedin' ) {
441 return array_merge( $retval, array(
442 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
443 'filterredir' => "How to filter for redirects. If set to nonredirects when {$this->bl_code}redirect is enabled, this is only applied to the second level",
444 'limit' => "How many total pages to return. If {$this->bl_code}redirect is enabled, limit applies to each level separately (which means you may get up to 2 * limit results)."
445 ) );
446 }
447 return array_merge( $retval, array(
448 'filterredir' => 'How to filter for redirects',
449 'limit' => 'How many total pages to return'
450 ) );
451 }
452
453 public function getDescription() {
454 switch ( $this->getModuleName() ) {
455 case 'backlinks':
456 return 'Find all pages that link to the given page';
457 case 'embeddedin':
458 return 'Find all pages that embed (transclude) the given title';
459 case 'imageusage':
460 return 'Find all pages that use the given image title.';
461 default:
462 ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
463 }
464 }
465
466 public function getPossibleErrors() {
467 return array_merge( parent::getPossibleErrors(), array(
468 array( 'invalidtitle', 'title' ),
469 array( 'missingparam', 'title' ),
470 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
471 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
472 ) );
473 }
474
475 protected function getExamples() {
476 static $examples = array(
477 'backlinks' => array(
478 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
479 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
480 ),
481 'embeddedin' => array(
482 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
483 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
484 ),
485 'imageusage' => array(
486 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
487 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
488 )
489 );
490
491 return $examples[$this->getModuleName()];
492 }
493
494 public function getVersion() {
495 return __CLASS__ . ': $Id$';
496 }
497 }