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
{
42 private $bl_ns, $bl_from, $bl_from_ns, $bl_table, $bl_code, $bl_title, $bl_fields, $hasNS;
48 * Maps ns and title to pageid
52 private $pageMap = [];
55 private $redirTitles = [];
56 private $continueStr = null;
58 // output element name, database column field prefix, database table
59 private $backlinksSettings = [
63 'linktbl' => 'pagelinks',
64 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Backlinks',
69 'linktbl' => 'templatelinks',
70 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Embeddedin',
75 'linktbl' => 'imagelinks',
76 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageusage',
80 public function __construct( ApiQuery
$query, $moduleName ) {
81 $settings = $this->backlinksSettings
[$moduleName];
82 $prefix = $settings['prefix'];
83 $code = $settings['code'];
84 $this->resultArr
= [];
86 parent
::__construct( $query, $moduleName, $code );
87 $this->bl_ns
= $prefix . '_namespace';
88 $this->bl_from
= $prefix . '_from';
89 $this->bl_from_ns
= $prefix . '_from_namespace';
90 $this->bl_table
= $settings['linktbl'];
91 $this->bl_code
= $code;
92 $this->helpUrl
= $settings['helpurl'];
94 $this->hasNS
= $moduleName !== 'imageusage';
96 $this->bl_title
= $prefix . '_title';
102 $this->bl_title
= $prefix . '_to';
109 public function execute() {
113 public function getCacheMode( $params ) {
117 public function executeGenerator( $resultPageSet ) {
118 $this->run( $resultPageSet );
122 * @param ApiPageSet $resultPageSet
125 private function runFirstQuery( $resultPageSet = null ) {
126 $this->addTables( [ $this->bl_table
, 'page' ] );
127 $this->addWhere( "{$this->bl_from}=page_id" );
128 if ( is_null( $resultPageSet ) ) {
129 $this->addFields( [ 'page_id', 'page_title', 'page_namespace' ] );
131 $this->addFields( $resultPageSet->getPageTableFields() );
133 $this->addFields( [ 'page_is_redirect', 'from_ns' => 'page_namespace' ] );
135 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
136 if ( $this->hasNS
) {
137 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
139 $this->addWhereFld( $this->bl_from_ns
, $this->params
['namespace'] );
141 if ( count( $this->cont
) >= 2 ) {
142 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
143 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
145 "{$this->bl_from_ns} $op {$this->cont[0]} OR " .
146 "({$this->bl_from_ns} = {$this->cont[0]} AND " .
147 "{$this->bl_from} $op= {$this->cont[1]})"
150 $this->addWhere( "{$this->bl_from} $op= {$this->cont[1]}" );
154 if ( $this->params
['filterredir'] == 'redirects' ) {
155 $this->addWhereFld( 'page_is_redirect', 1 );
156 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
157 // T24245 - Check for !redirect, as filtering nonredirects, when
158 // getting what links to them is contradictory
159 $this->addWhereFld( 'page_is_redirect', 0 );
162 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
163 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
165 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
166 $orderBy[] = $this->bl_from_ns
. $sort;
168 $orderBy[] = $this->bl_from
. $sort;
169 $this->addOption( 'ORDER BY', $orderBy );
170 $this->addOption( 'STRAIGHT_JOIN' );
172 $res = $this->select( __METHOD__
);
174 foreach ( $res as $row ) {
175 if ( ++
$count > $this->params
['limit'] ) {
176 // We've reached the one extra which shows that there are
177 // additional pages to be had. Stop here...
178 // Continue string may be overridden at a later step
179 $this->continueStr
= "{$row->from_ns}|{$row->page_id}";
183 // Fill in continuation fields for later steps
184 if ( count( $this->cont
) < 2 ) {
185 $this->cont
[] = $row->from_ns
;
186 $this->cont
[] = $row->page_id
;
189 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
190 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
191 if ( $row->page_is_redirect
) {
192 $this->redirTitles
[] = $t;
195 if ( is_null( $resultPageSet ) ) {
196 $a = [ 'pageid' => (int)$row->page_id
];
197 ApiQueryBase
::addTitleInfo( $a, $t );
198 if ( $row->page_is_redirect
) {
199 $a['redirect'] = true;
201 // Put all the results in an array first
202 $this->resultArr
[$a['pageid']] = $a;
204 $resultPageSet->processDbRow( $row );
210 * @param ApiPageSet $resultPageSet
213 private function runSecondQuery( $resultPageSet = null ) {
214 $db = $this->getDB();
215 $this->addTables( [ 'page', $this->bl_table
] );
216 $this->addWhere( "{$this->bl_from}=page_id" );
218 if ( is_null( $resultPageSet ) ) {
219 $this->addFields( [ 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ] );
221 $this->addFields( $resultPageSet->getPageTableFields() );
224 $this->addFields( [ $this->bl_title
, 'from_ns' => 'page_namespace' ] );
225 if ( $this->hasNS
) {
226 $this->addFields( $this->bl_ns
);
229 // We can't use LinkBatch here because $this->hasNS may be false
234 foreach ( $this->redirTitles
as $t ) {
235 $redirNs = $t->getNamespace();
236 $redirDBkey = $t->getDBkey();
237 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $redirDBkey ) .
238 ( $this->hasNS ?
" AND {$this->bl_ns} = {$redirNs}" : '' );
239 $allRedirNs[$redirNs] = true;
240 $allRedirDBkey[$redirDBkey] = true;
242 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
243 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
245 if ( count( $this->cont
) >= 6 ) {
246 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
248 $where = "{$this->bl_from} $op= {$this->cont[5]}";
249 // Don't bother with namespace, title, or from_namespace if it's
250 // otherwise constant in the where clause.
251 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
252 $where = "{$this->bl_from_ns} $op {$this->cont[4]} OR " .
253 "({$this->bl_from_ns} = {$this->cont[4]} AND ($where))";
255 if ( count( $allRedirDBkey ) > 1 ) {
256 $title = $db->addQuotes( $this->cont
[3] );
257 $where = "{$this->bl_title} $op $title OR " .
258 "({$this->bl_title} = $title AND ($where))";
260 if ( $this->hasNS
&& count( $allRedirNs ) > 1 ) {
261 $where = "{$this->bl_ns} $op {$this->cont[2]} OR " .
262 "({$this->bl_ns} = {$this->cont[2]} AND ($where))";
265 $this->addWhere( $where );
267 if ( $this->params
['filterredir'] == 'redirects' ) {
268 $this->addWhereFld( 'page_is_redirect', 1 );
269 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
270 $this->addWhereFld( 'page_is_redirect', 0 );
273 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
275 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
276 // Don't order by namespace/title/from_namespace if it's constant in the WHERE clause
277 if ( $this->hasNS
&& count( $allRedirNs ) > 1 ) {
278 $orderBy[] = $this->bl_ns
. $sort;
280 if ( count( $allRedirDBkey ) > 1 ) {
281 $orderBy[] = $this->bl_title
. $sort;
283 if ( $this->params
['namespace'] !== null && count( $this->params
['namespace'] ) > 1 ) {
284 $orderBy[] = $this->bl_from_ns
. $sort;
286 $orderBy[] = $this->bl_from
. $sort;
287 $this->addOption( 'ORDER BY', $orderBy );
288 $this->addOption( 'USE INDEX', [ 'page' => 'PRIMARY' ] );
290 $res = $this->select( __METHOD__
);
292 foreach ( $res as $row ) {
293 $ns = $this->hasNS ?
$row->{$this->bl_ns
} : NS_FILE
;
295 if ( ++
$count > $this->params
['limit'] ) {
296 // We've reached the one extra which shows that there are
297 // additional pages to be had. Stop here...
298 // Note we must keep the parameters for the first query constant
299 // This may be overridden at a later step
300 $title = $row->{$this->bl_title
};
301 $this->continueStr
= implode( '|', array_slice( $this->cont
, 0, 2 ) ) .
302 "|$ns|$title|{$row->from_ns}|{$row->page_id}";
306 // Fill in continuation fields for later steps
307 if ( count( $this->cont
) < 6 ) {
309 $this->cont
[] = $row->{$this->bl_title
};
310 $this->cont
[] = $row->from_ns
;
311 $this->cont
[] = $row->page_id
;
314 if ( is_null( $resultPageSet ) ) {
315 $a = [ 'pageid' => (int)$row->page_id
];
316 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
317 if ( $row->page_is_redirect
) {
318 $a['redirect'] = true;
320 $parentID = $this->pageMap
[$ns][$row->{$this->bl_title
}];
321 // Put all the results in an array first
322 $this->resultArr
[$parentID]['redirlinks'][$row->page_id
] = $a;
324 $resultPageSet->processDbRow( $row );
330 * @param ApiPageSet $resultPageSet
333 private function run( $resultPageSet = null ) {
334 $this->params
= $this->extractRequestParams( false );
335 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
336 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
337 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
339 $result = $this->getResult();
341 if ( $this->params
['limit'] == 'max' ) {
342 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
343 $result->addParsedLimit( $this->getModuleName(), $this->params
['limit'] );
345 $this->params
['limit'] = (int)$this->params
['limit'];
346 $this->validateLimit( 'limit', $this->params
['limit'], 1, $userMax, $botMax );
349 $this->rootTitle
= $this->getTitleFromTitleOrPageId( $this->params
);
351 // only image titles are allowed for the root in imageinfo mode
352 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
354 [ 'apierror-imageusage-badtitle', $this->getModuleName() ],
359 // Parse and validate continuation parameter
361 if ( $this->params
['continue'] !== null ) {
362 $cont = explode( '|', $this->params
['continue'] );
364 switch ( count( $cont ) ) {
366 // redirect page ID for result adding
367 $this->cont
[7] = (int)$cont[7];
368 $this->dieContinueUsageIf( $cont[7] !== (string)$this->cont
[7] );
373 // top-level page ID for result adding
374 $this->cont
[6] = (int)$cont[6];
375 $this->dieContinueUsageIf( $cont[6] !== (string)$this->cont
[6] );
380 // ns for 2nd query (even for imageusage)
381 $this->cont
[2] = (int)$cont[2];
382 $this->dieContinueUsageIf( $cont[2] !== (string)$this->cont
[2] );
384 // title for 2nd query
385 $this->cont
[3] = $cont[3];
387 // from_ns for 2nd query
388 $this->cont
[4] = (int)$cont[4];
389 $this->dieContinueUsageIf( $cont[4] !== (string)$this->cont
[4] );
391 // from_id for 1st query
392 $this->cont
[5] = (int)$cont[5];
393 $this->dieContinueUsageIf( $cont[5] !== (string)$this->cont
[5] );
398 // from_ns for 1st query
399 $this->cont
[0] = (int)$cont[0];
400 $this->dieContinueUsageIf( $cont[0] !== (string)$this->cont
[0] );
402 // from_id for 1st query
403 $this->cont
[1] = (int)$cont[1];
404 $this->dieContinueUsageIf( $cont[1] !== (string)$this->cont
[1] );
409 $this->dieContinueUsageIf( true );
412 ksort( $this->cont
);
415 $this->runFirstQuery( $resultPageSet );
416 if ( $this->redirect
&& count( $this->redirTitles
) ) {
417 $this->resetQueryParams();
418 $this->runSecondQuery( $resultPageSet );
421 // Fill in any missing fields in case it's needed below
422 $this->cont +
= [ 0, 0, 0, '', 0, 0, 0 ];
424 if ( is_null( $resultPageSet ) ) {
425 // Try to add the result data in one go and pray that it fits
426 $code = $this->bl_code
;
427 $data = array_map( function ( $arr ) use ( $code ) {
428 if ( isset( $arr['redirlinks'] ) ) {
429 $arr['redirlinks'] = array_values( $arr['redirlinks'] );
430 ApiResult
::setIndexedTagName( $arr['redirlinks'], $code );
433 }, array_values( $this->resultArr
) );
434 $fit = $result->addValue( 'query', $this->getModuleName(), $data );
436 // It didn't fit. Add elements one by one until the
438 ksort( $this->resultArr
);
439 if ( count( $this->cont
) >= 7 ) {
440 $startAt = $this->cont
[6];
442 reset( $this->resultArr
);
443 $startAt = key( $this->resultArr
);
446 foreach ( $this->resultArr
as $pageID => $arr ) {
447 if ( $pageID < $startAt ) {
451 // Add the basic entry without redirlinks first
452 $fit = $result->addValue(
453 [ 'query', $this->getModuleName() ],
454 $idx, array_diff_key( $arr, [ 'redirlinks' => '' ] ) );
456 $this->continueStr
= implode( '|', array_slice( $this->cont
, 0, 6 ) ) .
462 $redirLinks = isset( $arr['redirlinks'] ) ?
(array)$arr['redirlinks'] : [];
463 ksort( $redirLinks );
464 if ( count( $this->cont
) >= 8 && $pageID == $startAt ) {
465 $redirStartAt = $this->cont
[7];
467 reset( $redirLinks );
468 $redirStartAt = key( $redirLinks );
470 foreach ( $redirLinks as $key => $redir ) {
471 if ( $key < $redirStartAt ) {
475 $fit = $result->addValue(
476 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
479 $this->continueStr
= implode( '|', array_slice( $this->cont
, 0, 6 ) ) .
486 $result->addIndexedTagName(
487 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
498 $result->addIndexedTagName(
499 [ 'query', $this->getModuleName() ],
503 if ( !is_null( $this->continueStr
) ) {
504 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
508 public function getAllowedParams() {
511 ApiBase
::PARAM_TYPE
=> 'string',
514 ApiBase
::PARAM_TYPE
=> 'integer',
517 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
520 ApiBase
::PARAM_ISMULTI
=> true,
521 ApiBase
::PARAM_TYPE
=> 'namespace'
524 ApiBase
::PARAM_DFLT
=> 'ascending',
525 ApiBase
::PARAM_TYPE
=> [
531 ApiBase
::PARAM_DFLT
=> 'all',
532 ApiBase
::PARAM_TYPE
=> [
539 ApiBase
::PARAM_DFLT
=> 10,
540 ApiBase
::PARAM_TYPE
=> 'limit',
541 ApiBase
::PARAM_MIN
=> 1,
542 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
543 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
546 if ( $this->getModuleName() == 'embeddedin' ) {
549 $retval['redirect'] = false;
554 protected function getExamplesMessages() {
557 'action=query&list=backlinks&bltitle=Main%20Page'
558 => 'apihelp-query+backlinks-example-simple',
559 'action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
560 => 'apihelp-query+backlinks-example-generator',
563 'action=query&list=embeddedin&eititle=Template:Stub'
564 => 'apihelp-query+embeddedin-example-simple',
565 'action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
566 => 'apihelp-query+embeddedin-example-generator',
569 'action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg'
570 => 'apihelp-query+imageusage-example-simple',
571 'action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
572 => 'apihelp-query+imageusage-example-generator',
576 return $examples[$this->getModuleName()];
579 public function getHelpUrls() {
580 return $this->helpUrl
;