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