Bug 36453 - Provide the git info on action=query&meta=siteinfo
[mediawiki.git] / includes / api / ApiQueryBacklinks.php
blob9704b6d8d6c92b978807c6422c66d8365b88f7d0
1 <?php
2 /**
5 * Created on Oct 16, 2006
7 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
24 * @file
27 /**
28 * This is a three-in-one module to query:
29 * * backlinks - links pointing to the given page,
30 * * embeddedin - what pages transclude the given page within themselves,
31 * * imageusage - what pages use the given image
33 * @ingroup API
35 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
37 /**
38 * @var Title
40 private $rootTitle;
42 private $params, $contID, $redirID, $redirect;
43 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
45 /**
46 * Maps ns and title to pageid
48 * @var array
50 private $pageMap = array();
51 private $resultArr;
53 private $redirTitles = array();
54 private $continueStr = null;
56 // output element name, database column field prefix, database table
57 private $backlinksSettings = array(
58 'backlinks' => array(
59 'code' => 'bl',
60 'prefix' => 'pl',
61 'linktbl' => 'pagelinks',
62 'helpurl' => 'https://www.mediawiki.org/wiki/API:Backlinks',
64 'embeddedin' => array(
65 'code' => 'ei',
66 'prefix' => 'tl',
67 'linktbl' => 'templatelinks',
68 'helpurl' => 'https://www.mediawiki.org/wiki/API:Embeddedin',
70 'imageusage' => array(
71 'code' => 'iu',
72 'prefix' => 'il',
73 'linktbl' => 'imagelinks',
74 'helpurl' => 'https://www.mediawiki.org/wiki/API:Imageusage',
78 public function __construct( $query, $moduleName ) {
79 $settings = $this->backlinksSettings[$moduleName];
80 $prefix = $settings['prefix'];
81 $code = $settings['code'];
82 $this->resultArr = array();
84 parent::__construct( $query, $moduleName, $code );
85 $this->bl_ns = $prefix . '_namespace';
86 $this->bl_from = $prefix . '_from';
87 $this->bl_table = $settings['linktbl'];
88 $this->bl_code = $code;
89 $this->helpUrl = $settings['helpurl'];
91 $this->hasNS = $moduleName !== 'imageusage';
92 if ( $this->hasNS ) {
93 $this->bl_title = $prefix . '_title';
94 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
95 $this->bl_fields = array(
96 $this->bl_ns,
97 $this->bl_title
99 } else {
100 $this->bl_title = $prefix . '_to';
101 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
102 $this->bl_fields = array(
103 $this->bl_title
108 public function execute() {
109 $this->run();
112 public function getCacheMode( $params ) {
113 return 'public';
116 public function executeGenerator( $resultPageSet ) {
117 $this->run( $resultPageSet );
121 * @param $resultPageSet ApiPageSet
122 * @return void
124 private function prepareFirstQuery( $resultPageSet = null ) {
125 /* SELECT page_id, page_title, page_namespace, page_is_redirect
126 * FROM pagelinks, page WHERE pl_from=page_id
127 * AND pl_title='Foo' AND pl_namespace=0
128 * LIMIT 11 ORDER BY pl_from
130 $this->addTables( array( $this->bl_table, 'page' ) );
131 $this->addWhere( "{$this->bl_from}=page_id" );
132 if ( is_null( $resultPageSet ) ) {
133 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
134 } else {
135 $this->addFields( $resultPageSet->getPageTableFields() );
138 $this->addFields( 'page_is_redirect' );
139 $this->addWhereFld( $this->bl_title, $this->rootTitle->getDBkey() );
141 if ( $this->hasNS ) {
142 $this->addWhereFld( $this->bl_ns, $this->rootTitle->getNamespace() );
144 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
146 if ( !is_null( $this->contID ) ) {
147 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
150 if ( $this->params['filterredir'] == 'redirects' ) {
151 $this->addWhereFld( 'page_is_redirect', 1 );
152 } elseif ( $this->params['filterredir'] == 'nonredirects' && !$this->redirect ) {
153 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
154 $this->addWhereFld( 'page_is_redirect', 0 );
157 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
158 $this->addOption( 'ORDER BY', $this->bl_from );
159 $this->addOption( 'STRAIGHT_JOIN' );
163 * @param $resultPageSet ApiPageSet
164 * @return void
166 private function prepareSecondQuery( $resultPageSet = null ) {
167 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
168 FROM pagelinks, page WHERE pl_from=page_id
169 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
170 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
172 $db = $this->getDB();
173 $this->addTables( array( 'page', $this->bl_table ) );
174 $this->addWhere( "{$this->bl_from}=page_id" );
176 if ( is_null( $resultPageSet ) ) {
177 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
178 } else {
179 $this->addFields( $resultPageSet->getPageTableFields() );
182 $this->addFields( $this->bl_title );
183 if ( $this->hasNS ) {
184 $this->addFields( $this->bl_ns );
187 // We can't use LinkBatch here because $this->hasNS may be false
188 $titleWhere = array();
189 foreach ( $this->redirTitles as $t ) {
190 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
191 ( $this->hasNS ? " AND {$this->bl_ns} = {$t->getNamespace()}" : '' );
193 $this->addWhere( $db->makeList( $titleWhere, LIST_OR ) );
194 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
196 if ( !is_null( $this->redirID ) ) {
197 $first = $this->redirTitles[0];
198 $title = $db->addQuotes( $first->getDBkey() );
199 $ns = $first->getNamespace();
200 $from = $this->redirID;
201 if ( $this->hasNS ) {
202 $this->addWhere( "{$this->bl_ns} > $ns OR " .
203 "({$this->bl_ns} = $ns AND " .
204 "({$this->bl_title} > $title OR " .
205 "({$this->bl_title} = $title AND " .
206 "{$this->bl_from} >= $from)))" );
207 } else {
208 $this->addWhere( "{$this->bl_title} > $title OR " .
209 "({$this->bl_title} = $title AND " .
210 "{$this->bl_from} >= $from)" );
213 if ( $this->params['filterredir'] == 'redirects' ) {
214 $this->addWhereFld( 'page_is_redirect', 1 );
215 } elseif ( $this->params['filterredir'] == 'nonredirects' ) {
216 $this->addWhereFld( 'page_is_redirect', 0 );
219 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
220 $this->addOption( 'ORDER BY', $this->bl_sort );
221 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
225 * @param $resultPageSet ApiPageSet
226 * @return void
228 private function run( $resultPageSet = null ) {
229 $this->params = $this->extractRequestParams( false );
230 $this->redirect = isset( $this->params['redirect'] ) && $this->params['redirect'];
231 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1 / 2 : ApiBase::LIMIT_BIG1 );
232 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2 / 2 : ApiBase::LIMIT_BIG2 );
234 $result = $this->getResult();
236 if ( $this->params['limit'] == 'max' ) {
237 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
238 $result->setParsedLimit( $this->getModuleName(), $this->params['limit'] );
241 $this->processContinue();
242 $this->prepareFirstQuery( $resultPageSet );
244 $res = $this->select( __METHOD__ . '::firstQuery' );
246 $count = 0;
248 foreach ( $res as $row ) {
249 if ( ++ $count > $this->params['limit'] ) {
250 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
251 // Continue string preserved in case the redirect query doesn't pass the limit
252 $this->continueStr = $this->getContinueStr( $row->page_id );
253 break;
256 if ( is_null( $resultPageSet ) ) {
257 $this->extractRowInfo( $row );
258 } else {
259 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
260 if ( $row->page_is_redirect ) {
261 $this->redirTitles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
264 $resultPageSet->processDbRow( $row );
268 if ( $this->redirect && count( $this->redirTitles ) ) {
269 $this->resetQueryParams();
270 $this->prepareSecondQuery( $resultPageSet );
271 $res = $this->select( __METHOD__ . '::secondQuery' );
272 $count = 0;
273 foreach ( $res as $row ) {
274 if ( ++$count > $this->params['limit'] ) {
275 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
276 // We need to keep the parent page of this redir in
277 if ( $this->hasNS ) {
278 $parentID = $this->pageMap[$row-> { $this->bl_ns } ][$row-> { $this->bl_title } ];
279 } else {
280 $parentID = $this->pageMap[NS_FILE][$row-> { $this->bl_title } ];
282 $this->continueStr = $this->getContinueRedirStr( $parentID, $row->page_id );
283 break;
286 if ( is_null( $resultPageSet ) ) {
287 $this->extractRedirRowInfo( $row );
288 } else {
289 $resultPageSet->processDbRow( $row );
293 if ( is_null( $resultPageSet ) ) {
294 // Try to add the result data in one go and pray that it fits
295 $fit = $result->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr ) );
296 if ( !$fit ) {
297 // It didn't fit. Add elements one by one until the
298 // result is full.
299 foreach ( $this->resultArr as $pageID => $arr ) {
300 // Add the basic entry without redirlinks first
301 $fit = $result->addValue(
302 array( 'query', $this->getModuleName() ),
303 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
304 if ( !$fit ) {
305 $this->continueStr = $this->getContinueStr( $pageID );
306 break;
309 $hasRedirs = false;
310 $redirLinks = isset( $arr['redirlinks'] ) ? $arr['redirlinks'] : array();
311 foreach ( (array)$redirLinks as $key => $redir ) {
312 $fit = $result->addValue(
313 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
314 $key, $redir );
315 if ( !$fit ) {
316 $this->continueStr = $this->getContinueRedirStr( $pageID, $redir['pageid'] );
317 break;
319 $hasRedirs = true;
321 if ( $hasRedirs ) {
322 $result->setIndexedTagName_internal(
323 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
324 $this->bl_code );
326 if ( !$fit ) {
327 break;
332 $result->setIndexedTagName_internal(
333 array( 'query', $this->getModuleName() ),
334 $this->bl_code
337 if ( !is_null( $this->continueStr ) ) {
338 $this->setContinueEnumParameter( 'continue', $this->continueStr );
342 private function extractRowInfo( $row ) {
343 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
344 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
345 $a = array( 'pageid' => intval( $row->page_id ) );
346 ApiQueryBase::addTitleInfo( $a, $t );
347 if ( $row->page_is_redirect ) {
348 $a['redirect'] = '';
349 $this->redirTitles[] = $t;
351 // Put all the results in an array first
352 $this->resultArr[$a['pageid']] = $a;
355 private function extractRedirRowInfo( $row ) {
356 $a['pageid'] = intval( $row->page_id );
357 ApiQueryBase::addTitleInfo( $a, Title::makeTitle( $row->page_namespace, $row->page_title ) );
358 if ( $row->page_is_redirect ) {
359 $a['redirect'] = '';
361 $ns = $this->hasNS ? $row-> { $this->bl_ns } : NS_FILE;
362 $parentID = $this->pageMap[$ns][$row-> { $this->bl_title } ];
363 // Put all the results in an array first
364 $this->resultArr[$parentID]['redirlinks'][] = $a;
365 $this->getResult()->setIndexedTagName( $this->resultArr[$parentID]['redirlinks'], $this->bl_code );
368 protected function processContinue() {
369 if ( !is_null( $this->params['continue'] ) ) {
370 $this->parseContinueParam();
371 } else {
372 $this->rootTitle = $this->getTitleOrPageId( $this->params )->getTitle();
375 // only image titles are allowed for the root in imageinfo mode
376 if ( !$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE ) {
377 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
381 protected function parseContinueParam() {
382 $continueList = explode( '|', $this->params['continue'] );
383 // expected format:
384 // ns | key | id1 [| id2]
385 // ns+key: root title
386 // id1: first-level page ID to continue from
387 // id2: second-level page ID to continue from
389 // null stuff out now so we know what's set and what isn't
390 $this->rootTitle = $this->contID = $this->redirID = null;
391 $rootNs = intval( $continueList[0] );
392 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
393 // Illegal continue parameter
394 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
396 $this->rootTitle = Title::makeTitleSafe( $rootNs, $continueList[1] );
398 if ( !$this->rootTitle ) {
399 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
401 $contID = intval( $continueList[2] );
403 if ( $contID === 0 && $continueList[2] !== '0' ) {
404 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
406 $this->contID = $contID;
407 $id2 = isset( $continueList[3] ) ? $continueList[3] : null;
408 $redirID = intval( $id2 );
410 if ( $redirID === 0 && $id2 !== '0' ) {
411 // This one isn't required
412 return;
414 $this->redirID = $redirID;
418 protected function getContinueStr( $lastPageID ) {
419 return $this->rootTitle->getNamespace() .
420 '|' . $this->rootTitle->getDBkey() .
421 '|' . $lastPageID;
424 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
425 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
428 public function getAllowedParams() {
429 $retval = array(
430 'title' => array(
431 ApiBase::PARAM_TYPE => 'string',
433 'pageid' => array(
434 ApiBase::PARAM_TYPE => 'integer',
436 'continue' => null,
437 'namespace' => array(
438 ApiBase::PARAM_ISMULTI => true,
439 ApiBase::PARAM_TYPE => 'namespace'
441 'filterredir' => array(
442 ApiBase::PARAM_DFLT => 'all',
443 ApiBase::PARAM_TYPE => array(
444 'all',
445 'redirects',
446 'nonredirects'
449 'limit' => array(
450 ApiBase::PARAM_DFLT => 10,
451 ApiBase::PARAM_TYPE => 'limit',
452 ApiBase::PARAM_MIN => 1,
453 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
454 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
457 if ( $this->getModuleName() == 'embeddedin' ) {
458 return $retval;
460 $retval['redirect'] = false;
461 return $retval;
464 public function getParamDescription() {
465 $retval = array(
466 'title' => "Title to search. Cannot be used together with {$this->bl_code}pageid",
467 'pageid' => "Pageid to search. Cannot be used together with {$this->bl_code}title",
468 'continue' => 'When more results are available, use this to continue',
469 'namespace' => 'The namespace to enumerate',
471 if ( $this->getModuleName() != 'embeddedin' ) {
472 return array_merge( $retval, array(
473 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
474 '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",
475 '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)."
476 ) );
478 return array_merge( $retval, array(
479 'filterredir' => 'How to filter for redirects',
480 'limit' => 'How many total pages to return'
481 ) );
484 public function getResultProperties() {
485 return array(
486 '' => array(
487 'pageid' => 'integer',
488 'ns' => 'namespace',
489 'title' => 'string',
490 'redirect' => 'boolean'
495 public function getDescription() {
496 switch ( $this->getModuleName() ) {
497 case 'backlinks':
498 return 'Find all pages that link to the given page';
499 case 'embeddedin':
500 return 'Find all pages that embed (transclude) the given title';
501 case 'imageusage':
502 return 'Find all pages that use the given image title.';
503 default:
504 ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
508 public function getPossibleErrors() {
509 return array_merge( parent::getPossibleErrors(),
510 $this->getTitleOrPageIdErrorMessage(),
511 array(
512 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
513 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
518 public function getExamples() {
519 static $examples = array(
520 'backlinks' => array(
521 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
522 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
524 'embeddedin' => array(
525 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
526 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
528 'imageusage' => array(
529 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
530 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
534 return $examples[$this->getModuleName()];
537 public function getHelpUrls() {
538 return $this->helpUrl;
541 public function getVersion() {
542 return __CLASS__ . ': $Id$';