4 * Created on Oct 16, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once ( "ApiQueryBase.php" );
32 * This is a three-in-one module to query:
33 * * backlinks - links pointing to the given page,
34 * * embeddedin - what pages transclude the given page within themselves,
35 * * imageusage - what pages use the given image
39 class ApiQueryBacklinks
extends ApiQueryGeneratorBase
{
41 private $params, $rootTitle, $contRedirs, $contLevel, $contTitle, $contID, $redirID, $redirect;
42 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
43 private $pageMap, $resultArr;
45 // output element name, database column field prefix, database table
46 private $backlinksSettings = array (
47 'backlinks' => array (
50 'linktbl' => 'pagelinks'
52 'embeddedin' => array (
55 'linktbl' => 'templatelinks'
57 'imageusage' => array (
60 'linktbl' => 'imagelinks'
64 public function __construct( $query, $moduleName ) {
65 extract( $this->backlinksSettings
[$moduleName] );
66 $this->resultArr
= array();
68 parent
:: __construct( $query, $moduleName, $code );
69 $this->bl_ns
= $prefix . '_namespace';
70 $this->bl_from
= $prefix . '_from';
71 $this->bl_table
= $linktbl;
72 $this->bl_code
= $code;
74 $this->hasNS
= $moduleName !== 'imageusage';
76 $this->bl_title
= $prefix . '_title';
77 $this->bl_sort
= "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
78 $this->bl_fields
= array (
83 $this->bl_title
= $prefix . '_to';
84 $this->bl_sort
= "{$this->bl_title}, {$this->bl_from}";
85 $this->bl_fields
= array (
91 public function execute() {
95 public function executeGenerator( $resultPageSet ) {
96 $this->run( $resultPageSet );
99 private function prepareFirstQuery( $resultPageSet = null ) {
100 /* SELECT page_id, page_title, page_namespace, page_is_redirect
101 * FROM pagelinks, page WHERE pl_from=page_id
102 * AND pl_title='Foo' AND pl_namespace=0
103 * LIMIT 11 ORDER BY pl_from
105 $db = $this->getDB();
106 $this->addTables( array( $this->bl_table
, 'page' ) );
107 $this->addWhere( "{$this->bl_from}=page_id" );
108 if ( is_null( $resultPageSet ) )
109 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
111 $this->addFields( $resultPageSet->getPageTableFields() );
112 $this->addFields( 'page_is_redirect' );
113 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
115 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
116 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
117 if ( !is_null( $this->contID
) )
118 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
120 if ( $this->params
['filterredir'] == 'redirects' )
121 $this->addWhereFld( 'page_is_redirect', 1 );
122 else if ( $this->params
['filterredir'] == 'nonredirects' )
123 $this->addWhereFld( 'page_is_redirect', 0 );
125 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
126 $this->addOption( 'ORDER BY', $this->bl_from
);
127 $this->addOption( 'STRAIGHT_JOIN' );
130 private function prepareSecondQuery( $resultPageSet = null ) {
131 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
132 FROM pagelinks, page WHERE pl_from=page_id
133 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
134 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
136 $db = $this->getDB();
137 $this->addTables( array( 'page', $this->bl_table
) );
138 $this->addWhere( "{$this->bl_from}=page_id" );
139 if ( is_null( $resultPageSet ) )
140 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
142 $this->addFields( $resultPageSet->getPageTableFields() );
143 $this->addFields( $this->bl_title
);
145 $this->addFields( $this->bl_ns
);
146 // We can't use LinkBatch here because $this->hasNS may be false
147 $titleWhere = array();
148 foreach ( $this->redirTitles
as $t )
149 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
150 ( $this->hasNS ?
" AND {$this->bl_ns} = '{$t->getNamespace()}'" : "" );
151 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
152 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
153 if ( !is_null( $this->redirID
) )
155 $first = $this->redirTitles
[0];
156 $title = $db->strencode( $first->getDBkey() );
157 $ns = $first->getNamespace();
158 $from = $this->redirID
;
160 $this->addWhere( "{$this->bl_ns} > $ns OR " .
161 "({$this->bl_ns} = $ns AND " .
162 "({$this->bl_title} > '$title' OR " .
163 "({$this->bl_title} = '$title' AND " .
164 "{$this->bl_from} >= $from)))" );
166 $this->addWhere( "{$this->bl_title} > '$title' OR " .
167 "({$this->bl_title} = '$title' AND " .
168 "{$this->bl_from} >= $from)" );
171 if ( $this->params
['filterredir'] == 'redirects' )
172 $this->addWhereFld( 'page_is_redirect', 1 );
173 else if ( $this->params
['filterredir'] == 'nonredirects' )
174 $this->addWhereFld( 'page_is_redirect', 0 );
175 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
176 $this->addOption( 'ORDER BY', $this->bl_sort
);
177 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
180 private function run( $resultPageSet = null ) {
181 $this->params
= $this->extractRequestParams( false );
182 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
183 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
184 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
185 if ( $this->params
['limit'] == 'max' ) {
186 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
187 $this->getResult()->addValue( 'limits', $this->getModuleName(), $this->params
['limit'] );
190 $this->processContinue();
191 $this->prepareFirstQuery( $resultPageSet );
193 $db = $this->getDB();
194 $res = $this->select( __METHOD__
. '::firstQuery' );
197 $this->pageMap
= array(); // Maps ns and title to pageid
198 $this->continueStr
= null;
199 $this->redirTitles
= array();
200 while ( $row = $db->fetchObject( $res ) ) {
201 if ( ++
$count > $this->params
['limit'] ) {
202 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
203 // Continue string preserved in case the redirect query doesn't pass the limit
204 $this->continueStr
= $this->getContinueStr( $row->page_id
);
208 if ( is_null( $resultPageSet ) )
209 $this->extractRowInfo( $row );
212 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
213 if ( $row->page_is_redirect
)
214 $this->redirTitles
[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
215 $resultPageSet->processDbRow( $row );
218 $db->freeResult( $res );
220 if ( $this->redirect
&& count( $this->redirTitles
) )
222 $this->resetQueryParams();
223 $this->prepareSecondQuery( $resultPageSet );
224 $res = $this->select( __METHOD__
. '::secondQuery' );
226 while ( $row = $db->fetchObject( $res ) )
228 if ( ++
$count > $this->params
['limit'] )
230 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
231 // We need to keep the parent page of this redir in
233 $parentID = $this->pageMap
[$row-> { $this->bl_ns
} ][$row-> { $this->bl_title
} ];
235 $parentID = $this->pageMap
[NS_IMAGE
][$row-> { $this->bl_title
} ];
236 $this->continueStr
= $this->getContinueRedirStr( $parentID, $row->page_id
);
240 if ( is_null( $resultPageSet ) )
241 $this->extractRedirRowInfo( $row );
243 $resultPageSet->processDbRow( $row );
245 $db->freeResult( $res );
247 if ( is_null( $resultPageSet ) ) {
248 // Try to add the result data in one go and pray that it fits
249 $fit = $this->getResult()->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr
) );
252 // It didn't fit. Add elements one by one until the
254 foreach ( $this->resultArr
as $pageID => $arr )
256 // Add the basic entry without redirlinks first
257 $fit = $this->getResult()->addValue(
258 array( 'query', $this->getModuleName() ),
259 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
262 $this->continueStr
= $this->getContinueStr( $pageID );
267 foreach ( (array)@$arr['redirlinks'] as $key => $redir )
269 $fit = $this->getResult()->addValue(
270 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
274 $this->continueStr
= $this->getContinueRedirStr( $pageID, $redir['pageid'] );
280 $this->getResult()->setIndexedTagName_internal(
281 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
288 $this->getResult()->setIndexedTagName_internal(
289 array( 'query', $this->getModuleName() ),
292 if ( !is_null( $this->continueStr
) )
293 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
296 private function extractRowInfo( $row ) {
297 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
298 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
299 $a = array( 'pageid' => intval( $row->page_id
) );
300 ApiQueryBase
::addTitleInfo( $a, $t );
301 if ( $row->page_is_redirect
)
304 $this->redirTitles
[] = $t;
306 // Put all the results in an array first
307 $this->resultArr
[$a['pageid']] = $a;
310 private function extractRedirRowInfo( $row )
312 $a['pageid'] = intval( $row->page_id
);
313 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
314 if ( $row->page_is_redirect
)
316 $ns = $this->hasNS ?
$row-> { $this->bl_ns
} : NS_FILE
;
317 $parentID = $this->pageMap
[$ns][$row-> { $this->bl_title
} ];
318 // Put all the results in an array first
319 $this->resultArr
[$parentID]['redirlinks'][] = $a;
320 $this->getResult()->setIndexedTagName( $this->resultArr
[$parentID]['redirlinks'], $this->bl_code
);
323 protected function processContinue() {
324 if ( !is_null( $this->params
['continue'] ) )
325 $this->parseContinueParam();
327 if ( $this->params
['title'] !== "" ) {
328 $title = Title
::newFromText( $this->params
['title'] );
330 $this->dieUsageMsg( array( 'invalidtitle', $this->params
['title'] ) );
332 $this->rootTitle
= $title;
335 $this->dieUsageMsg( array( 'missingparam', 'title' ) );
339 // only image titles are allowed for the root in imageinfo mode
340 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
)
341 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
344 protected function parseContinueParam() {
345 $continueList = explode( '|', $this->params
['continue'] );
347 // ns | key | id1 [| id2]
348 // ns+key: root title
349 // id1: first-level page ID to continue from
350 // id2: second-level page ID to continue from
352 // null stuff out now so we know what's set and what isn't
353 $this->rootTitle
= $this->contID
= $this->redirID
= null;
354 $rootNs = intval( $continueList[0] );
355 if ( $rootNs === 0 && $continueList[0] !== '0' )
356 // Illegal continue parameter
357 $this->dieUsage( "Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue" );
358 $this->rootTitle
= Title
::makeTitleSafe( $rootNs, $continueList[1] );
359 if ( !$this->rootTitle
)
360 $this->dieUsage( "Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue" );
361 $contID = intval( $continueList[2] );
362 if ( $contID === 0 && $continueList[2] !== '0' )
363 $this->dieUsage( "Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue" );
364 $this->contID
= $contID;
365 $redirID = intval( @$continueList[3] );
366 if ( $redirID === 0 && @$continueList[3] !== '0' )
367 // This one isn't required
369 $this->redirID
= $redirID;
373 protected function getContinueStr( $lastPageID ) {
374 return $this->rootTitle
->getNamespace() .
375 '|' . $this->rootTitle
->getDBkey() .
379 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
380 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
383 public function getAllowedParams() {
387 'namespace' => array (
388 ApiBase
:: PARAM_ISMULTI
=> true,
389 ApiBase
:: PARAM_TYPE
=> 'namespace'
391 'filterredir' => array(
392 ApiBase
:: PARAM_DFLT
=> 'all',
393 ApiBase
:: PARAM_TYPE
=> array(
400 ApiBase
:: PARAM_DFLT
=> 10,
401 ApiBase
:: PARAM_TYPE
=> 'limit',
402 ApiBase
:: PARAM_MIN
=> 1,
403 ApiBase
:: PARAM_MAX
=> ApiBase
:: LIMIT_BIG1
,
404 ApiBase
:: PARAM_MAX2
=> ApiBase
:: LIMIT_BIG2
407 if ( $this->getModuleName() == 'embeddedin' )
409 $retval['redirect'] = false;
413 public function getParamDescription() {
415 'title' => 'Title to search.',
416 'continue' => 'When more results are available, use this to continue.',
417 'namespace' => 'The namespace to enumerate.',
418 'filterredir' => 'How to filter for redirects'
420 if ( $this->getModuleName() != 'embeddedin' )
421 return array_merge( $retval, array(
422 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
423 '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)."
425 return array_merge( $retval, array(
426 'limit' => "How many total pages to return."
430 public function getDescription() {
431 switch ( $this->getModuleName() ) {
433 return 'Find all pages that link to the given page';
435 return 'Find all pages that embed (transclude) the given title';
437 return 'Find all pages that use the given image title.';
439 ApiBase
:: dieDebug( __METHOD__
, 'Unknown module name' );
443 protected function getExamples() {
444 static $examples = array (
445 'backlinks' => array (
446 "api.php?action=query&list=backlinks&bltitle=Main%20Page",
447 "api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info"
449 'embeddedin' => array (
450 "api.php?action=query&list=embeddedin&eititle=Template:Stub",
451 "api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info"
453 'imageusage' => array (
454 "api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg",
455 "api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info"
459 return $examples[$this->getModuleName()];
462 public function getVersion() {
463 return __CLASS__
. ': $Id$';