3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * This is a three-in-one module to query:
25 * * backlinks - links pointing to the given page,
26 * * embeddedin - what pages transclude the given page within themselves,
27 * * imageusage - what pages use the given image
31 class ApiQueryBacklinks
extends ApiQueryGeneratorBase
{
38 private $params, $cont, $redirect;
39 private $bl_ns, $bl_from, $bl_from_ns, $bl_table, $bl_code, $bl_title, $bl_fields, $hasNS;
42 * Maps ns and title to pageid
46 private $pageMap = [];
49 private $redirTitles = [];
50 private $continueStr = null;
52 // output element name, database column field prefix, database table
53 private $backlinksSettings = [
57 'linktbl' => 'pagelinks',
58 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Backlinks',
63 'linktbl' => 'templatelinks',
64 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Embeddedin',
69 'linktbl' => 'imagelinks',
70 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageusage',
74 public function __construct( ApiQuery
$query, $moduleName ) {
75 $settings = $this->backlinksSettings
[$moduleName];
76 $prefix = $settings['prefix'];
77 $code = $settings['code'];
78 $this->resultArr
= [];
80 parent
::__construct( $query, $moduleName, $code );
81 $this->bl_ns
= $prefix . '_namespace';
82 $this->bl_from
= $prefix . '_from';
83 $this->bl_from_ns
= $prefix . '_from_namespace';
84 $this->bl_table
= $settings['linktbl'];
85 $this->bl_code
= $code;
86 $this->helpUrl
= $settings['helpurl'];
88 $this->hasNS
= $moduleName !== 'imageusage';
90 $this->bl_title
= $prefix . '_title';
96 $this->bl_title
= $prefix . '_to';
103 public function execute() {
107 public function getCacheMode( $params ) {
111 public function executeGenerator( $resultPageSet ) {
112 $this->run( $resultPageSet );
116 * @param ApiPageSet $resultPageSet
119 private function runFirstQuery( $resultPageSet = null ) {
120 $this->addTables( [ $this->bl_table
, 'page' ] );
121 $this->addWhere( "{$this->bl_from}=page_id" );
122 if ( is_null( $resultPageSet ) ) {
123 $this->addFields( [ 'page_id', 'page_title', 'page_namespace' ] );
125 $this->addFields( $resultPageSet->getPageTableFields() );
127 $this->addFields( [ 'page_is_redirect', 'from_ns' => 'page_namespace' ] );
129 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
130 if ( $this->hasNS
) {
131 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
133 $this->addWhereFld( $this->bl_from_ns
, $this->params
['namespace'] );
135 if ( count( $this->cont
) >= 2 ) {
136 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
137 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
139 "{$this->bl_from_ns} $op {$this->cont[0]} OR " .
140 "({$this->bl_from_ns} = {$this->cont[0]} AND " .
141 "{$this->bl_from} $op= {$this->cont[1]})"
144 $this->addWhere( "{$this->bl_from} $op= {$this->cont[1]}" );
148 if ( $this->params
['filterredir'] == 'redirects' ) {
149 $this->addWhereFld( 'page_is_redirect', 1 );
150 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
151 // T24245 - Check for !redirect, as filtering nonredirects, when
152 // 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' : '' );
159 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
160 $orderBy[] = $this->bl_from_ns
. $sort;
162 $orderBy[] = $this->bl_from
. $sort;
163 $this->addOption( 'ORDER BY', $orderBy );
164 $this->addOption( 'STRAIGHT_JOIN' );
166 $res = $this->select( __METHOD__
);
168 foreach ( $res as $row ) {
169 if ( ++
$count > $this->params
['limit'] ) {
170 // We've reached the one extra which shows that there are
171 // additional pages to be had. Stop here...
172 // Continue string may be overridden at a later step
173 $this->continueStr
= "{$row->from_ns}|{$row->page_id}";
177 // Fill in continuation fields for later steps
178 if ( count( $this->cont
) < 2 ) {
179 $this->cont
[] = $row->from_ns
;
180 $this->cont
[] = $row->page_id
;
183 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
184 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
185 if ( $row->page_is_redirect
) {
186 $this->redirTitles
[] = $t;
189 if ( is_null( $resultPageSet ) ) {
190 $a = [ 'pageid' => (int)$row->page_id
];
191 ApiQueryBase
::addTitleInfo( $a, $t );
192 if ( $row->page_is_redirect
) {
193 $a['redirect'] = true;
195 // Put all the results in an array first
196 $this->resultArr
[$a['pageid']] = $a;
198 $resultPageSet->processDbRow( $row );
204 * @param ApiPageSet $resultPageSet
207 private function runSecondQuery( $resultPageSet = null ) {
208 $db = $this->getDB();
209 $this->addTables( [ 'page', $this->bl_table
] );
210 $this->addWhere( "{$this->bl_from}=page_id" );
212 if ( is_null( $resultPageSet ) ) {
213 $this->addFields( [ 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ] );
215 $this->addFields( $resultPageSet->getPageTableFields() );
218 $this->addFields( [ $this->bl_title
, 'from_ns' => 'page_namespace' ] );
219 if ( $this->hasNS
) {
220 $this->addFields( $this->bl_ns
);
223 // We can't use LinkBatch here because $this->hasNS may be false
228 foreach ( $this->redirTitles
as $t ) {
229 $redirNs = $t->getNamespace();
230 $redirDBkey = $t->getDBkey();
231 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $redirDBkey ) .
232 ( $this->hasNS ?
" AND {$this->bl_ns} = {$redirNs}" : '' );
233 $allRedirNs[$redirNs] = true;
234 $allRedirDBkey[$redirDBkey] = true;
236 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
237 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
239 if ( count( $this->cont
) >= 6 ) {
240 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
242 $where = "{$this->bl_from} $op= {$this->cont[5]}";
243 // Don't bother with namespace, title, or from_namespace if it's
244 // otherwise constant in the where clause.
245 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
246 $where = "{$this->bl_from_ns} $op {$this->cont[4]} OR " .
247 "({$this->bl_from_ns} = {$this->cont[4]} AND ($where))";
249 if ( count( $allRedirDBkey ) > 1 ) {
250 $title = $db->addQuotes( $this->cont
[3] );
251 $where = "{$this->bl_title} $op $title OR " .
252 "({$this->bl_title} = $title AND ($where))";
254 if ( $this->hasNS
&& count( $allRedirNs ) > 1 ) {
255 $where = "{$this->bl_ns} $op {$this->cont[2]} OR " .
256 "({$this->bl_ns} = {$this->cont[2]} AND ($where))";
259 $this->addWhere( $where );
261 if ( $this->params
['filterredir'] == 'redirects' ) {
262 $this->addWhereFld( 'page_is_redirect', 1 );
263 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
264 $this->addWhereFld( 'page_is_redirect', 0 );
267 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
269 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
270 // Don't order by namespace/title/from_namespace if it's constant in the WHERE clause
271 if ( $this->hasNS
&& count( $allRedirNs ) > 1 ) {
272 $orderBy[] = $this->bl_ns
. $sort;
274 if ( count( $allRedirDBkey ) > 1 ) {
275 $orderBy[] = $this->bl_title
. $sort;
277 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
278 $orderBy[] = $this->bl_from_ns
. $sort;
280 $orderBy[] = $this->bl_from
. $sort;
281 $this->addOption( 'ORDER BY', $orderBy );
282 $this->addOption( 'USE INDEX', [ 'page' => 'PRIMARY' ] );
284 $res = $this->select( __METHOD__
);
286 foreach ( $res as $row ) {
287 $ns = $this->hasNS ?
$row->{$this->bl_ns
} : NS_FILE
;
289 if ( ++
$count > $this->params
['limit'] ) {
290 // We've reached the one extra which shows that there are
291 // additional pages to be had. Stop here...
292 // Note we must keep the parameters for the first query constant
293 // This may be overridden at a later step
294 $title = $row->{$this->bl_title
};
295 $this->continueStr
= implode( '|', array_slice( $this->cont
, 0, 2 ) ) .
296 "|$ns|$title|{$row->from_ns}|{$row->page_id}";
300 // Fill in continuation fields for later steps
301 if ( count( $this->cont
) < 6 ) {
303 $this->cont
[] = $row->{$this->bl_title
};
304 $this->cont
[] = $row->from_ns
;
305 $this->cont
[] = $row->page_id
;
308 if ( is_null( $resultPageSet ) ) {
309 $a['pageid'] = (int)$row->page_id
;
310 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
311 if ( $row->page_is_redirect
) {
312 $a['redirect'] = true;
314 $parentID = $this->pageMap
[$ns][$row->{$this->bl_title
}];
315 // Put all the results in an array first
316 $this->resultArr
[$parentID]['redirlinks'][$row->page_id
] = $a;
318 $resultPageSet->processDbRow( $row );
324 * @param ApiPageSet $resultPageSet
327 private function run( $resultPageSet = null ) {
328 $this->params
= $this->extractRequestParams( false );
329 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
330 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
331 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
333 $result = $this->getResult();
335 if ( $this->params
['limit'] == 'max' ) {
336 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
337 $result->addParsedLimit( $this->getModuleName(), $this->params
['limit'] );
339 $this->params
['limit'] = (int)$this->params
['limit'];
340 $this->validateLimit( 'limit', $this->params
['limit'], 1, $userMax, $botMax );
343 $this->rootTitle
= $this->getTitleFromTitleOrPageId( $this->params
);
345 // only image titles are allowed for the root in imageinfo mode
346 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
348 [ 'apierror-imageusage-badtitle', $this->getModuleName() ],
353 // Parse and validate continuation parameter
355 if ( $this->params
['continue'] !== null ) {
356 $cont = explode( '|', $this->params
['continue'] );
358 switch ( count( $cont ) ) {
360 // redirect page ID for result adding
361 $this->cont
[7] = (int)$cont[7];
362 $this->dieContinueUsageIf( $cont[7] !== (string)$this->cont
[7] );
367 // top-level page ID for result adding
368 $this->cont
[6] = (int)$cont[6];
369 $this->dieContinueUsageIf( $cont[6] !== (string)$this->cont
[6] );
374 // ns for 2nd query (even for imageusage)
375 $this->cont
[2] = (int)$cont[2];
376 $this->dieContinueUsageIf( $cont[2] !== (string)$this->cont
[2] );
378 // title for 2nd query
379 $this->cont
[3] = $cont[3];
381 // from_ns for 2nd query
382 $this->cont
[4] = (int)$cont[4];
383 $this->dieContinueUsageIf( $cont[4] !== (string)$this->cont
[4] );
385 // from_id for 1st query
386 $this->cont
[5] = (int)$cont[5];
387 $this->dieContinueUsageIf( $cont[5] !== (string)$this->cont
[5] );
392 // from_ns for 1st query
393 $this->cont
[0] = (int)$cont[0];
394 $this->dieContinueUsageIf( $cont[0] !== (string)$this->cont
[0] );
396 // from_id for 1st query
397 $this->cont
[1] = (int)$cont[1];
398 $this->dieContinueUsageIf( $cont[1] !== (string)$this->cont
[1] );
403 $this->dieContinueUsageIf( true );
406 ksort( $this->cont
);
409 $this->runFirstQuery( $resultPageSet );
410 if ( $this->redirect
&& count( $this->redirTitles
) ) {
411 $this->resetQueryParams();
412 $this->runSecondQuery( $resultPageSet );
415 // Fill in any missing fields in case it's needed below
416 $this->cont +
= [ 0, 0, 0, '', 0, 0, 0 ];
418 if ( is_null( $resultPageSet ) ) {
419 // Try to add the result data in one go and pray that it fits
420 $code = $this->bl_code
;
421 $data = array_map( function ( $arr ) use ( $code ) {
422 if ( isset( $arr['redirlinks'] ) ) {
423 $arr['redirlinks'] = array_values( $arr['redirlinks'] );
424 ApiResult
::setIndexedTagName( $arr['redirlinks'], $code );
427 }, array_values( $this->resultArr
) );
428 $fit = $result->addValue( 'query', $this->getModuleName(), $data );
430 // It didn't fit. Add elements one by one until the
432 ksort( $this->resultArr
);
433 if ( count( $this->cont
) >= 7 ) {
434 $startAt = $this->cont
[6];
436 reset( $this->resultArr
);
437 $startAt = key( $this->resultArr
);
440 foreach ( $this->resultArr
as $pageID => $arr ) {
441 if ( $pageID < $startAt ) {
445 // Add the basic entry without redirlinks first
446 $fit = $result->addValue(
447 [ 'query', $this->getModuleName() ],
448 $idx, array_diff_key( $arr, [ 'redirlinks' => '' ] ) );
450 $this->continueStr
= implode( '|', array_slice( $this->cont
, 0, 6 ) ) .
456 $redirLinks = isset( $arr['redirlinks'] ) ?
(array)$arr['redirlinks'] : [];
457 ksort( $redirLinks );
458 if ( count( $this->cont
) >= 8 && $pageID == $startAt ) {
459 $redirStartAt = $this->cont
[7];
461 reset( $redirLinks );
462 $redirStartAt = key( $redirLinks );
464 foreach ( $redirLinks as $key => $redir ) {
465 if ( $key < $redirStartAt ) {
469 $fit = $result->addValue(
470 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
473 $this->continueStr
= implode( '|', array_slice( $this->cont
, 0, 6 ) ) .
480 $result->addIndexedTagName(
481 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
492 $result->addIndexedTagName(
493 [ 'query', $this->getModuleName() ],
497 if ( !is_null( $this->continueStr
) ) {
498 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
502 public function getAllowedParams() {
505 ApiBase
::PARAM_TYPE
=> 'string',
508 ApiBase
::PARAM_TYPE
=> 'integer',
511 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
514 ApiBase
::PARAM_ISMULTI
=> true,
515 ApiBase
::PARAM_TYPE
=> 'namespace'
518 ApiBase
::PARAM_DFLT
=> 'ascending',
519 ApiBase
::PARAM_TYPE
=> [
525 ApiBase
::PARAM_DFLT
=> 'all',
526 ApiBase
::PARAM_TYPE
=> [
533 ApiBase
::PARAM_DFLT
=> 10,
534 ApiBase
::PARAM_TYPE
=> 'limit',
535 ApiBase
::PARAM_MIN
=> 1,
536 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
537 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
540 if ( $this->getModuleName() == 'embeddedin' ) {
543 $retval['redirect'] = false;
548 protected function getExamplesMessages() {
551 'action=query&list=backlinks&bltitle=Main%20Page'
552 => 'apihelp-query+backlinks-example-simple',
553 'action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
554 => 'apihelp-query+backlinks-example-generator',
557 'action=query&list=embeddedin&eititle=Template:Stub'
558 => 'apihelp-query+embeddedin-example-simple',
559 'action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
560 => 'apihelp-query+embeddedin-example-generator',
563 'action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg'
564 => 'apihelp-query+imageusage-example-simple',
565 'action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
566 => 'apihelp-query+imageusage-example-generator',
570 return $examples[$this->getModuleName()];
573 public function getHelpUrls() {
574 return $this->helpUrl
;