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
{
47 private $params, $contID, $redirID, $redirect;
48 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
51 * Maps ns and title to pageid
55 private $pageMap = array();
58 private $redirTitles = array();
59 private $continueStr = null;
61 // output element name, database column field prefix, database table
62 private $backlinksSettings = array(
66 'linktbl' => 'pagelinks'
68 'embeddedin' => array(
71 'linktbl' => 'templatelinks'
73 'imageusage' => array(
76 'linktbl' => 'imagelinks'
80 public function __construct( $query, $moduleName ) {
81 $settings = $this->backlinksSettings
[$moduleName];
82 $prefix = $settings['prefix'];
83 $code = $settings['code'];
84 $this->resultArr
= array();
86 parent
::__construct( $query, $moduleName, $code );
87 $this->bl_ns
= $prefix . '_namespace';
88 $this->bl_from
= $prefix . '_from';
89 $this->bl_table
= $settings['linktbl'];
90 $this->bl_code
= $code;
92 $this->hasNS
= $moduleName !== 'imageusage';
94 $this->bl_title
= $prefix . '_title';
95 $this->bl_sort
= "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
96 $this->bl_fields
= array(
101 $this->bl_title
= $prefix . '_to';
102 $this->bl_sort
= "{$this->bl_title}, {$this->bl_from}";
103 $this->bl_fields
= array(
109 public function execute() {
113 public function getCacheMode( $params ) {
117 public function executeGenerator( $resultPageSet ) {
118 $this->run( $resultPageSet );
122 * @param $resultPageSet ApiPageSet
125 private function prepareFirstQuery( $resultPageSet = null ) {
126 /* SELECT page_id, page_title, page_namespace, page_is_redirect
127 * FROM pagelinks, page WHERE pl_from=page_id
128 * AND pl_title='Foo' AND pl_namespace=0
129 * LIMIT 11 ORDER BY pl_from
131 $this->addTables( array( $this->bl_table
, 'page' ) );
132 $this->addWhere( "{$this->bl_from}=page_id" );
133 if ( is_null( $resultPageSet ) ) {
134 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
136 $this->addFields( $resultPageSet->getPageTableFields() );
139 $this->addFields( 'page_is_redirect' );
140 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
142 if ( $this->hasNS
) {
143 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
145 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
147 if ( !is_null( $this->contID
) ) {
148 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
151 if ( $this->params
['filterredir'] == 'redirects' ) {
152 $this->addWhereFld( 'page_is_redirect', 1 );
153 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
154 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
155 $this->addWhereFld( 'page_is_redirect', 0 );
158 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
159 $this->addOption( 'ORDER BY', $this->bl_from
);
160 $this->addOption( 'STRAIGHT_JOIN' );
164 * @param $resultPageSet ApiPageSet
167 private function prepareSecondQuery( $resultPageSet = null ) {
168 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
169 FROM pagelinks, page WHERE pl_from=page_id
170 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
171 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
173 $db = $this->getDB();
174 $this->addTables( array( 'page', $this->bl_table
) );
175 $this->addWhere( "{$this->bl_from}=page_id" );
177 if ( is_null( $resultPageSet ) ) {
178 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
180 $this->addFields( $resultPageSet->getPageTableFields() );
183 $this->addFields( $this->bl_title
);
184 if ( $this->hasNS
) {
185 $this->addFields( $this->bl_ns
);
188 // We can't use LinkBatch here because $this->hasNS may be false
189 $titleWhere = array();
190 foreach ( $this->redirTitles
as $t ) {
191 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
192 ( $this->hasNS ?
" AND {$this->bl_ns} = '{$t->getNamespace()}'" : '' );
194 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
195 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
197 if ( !is_null( $this->redirID
) ) {
198 $first = $this->redirTitles
[0];
199 $title = $db->strencode( $first->getDBkey() );
200 $ns = $first->getNamespace();
201 $from = $this->redirID
;
202 if ( $this->hasNS
) {
203 $this->addWhere( "{$this->bl_ns} > $ns OR " .
204 "({$this->bl_ns} = $ns AND " .
205 "({$this->bl_title} > '$title' OR " .
206 "({$this->bl_title} = '$title' AND " .
207 "{$this->bl_from} >= $from)))" );
209 $this->addWhere( "{$this->bl_title} > '$title' OR " .
210 "({$this->bl_title} = '$title' AND " .
211 "{$this->bl_from} >= $from)" );
214 if ( $this->params
['filterredir'] == 'redirects' ) {
215 $this->addWhereFld( 'page_is_redirect', 1 );
216 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
217 $this->addWhereFld( 'page_is_redirect', 0 );
220 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
221 $this->addOption( 'ORDER BY', $this->bl_sort
);
222 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
226 * @param $resultPageSet ApiPageSet
229 private function run( $resultPageSet = null ) {
230 $this->params
= $this->extractRequestParams( false );
231 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
232 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
233 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
234 if ( $this->params
['limit'] == 'max' ) {
235 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
236 $this->getResult()->setParsedLimit( $this->getModuleName(), $this->params
['limit'] );
239 $this->processContinue();
240 $this->prepareFirstQuery( $resultPageSet );
242 $res = $this->select( __METHOD__
. '::firstQuery' );
246 foreach ( $res as $row ) {
247 if ( ++
$count > $this->params
['limit'] ) {
248 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
249 // Continue string preserved in case the redirect query doesn't pass the limit
250 $this->continueStr
= $this->getContinueStr( $row->page_id
);
254 if ( is_null( $resultPageSet ) ) {
255 $this->extractRowInfo( $row );
257 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
258 if ( $row->page_is_redirect
) {
259 $this->redirTitles
[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
262 $resultPageSet->processDbRow( $row );
266 if ( $this->redirect
&& count( $this->redirTitles
) ) {
267 $this->resetQueryParams();
268 $this->prepareSecondQuery( $resultPageSet );
269 $res = $this->select( __METHOD__
. '::secondQuery' );
271 foreach ( $res as $row ) {
272 if ( ++
$count > $this->params
['limit'] ) {
273 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
274 // We need to keep the parent page of this redir in
275 if ( $this->hasNS
) {
276 $parentID = $this->pageMap
[$row-> { $this->bl_ns
} ][$row-> { $this->bl_title
} ];
278 $parentID = $this->pageMap
[NS_IMAGE
][$row-> { $this->bl_title
} ];
280 $this->continueStr
= $this->getContinueRedirStr( $parentID, $row->page_id
);
284 if ( is_null( $resultPageSet ) ) {
285 $this->extractRedirRowInfo( $row );
287 $resultPageSet->processDbRow( $row );
291 if ( is_null( $resultPageSet ) ) {
292 // Try to add the result data in one go and pray that it fits
293 $fit = $this->getResult()->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr
) );
295 // It didn't fit. Add elements one by one until the
297 foreach ( $this->resultArr
as $pageID => $arr ) {
298 // Add the basic entry without redirlinks first
299 $fit = $this->getResult()->addValue(
300 array( 'query', $this->getModuleName() ),
301 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
303 $this->continueStr
= $this->getContinueStr( $pageID );
308 foreach ( (array)@$arr['redirlinks'] as $key => $redir ) {
309 $fit = $this->getResult()->addValue(
310 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
313 $this->continueStr
= $this->getContinueRedirStr( $pageID, $redir['pageid'] );
319 $this->getResult()->setIndexedTagName_internal(
320 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
329 $this->getResult()->setIndexedTagName_internal(
330 array( 'query', $this->getModuleName() ),
334 if ( !is_null( $this->continueStr
) ) {
335 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
339 private function extractRowInfo( $row ) {
340 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
341 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
342 $a = array( 'pageid' => intval( $row->page_id
) );
343 ApiQueryBase
::addTitleInfo( $a, $t );
344 if ( $row->page_is_redirect
) {
346 $this->redirTitles
[] = $t;
348 // Put all the results in an array first
349 $this->resultArr
[$a['pageid']] = $a;
352 private function extractRedirRowInfo( $row ) {
353 $a['pageid'] = intval( $row->page_id
);
354 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
355 if ( $row->page_is_redirect
) {
358 $ns = $this->hasNS ?
$row-> { $this->bl_ns
} : NS_FILE
;
359 $parentID = $this->pageMap
[$ns][$row-> { $this->bl_title
} ];
360 // Put all the results in an array first
361 $this->resultArr
[$parentID]['redirlinks'][] = $a;
362 $this->getResult()->setIndexedTagName( $this->resultArr
[$parentID]['redirlinks'], $this->bl_code
);
365 protected function processContinue() {
366 if ( !is_null( $this->params
['continue'] ) ) {
367 $this->parseContinueParam();
369 if ( $this->params
['title'] !== '' ) {
370 $title = Title
::newFromText( $this->params
['title'] );
372 $this->dieUsageMsg( array( 'invalidtitle', $this->params
['title'] ) );
374 $this->rootTitle
= $title;
379 // only image titles are allowed for the root in imageinfo mode
380 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
381 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
385 protected function parseContinueParam() {
386 $continueList = explode( '|', $this->params
['continue'] );
388 // ns | key | id1 [| id2]
389 // ns+key: root title
390 // id1: first-level page ID to continue from
391 // id2: second-level page ID to continue from
393 // null stuff out now so we know what's set and what isn't
394 $this->rootTitle
= $this->contID
= $this->redirID
= null;
395 $rootNs = intval( $continueList[0] );
396 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
397 // Illegal continue parameter
398 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
400 $this->rootTitle
= Title
::makeTitleSafe( $rootNs, $continueList[1] );
402 if ( !$this->rootTitle
) {
403 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
405 $contID = intval( $continueList[2] );
407 if ( $contID === 0 && $continueList[2] !== '0' ) {
408 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
410 $this->contID
= $contID;
411 $redirID = intval( @$continueList[3] );
413 if ( $redirID === 0 && @$continueList[3] !== '0' ) {
414 // This one isn't required
417 $this->redirID
= $redirID;
421 protected function getContinueStr( $lastPageID ) {
422 return $this->rootTitle
->getNamespace() .
423 '|' . $this->rootTitle
->getDBkey() .
427 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
428 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
431 public function getAllowedParams() {
434 ApiBase
::PARAM_TYPE
=> 'string',
435 ApiBase
::PARAM_REQUIRED
=> true
438 'namespace' => array(
439 ApiBase
::PARAM_ISMULTI
=> true,
440 ApiBase
::PARAM_TYPE
=> 'namespace'
442 'filterredir' => array(
443 ApiBase
::PARAM_DFLT
=> 'all',
444 ApiBase
::PARAM_TYPE
=> array(
451 ApiBase
::PARAM_DFLT
=> 10,
452 ApiBase
::PARAM_TYPE
=> 'limit',
453 ApiBase
::PARAM_MIN
=> 1,
454 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
455 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
458 if ( $this->getModuleName() == 'embeddedin' ) {
461 $retval['redirect'] = false;
465 public function getParamDescription() {
467 'title' => 'Title to search',
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)."
478 return array_merge( $retval, array(
479 'filterredir' => 'How to filter for redirects',
480 'limit' => 'How many total pages to return'
484 public function getDescription() {
485 switch ( $this->getModuleName() ) {
487 return 'Find all pages that link to the given page';
489 return 'Find all pages that embed (transclude) the given title';
491 return 'Find all pages that use the given image title.';
493 ApiBase
::dieDebug( __METHOD__
, 'Unknown module name' );
497 public function getPossibleErrors() {
498 return array_merge( parent
::getPossibleErrors(), array(
499 array( 'invalidtitle', 'title' ),
500 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
501 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
505 protected function getExamples() {
506 static $examples = array(
507 'backlinks' => array(
508 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
509 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
511 'embeddedin' => array(
512 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
513 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
515 'imageusage' => array(
516 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
517 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
521 return $examples[$this->getModuleName()];
524 public function getVersion() {
525 return __CLASS__
. ': $Id$';