3 * API for MediaWiki 1.8+
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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiQueryBase.php" );
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
40 class ApiQueryBacklinks
extends ApiQueryGeneratorBase
{
42 private $params, $rootTitle, $contID, $redirID, $redirect;
43 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
44 private $pageMap, $resultArr;
46 // output element name, database column field prefix, database table
47 private $backlinksSettings = array(
51 'linktbl' => 'pagelinks'
53 'embeddedin' => array(
56 'linktbl' => 'templatelinks'
58 'imageusage' => array(
61 'linktbl' => 'imagelinks'
65 public function __construct( $query, $moduleName ) {
66 extract( $this->backlinksSettings
[$moduleName] );
67 $this->resultArr
= array();
69 parent
::__construct( $query, $moduleName, $code );
70 $this->bl_ns
= $prefix . '_namespace';
71 $this->bl_from
= $prefix . '_from';
72 $this->bl_table
= $linktbl;
73 $this->bl_code
= $code;
75 $this->hasNS
= $moduleName !== 'imageusage';
77 $this->bl_title
= $prefix . '_title';
78 $this->bl_sort
= "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
79 $this->bl_fields
= array(
84 $this->bl_title
= $prefix . '_to';
85 $this->bl_sort
= "{$this->bl_title}, {$this->bl_from}";
86 $this->bl_fields
= array(
92 public function execute() {
96 public function getCacheMode( $params ) {
100 public function executeGenerator( $resultPageSet ) {
101 $this->run( $resultPageSet );
104 private function prepareFirstQuery( $resultPageSet = null ) {
105 /* SELECT page_id, page_title, page_namespace, page_is_redirect
106 * FROM pagelinks, page WHERE pl_from=page_id
107 * AND pl_title='Foo' AND pl_namespace=0
108 * LIMIT 11 ORDER BY pl_from
110 $this->addTables( array( $this->bl_table
, 'page' ) );
111 $this->addWhere( "{$this->bl_from}=page_id" );
112 if ( is_null( $resultPageSet ) ) {
113 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
115 $this->addFields( $resultPageSet->getPageTableFields() );
118 $this->addFields( 'page_is_redirect' );
119 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
121 if ( $this->hasNS
) {
122 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
124 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
126 if ( !is_null( $this->contID
) ) {
127 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
130 if ( $this->params
['filterredir'] == 'redirects' ) {
131 $this->addWhereFld( 'page_is_redirect', 1 );
132 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
133 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
134 $this->addWhereFld( 'page_is_redirect', 0 );
137 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
138 $this->addOption( 'ORDER BY', $this->bl_from
);
139 $this->addOption( 'STRAIGHT_JOIN' );
142 private function prepareSecondQuery( $resultPageSet = null ) {
143 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
144 FROM pagelinks, page WHERE pl_from=page_id
145 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
146 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
148 $db = $this->getDB();
149 $this->addTables( array( 'page', $this->bl_table
) );
150 $this->addWhere( "{$this->bl_from}=page_id" );
152 if ( is_null( $resultPageSet ) ) {
153 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
155 $this->addFields( $resultPageSet->getPageTableFields() );
158 $this->addFields( $this->bl_title
);
159 if ( $this->hasNS
) {
160 $this->addFields( $this->bl_ns
);
163 // We can't use LinkBatch here because $this->hasNS may be false
164 $titleWhere = array();
165 foreach ( $this->redirTitles
as $t ) {
166 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
167 ( $this->hasNS ?
" AND {$this->bl_ns} = '{$t->getNamespace()}'" : '' );
169 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
170 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
172 if ( !is_null( $this->redirID
) ) {
173 $first = $this->redirTitles
[0];
174 $title = $db->strencode( $first->getDBkey() );
175 $ns = $first->getNamespace();
176 $from = $this->redirID
;
177 if ( $this->hasNS
) {
178 $this->addWhere( "{$this->bl_ns} > $ns OR " .
179 "({$this->bl_ns} = $ns AND " .
180 "({$this->bl_title} > '$title' OR " .
181 "({$this->bl_title} = '$title' AND " .
182 "{$this->bl_from} >= $from)))" );
184 $this->addWhere( "{$this->bl_title} > '$title' OR " .
185 "({$this->bl_title} = '$title' AND " .
186 "{$this->bl_from} >= $from)" );
189 if ( $this->params
['filterredir'] == 'redirects' ) {
190 $this->addWhereFld( 'page_is_redirect', 1 );
191 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
192 $this->addWhereFld( 'page_is_redirect', 0 );
195 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
196 $this->addOption( 'ORDER BY', $this->bl_sort
);
197 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
200 private function run( $resultPageSet = null ) {
201 $this->params
= $this->extractRequestParams( false );
202 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
203 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
204 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
205 if ( $this->params
['limit'] == 'max' ) {
206 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
207 $this->getResult()->setParsedLimit( $this->getModuleName(), $this->params
['limit'] );
210 $this->processContinue();
211 $this->prepareFirstQuery( $resultPageSet );
213 $res = $this->select( __METHOD__
. '::firstQuery' );
216 $this->pageMap
= array(); // Maps ns and title to pageid
217 $this->continueStr
= null;
218 $this->redirTitles
= array();
219 foreach ( $res as $row ) {
220 if ( ++
$count > $this->params
['limit'] ) {
221 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
222 // Continue string preserved in case the redirect query doesn't pass the limit
223 $this->continueStr
= $this->getContinueStr( $row->page_id
);
227 if ( is_null( $resultPageSet ) ) {
228 $this->extractRowInfo( $row );
230 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
231 if ( $row->page_is_redirect
) {
232 $this->redirTitles
[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
235 $resultPageSet->processDbRow( $row );
239 if ( $this->redirect
&& count( $this->redirTitles
) ) {
240 $this->resetQueryParams();
241 $this->prepareSecondQuery( $resultPageSet );
242 $res = $this->select( __METHOD__
. '::secondQuery' );
244 foreach ( $res as $row ) {
245 if ( ++
$count > $this->params
['limit'] ) {
246 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
247 // We need to keep the parent page of this redir in
248 if ( $this->hasNS
) {
249 $parentID = $this->pageMap
[$row-> { $this->bl_ns
} ][$row-> { $this->bl_title
} ];
251 $parentID = $this->pageMap
[NS_IMAGE
][$row-> { $this->bl_title
} ];
253 $this->continueStr
= $this->getContinueRedirStr( $parentID, $row->page_id
);
257 if ( is_null( $resultPageSet ) ) {
258 $this->extractRedirRowInfo( $row );
260 $resultPageSet->processDbRow( $row );
264 if ( is_null( $resultPageSet ) ) {
265 // Try to add the result data in one go and pray that it fits
266 $fit = $this->getResult()->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr
) );
268 // It didn't fit. Add elements one by one until the
270 foreach ( $this->resultArr
as $pageID => $arr ) {
271 // Add the basic entry without redirlinks first
272 $fit = $this->getResult()->addValue(
273 array( 'query', $this->getModuleName() ),
274 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
276 $this->continueStr
= $this->getContinueStr( $pageID );
281 foreach ( (array)@$arr['redirlinks'] as $key => $redir ) {
282 $fit = $this->getResult()->addValue(
283 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
286 $this->continueStr
= $this->getContinueRedirStr( $pageID, $redir['pageid'] );
292 $this->getResult()->setIndexedTagName_internal(
293 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
302 $this->getResult()->setIndexedTagName_internal(
303 array( 'query', $this->getModuleName() ),
307 if ( !is_null( $this->continueStr
) ) {
308 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
312 private function extractRowInfo( $row ) {
313 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
314 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
315 $a = array( 'pageid' => intval( $row->page_id
) );
316 ApiQueryBase
::addTitleInfo( $a, $t );
317 if ( $row->page_is_redirect
) {
319 $this->redirTitles
[] = $t;
321 // Put all the results in an array first
322 $this->resultArr
[$a['pageid']] = $a;
325 private function extractRedirRowInfo( $row ) {
326 $a['pageid'] = intval( $row->page_id
);
327 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
328 if ( $row->page_is_redirect
) {
331 $ns = $this->hasNS ?
$row-> { $this->bl_ns
} : NS_FILE
;
332 $parentID = $this->pageMap
[$ns][$row-> { $this->bl_title
} ];
333 // Put all the results in an array first
334 $this->resultArr
[$parentID]['redirlinks'][] = $a;
335 $this->getResult()->setIndexedTagName( $this->resultArr
[$parentID]['redirlinks'], $this->bl_code
);
338 protected function processContinue() {
339 if ( !is_null( $this->params
['continue'] ) ) {
340 $this->parseContinueParam();
342 if ( $this->params
['title'] !== '' ) {
343 $title = Title
::newFromText( $this->params
['title'] );
345 $this->dieUsageMsg( array( 'invalidtitle', $this->params
['title'] ) );
347 $this->rootTitle
= $title;
352 // only image titles are allowed for the root in imageinfo mode
353 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
354 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
358 protected function parseContinueParam() {
359 $continueList = explode( '|', $this->params
['continue'] );
361 // ns | key | id1 [| id2]
362 // ns+key: root title
363 // id1: first-level page ID to continue from
364 // id2: second-level page ID to continue from
366 // null stuff out now so we know what's set and what isn't
367 $this->rootTitle
= $this->contID
= $this->redirID
= null;
368 $rootNs = intval( $continueList[0] );
369 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
370 // Illegal continue parameter
371 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
373 $this->rootTitle
= Title
::makeTitleSafe( $rootNs, $continueList[1] );
375 if ( !$this->rootTitle
) {
376 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
378 $contID = intval( $continueList[2] );
380 if ( $contID === 0 && $continueList[2] !== '0' ) {
381 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
383 $this->contID
= $contID;
384 $redirID = intval( @$continueList[3] );
386 if ( $redirID === 0 && @$continueList[3] !== '0' ) {
387 // This one isn't required
390 $this->redirID
= $redirID;
394 protected function getContinueStr( $lastPageID ) {
395 return $this->rootTitle
->getNamespace() .
396 '|' . $this->rootTitle
->getDBkey() .
400 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
401 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
404 public function getAllowedParams() {
407 ApiBase
::PARAM_TYPE
=> 'string',
408 ApiBase
::PARAM_REQUIRED
=> true
411 'namespace' => array(
412 ApiBase
::PARAM_ISMULTI
=> true,
413 ApiBase
::PARAM_TYPE
=> 'namespace'
415 'filterredir' => array(
416 ApiBase
::PARAM_DFLT
=> 'all',
417 ApiBase
::PARAM_TYPE
=> array(
424 ApiBase
::PARAM_DFLT
=> 10,
425 ApiBase
::PARAM_TYPE
=> 'limit',
426 ApiBase
::PARAM_MIN
=> 1,
427 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
428 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
431 if ( $this->getModuleName() == 'embeddedin' ) {
434 $retval['redirect'] = false;
438 public function getParamDescription() {
440 'title' => 'Title to search',
441 'continue' => 'When more results are available, use this to continue',
442 'namespace' => 'The namespace to enumerate',
444 if ( $this->getModuleName() != 'embeddedin' ) {
445 return array_merge( $retval, array(
446 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
447 '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",
448 '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)."
451 return array_merge( $retval, array(
452 'filterredir' => 'How to filter for redirects',
453 'limit' => 'How many total pages to return'
457 public function getDescription() {
458 switch ( $this->getModuleName() ) {
460 return 'Find all pages that link to the given page';
462 return 'Find all pages that embed (transclude) the given title';
464 return 'Find all pages that use the given image title.';
466 ApiBase
::dieDebug( __METHOD__
, 'Unknown module name' );
470 public function getPossibleErrors() {
471 return array_merge( parent
::getPossibleErrors(), array(
472 array( 'invalidtitle', 'title' ),
473 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
474 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
478 protected function getExamples() {
479 static $examples = array(
480 'backlinks' => array(
481 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
482 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
484 'embeddedin' => array(
485 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
486 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
488 'imageusage' => array(
489 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
490 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
494 return $examples[$this->getModuleName()];
497 public function getVersion() {
498 return __CLASS__
. ': $Id$';