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 $settings = $this->backlinksSettings
[$moduleName];
67 $prefix = $settings['prefix'];
68 $code = $settings['code'];
69 $this->resultArr
= array();
71 parent
::__construct( $query, $moduleName, $code );
72 $this->bl_ns
= $prefix . '_namespace';
73 $this->bl_from
= $prefix . '_from';
74 $this->bl_table
= $settings['linktbl'];
75 $this->bl_code
= $code;
77 $this->hasNS
= $moduleName !== 'imageusage';
79 $this->bl_title
= $prefix . '_title';
80 $this->bl_sort
= "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
81 $this->bl_fields
= array(
86 $this->bl_title
= $prefix . '_to';
87 $this->bl_sort
= "{$this->bl_title}, {$this->bl_from}";
88 $this->bl_fields
= array(
94 public function execute() {
98 public function getCacheMode( $params ) {
102 public function executeGenerator( $resultPageSet ) {
103 $this->run( $resultPageSet );
106 private function prepareFirstQuery( $resultPageSet = null ) {
107 /* SELECT page_id, page_title, page_namespace, page_is_redirect
108 * FROM pagelinks, page WHERE pl_from=page_id
109 * AND pl_title='Foo' AND pl_namespace=0
110 * LIMIT 11 ORDER BY pl_from
112 $this->addTables( array( $this->bl_table
, 'page' ) );
113 $this->addWhere( "{$this->bl_from}=page_id" );
114 if ( is_null( $resultPageSet ) ) {
115 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
117 $this->addFields( $resultPageSet->getPageTableFields() );
120 $this->addFields( 'page_is_redirect' );
121 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
123 if ( $this->hasNS
) {
124 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
126 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
128 if ( !is_null( $this->contID
) ) {
129 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
132 if ( $this->params
['filterredir'] == 'redirects' ) {
133 $this->addWhereFld( 'page_is_redirect', 1 );
134 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
135 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
136 $this->addWhereFld( 'page_is_redirect', 0 );
139 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
140 $this->addOption( 'ORDER BY', $this->bl_from
);
141 $this->addOption( 'STRAIGHT_JOIN' );
144 private function prepareSecondQuery( $resultPageSet = null ) {
145 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
146 FROM pagelinks, page WHERE pl_from=page_id
147 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
148 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
150 $db = $this->getDB();
151 $this->addTables( array( 'page', $this->bl_table
) );
152 $this->addWhere( "{$this->bl_from}=page_id" );
154 if ( is_null( $resultPageSet ) ) {
155 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
157 $this->addFields( $resultPageSet->getPageTableFields() );
160 $this->addFields( $this->bl_title
);
161 if ( $this->hasNS
) {
162 $this->addFields( $this->bl_ns
);
165 // We can't use LinkBatch here because $this->hasNS may be false
166 $titleWhere = array();
167 foreach ( $this->redirTitles
as $t ) {
168 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
169 ( $this->hasNS ?
" AND {$this->bl_ns} = '{$t->getNamespace()}'" : '' );
171 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
172 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
174 if ( !is_null( $this->redirID
) ) {
175 $first = $this->redirTitles
[0];
176 $title = $db->strencode( $first->getDBkey() );
177 $ns = $first->getNamespace();
178 $from = $this->redirID
;
179 if ( $this->hasNS
) {
180 $this->addWhere( "{$this->bl_ns} > $ns OR " .
181 "({$this->bl_ns} = $ns AND " .
182 "({$this->bl_title} > '$title' OR " .
183 "({$this->bl_title} = '$title' AND " .
184 "{$this->bl_from} >= $from)))" );
186 $this->addWhere( "{$this->bl_title} > '$title' OR " .
187 "({$this->bl_title} = '$title' AND " .
188 "{$this->bl_from} >= $from)" );
191 if ( $this->params
['filterredir'] == 'redirects' ) {
192 $this->addWhereFld( 'page_is_redirect', 1 );
193 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
194 $this->addWhereFld( 'page_is_redirect', 0 );
197 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
198 $this->addOption( 'ORDER BY', $this->bl_sort
);
199 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
202 private function run( $resultPageSet = null ) {
203 $this->params
= $this->extractRequestParams( false );
204 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
205 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
206 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
207 if ( $this->params
['limit'] == 'max' ) {
208 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
209 $this->getResult()->setParsedLimit( $this->getModuleName(), $this->params
['limit'] );
212 $this->processContinue();
213 $this->prepareFirstQuery( $resultPageSet );
215 $res = $this->select( __METHOD__
. '::firstQuery' );
218 $this->pageMap
= array(); // Maps ns and title to pageid
219 $this->continueStr
= null;
220 $this->redirTitles
= array();
221 foreach ( $res as $row ) {
222 if ( ++
$count > $this->params
['limit'] ) {
223 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
224 // Continue string preserved in case the redirect query doesn't pass the limit
225 $this->continueStr
= $this->getContinueStr( $row->page_id
);
229 if ( is_null( $resultPageSet ) ) {
230 $this->extractRowInfo( $row );
232 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
233 if ( $row->page_is_redirect
) {
234 $this->redirTitles
[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
237 $resultPageSet->processDbRow( $row );
241 if ( $this->redirect
&& count( $this->redirTitles
) ) {
242 $this->resetQueryParams();
243 $this->prepareSecondQuery( $resultPageSet );
244 $res = $this->select( __METHOD__
. '::secondQuery' );
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 // We need to keep the parent page of this redir in
250 if ( $this->hasNS
) {
251 $parentID = $this->pageMap
[$row-> { $this->bl_ns
} ][$row-> { $this->bl_title
} ];
253 $parentID = $this->pageMap
[NS_IMAGE
][$row-> { $this->bl_title
} ];
255 $this->continueStr
= $this->getContinueRedirStr( $parentID, $row->page_id
);
259 if ( is_null( $resultPageSet ) ) {
260 $this->extractRedirRowInfo( $row );
262 $resultPageSet->processDbRow( $row );
266 if ( is_null( $resultPageSet ) ) {
267 // Try to add the result data in one go and pray that it fits
268 $fit = $this->getResult()->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr
) );
270 // It didn't fit. Add elements one by one until the
272 foreach ( $this->resultArr
as $pageID => $arr ) {
273 // Add the basic entry without redirlinks first
274 $fit = $this->getResult()->addValue(
275 array( 'query', $this->getModuleName() ),
276 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
278 $this->continueStr
= $this->getContinueStr( $pageID );
283 foreach ( (array)@$arr['redirlinks'] as $key => $redir ) {
284 $fit = $this->getResult()->addValue(
285 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
288 $this->continueStr
= $this->getContinueRedirStr( $pageID, $redir['pageid'] );
294 $this->getResult()->setIndexedTagName_internal(
295 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
304 $this->getResult()->setIndexedTagName_internal(
305 array( 'query', $this->getModuleName() ),
309 if ( !is_null( $this->continueStr
) ) {
310 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
314 private function extractRowInfo( $row ) {
315 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
316 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
317 $a = array( 'pageid' => intval( $row->page_id
) );
318 ApiQueryBase
::addTitleInfo( $a, $t );
319 if ( $row->page_is_redirect
) {
321 $this->redirTitles
[] = $t;
323 // Put all the results in an array first
324 $this->resultArr
[$a['pageid']] = $a;
327 private function extractRedirRowInfo( $row ) {
328 $a['pageid'] = intval( $row->page_id
);
329 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
330 if ( $row->page_is_redirect
) {
333 $ns = $this->hasNS ?
$row-> { $this->bl_ns
} : NS_FILE
;
334 $parentID = $this->pageMap
[$ns][$row-> { $this->bl_title
} ];
335 // Put all the results in an array first
336 $this->resultArr
[$parentID]['redirlinks'][] = $a;
337 $this->getResult()->setIndexedTagName( $this->resultArr
[$parentID]['redirlinks'], $this->bl_code
);
340 protected function processContinue() {
341 if ( !is_null( $this->params
['continue'] ) ) {
342 $this->parseContinueParam();
344 if ( $this->params
['title'] !== '' ) {
345 $title = Title
::newFromText( $this->params
['title'] );
347 $this->dieUsageMsg( array( 'invalidtitle', $this->params
['title'] ) );
349 $this->rootTitle
= $title;
354 // only image titles are allowed for the root in imageinfo mode
355 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
356 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
360 protected function parseContinueParam() {
361 $continueList = explode( '|', $this->params
['continue'] );
363 // ns | key | id1 [| id2]
364 // ns+key: root title
365 // id1: first-level page ID to continue from
366 // id2: second-level page ID to continue from
368 // null stuff out now so we know what's set and what isn't
369 $this->rootTitle
= $this->contID
= $this->redirID
= null;
370 $rootNs = intval( $continueList[0] );
371 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
372 // Illegal continue parameter
373 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
375 $this->rootTitle
= Title
::makeTitleSafe( $rootNs, $continueList[1] );
377 if ( !$this->rootTitle
) {
378 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
380 $contID = intval( $continueList[2] );
382 if ( $contID === 0 && $continueList[2] !== '0' ) {
383 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
385 $this->contID
= $contID;
386 $redirID = intval( @$continueList[3] );
388 if ( $redirID === 0 && @$continueList[3] !== '0' ) {
389 // This one isn't required
392 $this->redirID
= $redirID;
396 protected function getContinueStr( $lastPageID ) {
397 return $this->rootTitle
->getNamespace() .
398 '|' . $this->rootTitle
->getDBkey() .
402 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
403 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
406 public function getAllowedParams() {
409 ApiBase
::PARAM_TYPE
=> 'string',
410 ApiBase
::PARAM_REQUIRED
=> true
413 'namespace' => array(
414 ApiBase
::PARAM_ISMULTI
=> true,
415 ApiBase
::PARAM_TYPE
=> 'namespace'
417 'filterredir' => array(
418 ApiBase
::PARAM_DFLT
=> 'all',
419 ApiBase
::PARAM_TYPE
=> array(
426 ApiBase
::PARAM_DFLT
=> 10,
427 ApiBase
::PARAM_TYPE
=> 'limit',
428 ApiBase
::PARAM_MIN
=> 1,
429 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
430 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
433 if ( $this->getModuleName() == 'embeddedin' ) {
436 $retval['redirect'] = false;
440 public function getParamDescription() {
442 'title' => 'Title to search',
443 'continue' => 'When more results are available, use this to continue',
444 'namespace' => 'The namespace to enumerate',
446 if ( $this->getModuleName() != 'embeddedin' ) {
447 return array_merge( $retval, array(
448 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
449 '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",
450 '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)."
453 return array_merge( $retval, array(
454 'filterredir' => 'How to filter for redirects',
455 'limit' => 'How many total pages to return'
459 public function getDescription() {
460 switch ( $this->getModuleName() ) {
462 return 'Find all pages that link to the given page';
464 return 'Find all pages that embed (transclude) the given title';
466 return 'Find all pages that use the given image title.';
468 ApiBase
::dieDebug( __METHOD__
, 'Unknown module name' );
472 public function getPossibleErrors() {
473 return array_merge( parent
::getPossibleErrors(), array(
474 array( 'invalidtitle', 'title' ),
475 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
476 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
480 protected function getExamples() {
481 static $examples = array(
482 'backlinks' => array(
483 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
484 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
486 'embeddedin' => array(
487 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
488 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
490 'imageusage' => array(
491 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
492 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
496 return $examples[$this->getModuleName()];
499 public function getVersion() {
500 return __CLASS__
. ': $Id$';