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
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
35 class ApiQueryBacklinks
extends ApiQueryGeneratorBase
{
42 private $params, $contID, $redirID, $redirect;
43 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_fields, $hasNS;
46 * Maps ns and title to pageid
50 private $pageMap = array();
53 private $redirTitles = array();
54 private $continueStr = null;
56 // output element name, database column field prefix, database table
57 private $backlinksSettings = array(
61 'linktbl' => 'pagelinks',
62 'helpurl' => 'https://www.mediawiki.org/wiki/API:Backlinks',
64 'embeddedin' => array(
67 'linktbl' => 'templatelinks',
68 'helpurl' => 'https://www.mediawiki.org/wiki/API:Embeddedin',
70 'imageusage' => array(
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';
93 $this->bl_title
= $prefix . '_title';
94 $this->bl_fields
= array(
99 $this->bl_title
= $prefix . '_to';
100 $this->bl_fields
= array(
106 public function execute() {
110 public function getCacheMode( $params ) {
114 public function executeGenerator( $resultPageSet ) {
115 $this->run( $resultPageSet );
119 * @param $resultPageSet ApiPageSet
122 private function prepareFirstQuery( $resultPageSet = null ) {
123 /* SELECT page_id, page_title, page_namespace, page_is_redirect
124 * FROM pagelinks, page WHERE pl_from=page_id
125 * AND pl_title='Foo' AND pl_namespace=0
126 * LIMIT 11 ORDER BY pl_from
128 $this->addTables( array( $this->bl_table
, 'page' ) );
129 $this->addWhere( "{$this->bl_from}=page_id" );
130 if ( is_null( $resultPageSet ) ) {
131 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
133 $this->addFields( $resultPageSet->getPageTableFields() );
136 $this->addFields( 'page_is_redirect' );
137 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
139 if ( $this->hasNS
) {
140 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
142 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
144 if ( !is_null( $this->contID
) ) {
145 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
146 $this->addWhere( "{$this->bl_from}$op={$this->contID}" );
149 if ( $this->params
['filterredir'] == 'redirects' ) {
150 $this->addWhereFld( 'page_is_redirect', 1 );
151 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
152 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
153 $this->addWhereFld( 'page_is_redirect', 0 );
156 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
157 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
158 $this->addOption( 'ORDER BY', $this->bl_from
. $sort );
159 $this->addOption( 'STRAIGHT_JOIN' );
163 * @param $resultPageSet ApiPageSet
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' ) );
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 $allRedirNs = array();
190 $allRedirDBkey = array();
191 foreach ( $this->redirTitles
as $t ) {
192 $redirNs = $t->getNamespace();
193 $redirDBkey = $t->getDBkey();
194 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $redirDBkey ) .
195 ( $this->hasNS ?
" AND {$this->bl_ns} = {$redirNs}" : '' );
196 $allRedirNs[] = $redirNs;
197 $allRedirDBkey[] = $redirDBkey;
199 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
200 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
202 if ( !is_null( $this->redirID
) ) {
203 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
204 $first = $this->redirTitles
[0];
205 $title = $db->addQuotes( $first->getDBkey() );
206 $ns = $first->getNamespace();
207 $from = $this->redirID
;
208 if ( $this->hasNS
) {
209 $this->addWhere( "{$this->bl_ns} $op $ns OR " .
210 "({$this->bl_ns} = $ns AND " .
211 "({$this->bl_title} $op $title OR " .
212 "({$this->bl_title} = $title AND " .
213 "{$this->bl_from} $op= $from)))" );
215 $this->addWhere( "{$this->bl_title} $op $title OR " .
216 "({$this->bl_title} = $title AND " .
217 "{$this->bl_from} $op= $from)" );
220 if ( $this->params
['filterredir'] == 'redirects' ) {
221 $this->addWhereFld( 'page_is_redirect', 1 );
222 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
223 $this->addWhereFld( 'page_is_redirect', 0 );
226 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
228 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
229 // Don't order by namespace/title if it's constant in the WHERE clause
230 if( $this->hasNS
&& count( array_unique( $allRedirNs ) ) != 1 ) {
231 $orderBy[] = $this->bl_ns
. $sort;
233 if( count( array_unique( $allRedirDBkey ) ) != 1 ) {
234 $orderBy[] = $this->bl_title
. $sort;
236 $orderBy[] = $this->bl_from
. $sort;
237 $this->addOption( 'ORDER BY', $orderBy );
238 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
242 * @param $resultPageSet ApiPageSet
245 private function run( $resultPageSet = null ) {
246 $this->params
= $this->extractRequestParams( false );
247 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
248 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
249 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
251 $result = $this->getResult();
253 if ( $this->params
['limit'] == 'max' ) {
254 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
255 $result->setParsedLimit( $this->getModuleName(), $this->params
['limit'] );
258 $this->processContinue();
259 $this->prepareFirstQuery( $resultPageSet );
261 $res = $this->select( __METHOD__
. '::firstQuery' );
265 foreach ( $res as $row ) {
266 if ( ++
$count > $this->params
['limit'] ) {
267 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
268 // Continue string preserved in case the redirect query doesn't pass the limit
269 $this->continueStr
= $this->getContinueStr( $row->page_id
);
273 if ( is_null( $resultPageSet ) ) {
274 $this->extractRowInfo( $row );
276 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
277 if ( $row->page_is_redirect
) {
278 $this->redirTitles
[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
281 $resultPageSet->processDbRow( $row );
285 if ( $this->redirect
&& count( $this->redirTitles
) ) {
286 $this->resetQueryParams();
287 $this->prepareSecondQuery( $resultPageSet );
288 $res = $this->select( __METHOD__
. '::secondQuery' );
290 foreach ( $res as $row ) {
291 if ( ++
$count > $this->params
['limit'] ) {
292 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
293 // We need to keep the parent page of this redir in
294 if ( $this->hasNS
) {
295 $parentID = $this->pageMap
[$row-> { $this->bl_ns
} ][$row-> { $this->bl_title
} ];
297 $parentID = $this->pageMap
[NS_FILE
][$row-> { $this->bl_title
} ];
299 $this->continueStr
= $this->getContinueRedirStr( $parentID, $row->page_id
);
303 if ( is_null( $resultPageSet ) ) {
304 $this->extractRedirRowInfo( $row );
306 $resultPageSet->processDbRow( $row );
310 if ( is_null( $resultPageSet ) ) {
311 // Try to add the result data in one go and pray that it fits
312 $fit = $result->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr
) );
314 // It didn't fit. Add elements one by one until the
316 foreach ( $this->resultArr
as $pageID => $arr ) {
317 // Add the basic entry without redirlinks first
318 $fit = $result->addValue(
319 array( 'query', $this->getModuleName() ),
320 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
322 $this->continueStr
= $this->getContinueStr( $pageID );
327 $redirLinks = isset( $arr['redirlinks'] ) ?
$arr['redirlinks'] : array();
328 foreach ( (array)$redirLinks as $key => $redir ) {
329 $fit = $result->addValue(
330 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
333 $this->continueStr
= $this->getContinueRedirStr( $pageID, $redir['pageid'] );
339 $result->setIndexedTagName_internal(
340 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
349 $result->setIndexedTagName_internal(
350 array( 'query', $this->getModuleName() ),
354 if ( !is_null( $this->continueStr
) ) {
355 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
359 private function extractRowInfo( $row ) {
360 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
361 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
362 $a = array( 'pageid' => intval( $row->page_id
) );
363 ApiQueryBase
::addTitleInfo( $a, $t );
364 if ( $row->page_is_redirect
) {
366 $this->redirTitles
[] = $t;
368 // Put all the results in an array first
369 $this->resultArr
[$a['pageid']] = $a;
372 private function extractRedirRowInfo( $row ) {
373 $a['pageid'] = intval( $row->page_id
);
374 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
375 if ( $row->page_is_redirect
) {
378 $ns = $this->hasNS ?
$row-> { $this->bl_ns
} : NS_FILE
;
379 $parentID = $this->pageMap
[$ns][$row-> { $this->bl_title
} ];
380 // Put all the results in an array first
381 $this->resultArr
[$parentID]['redirlinks'][] = $a;
382 $this->getResult()->setIndexedTagName( $this->resultArr
[$parentID]['redirlinks'], $this->bl_code
);
385 protected function processContinue() {
386 if ( !is_null( $this->params
['continue'] ) ) {
387 $this->parseContinueParam();
389 $this->rootTitle
= $this->getTitleOrPageId( $this->params
)->getTitle();
392 // only image titles are allowed for the root in imageinfo mode
393 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
394 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
398 protected function parseContinueParam() {
399 $continueList = explode( '|', $this->params
['continue'] );
401 // ns | key | id1 [| id2]
402 // ns+key: root title
403 // id1: first-level page ID to continue from
404 // id2: second-level page ID to continue from
406 // null stuff out now so we know what's set and what isn't
407 $this->rootTitle
= $this->contID
= $this->redirID
= null;
408 $rootNs = intval( $continueList[0] );
409 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
410 // Illegal continue parameter
411 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
413 $this->rootTitle
= Title
::makeTitleSafe( $rootNs, $continueList[1] );
415 if ( !$this->rootTitle
) {
416 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
418 $contID = intval( $continueList[2] );
420 if ( $contID === 0 && $continueList[2] !== '0' ) {
421 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
423 $this->contID
= $contID;
424 $id2 = isset( $continueList[3] ) ?
$continueList[3] : null;
425 $redirID = intval( $id2 );
427 if ( $redirID === 0 && $id2 !== '0' ) {
428 // This one isn't required
431 $this->redirID
= $redirID;
435 protected function getContinueStr( $lastPageID ) {
436 return $this->rootTitle
->getNamespace() .
437 '|' . $this->rootTitle
->getDBkey() .
441 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
442 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
445 public function getAllowedParams() {
448 ApiBase
::PARAM_TYPE
=> 'string',
451 ApiBase
::PARAM_TYPE
=> 'integer',
454 'namespace' => array(
455 ApiBase
::PARAM_ISMULTI
=> true,
456 ApiBase
::PARAM_TYPE
=> 'namespace'
459 ApiBase
::PARAM_DFLT
=> 'ascending',
460 ApiBase
::PARAM_TYPE
=> array(
465 'filterredir' => array(
466 ApiBase
::PARAM_DFLT
=> 'all',
467 ApiBase
::PARAM_TYPE
=> array(
474 ApiBase
::PARAM_DFLT
=> 10,
475 ApiBase
::PARAM_TYPE
=> 'limit',
476 ApiBase
::PARAM_MIN
=> 1,
477 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
478 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
481 if ( $this->getModuleName() == 'embeddedin' ) {
484 $retval['redirect'] = false;
488 public function getParamDescription() {
490 'title' => "Title to search. Cannot be used together with {$this->bl_code}pageid",
491 'pageid' => "Pageid to search. Cannot be used together with {$this->bl_code}title",
492 'continue' => 'When more results are available, use this to continue',
493 'namespace' => 'The namespace to enumerate',
494 'dir' => 'The direction in which to list',
496 if ( $this->getModuleName() != 'embeddedin' ) {
497 return array_merge( $retval, array(
498 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
499 '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",
500 '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)."
503 return array_merge( $retval, array(
504 'filterredir' => 'How to filter for redirects',
505 'limit' => 'How many total pages to return'
509 public function getResultProperties() {
512 'pageid' => 'integer',
515 'redirect' => 'boolean'
520 public function getDescription() {
521 switch ( $this->getModuleName() ) {
523 return 'Find all pages that link to the given page';
525 return 'Find all pages that embed (transclude) the given title';
527 return 'Find all pages that use the given image title.';
529 ApiBase
::dieDebug( __METHOD__
, 'Unknown module name' );
533 public function getPossibleErrors() {
534 return array_merge( parent
::getPossibleErrors(),
535 $this->getTitleOrPageIdErrorMessage(),
537 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
538 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
543 public function getExamples() {
544 static $examples = array(
545 'backlinks' => array(
546 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
547 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
549 'embeddedin' => array(
550 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
551 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
553 'imageusage' => array(
554 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
555 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
559 return $examples[$this->getModuleName()];
562 public function getHelpUrls() {
563 return $this->helpUrl
;
566 public function getVersion() {
567 return __CLASS__
. ': $Id$';