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, $cont, $redirect;
43 private $bl_ns, $bl_from, $bl_from_ns, $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( ApiQuery
$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_from_ns
= $prefix . '_from_namespace';
88 $this->bl_table
= $settings['linktbl'];
89 $this->bl_code
= $code;
90 $this->helpUrl
= $settings['helpurl'];
92 $this->hasNS
= $moduleName !== 'imageusage';
94 $this->bl_title
= $prefix . '_title';
95 $this->bl_fields
= array(
100 $this->bl_title
= $prefix . '_to';
101 $this->bl_fields
= array(
107 public function execute() {
111 public function getCacheMode( $params ) {
115 public function executeGenerator( $resultPageSet ) {
116 $this->run( $resultPageSet );
120 * @param ApiPageSet $resultPageSet
123 private function runFirstQuery( $resultPageSet = null ) {
124 $this->addTables( array( $this->bl_table
, 'page' ) );
125 $this->addWhere( "{$this->bl_from}=page_id" );
126 if ( is_null( $resultPageSet ) ) {
127 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
129 $this->addFields( $resultPageSet->getPageTableFields() );
131 $this->addFields( array( 'page_is_redirect', 'from_ns' => 'page_namespace' ) );
133 $this->addWhereFld( $this->bl_title
, $this->rootTitle
->getDBkey() );
134 if ( $this->hasNS
) {
135 $this->addWhereFld( $this->bl_ns
, $this->rootTitle
->getNamespace() );
137 $this->addWhereFld( $this->bl_from_ns
, $this->params
['namespace'] );
139 if ( count( $this->cont
) >= 2 ) {
140 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
141 if ( count( $this->params
['namespace'] ) > 1 ) {
143 "{$this->bl_from_ns} $op {$this->cont[0]} OR " .
144 "({$this->bl_from_ns} = {$this->cont[0]} AND " .
145 "{$this->bl_from} $op= {$this->cont[1]})"
148 $this->addWhere( "{$this->bl_from} $op= {$this->cont[1]}" );
152 if ( $this->params
['filterredir'] == 'redirects' ) {
153 $this->addWhereFld( 'page_is_redirect', 1 );
154 } elseif ( $this->params
['filterredir'] == 'nonredirects' && !$this->redirect
) {
155 // bug 22245 - Check for !redirect, as filtering nonredirects, when
156 // getting what links to them is contradictory
157 $this->addWhereFld( 'page_is_redirect', 0 );
160 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
161 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
163 if ( count( $this->params
['namespace'] ) > 1 ) {
164 $orderBy[] = $this->bl_from_ns
. $sort;
166 $orderBy[] = $this->bl_from
. $sort;
167 $this->addOption( 'ORDER BY', $orderBy );
168 $this->addOption( 'STRAIGHT_JOIN' );
170 $res = $this->select( __METHOD__
);
172 foreach ( $res as $row ) {
173 if ( ++
$count > $this->params
['limit'] ) {
174 // We've reached the one extra which shows that there are
175 // additional pages to be had. Stop here...
176 // Continue string may be overridden at a later step
177 $this->continueStr
= "{$row->from_ns}|{$row->page_id}";
181 // Fill in continuation fields for later steps
182 if ( count( $this->cont
) < 2 ) {
183 $this->cont
[] = $row->from_ns
;
184 $this->cont
[] = $row->page_id
;
187 $this->pageMap
[$row->page_namespace
][$row->page_title
] = $row->page_id
;
188 $t = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
189 if ( $row->page_is_redirect
) {
190 $this->redirTitles
[] = $t;
193 if ( is_null( $resultPageSet ) ) {
194 $a = array( 'pageid' => intval( $row->page_id
) );
195 ApiQueryBase
::addTitleInfo( $a, $t );
196 if ( $row->page_is_redirect
) {
199 // Put all the results in an array first
200 $this->resultArr
[$a['pageid']] = $a;
202 $resultPageSet->processDbRow( $row );
208 * @param ApiPageSet $resultPageSet
211 private function runSecondQuery( $resultPageSet = null ) {
212 $db = $this->getDB();
213 $this->addTables( array( 'page', $this->bl_table
) );
214 $this->addWhere( "{$this->bl_from}=page_id" );
216 if ( is_null( $resultPageSet ) ) {
217 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
219 $this->addFields( $resultPageSet->getPageTableFields() );
222 $this->addFields( array( $this->bl_title
, 'from_ns' => 'page_namespace' ) );
223 if ( $this->hasNS
) {
224 $this->addFields( $this->bl_ns
);
227 // We can't use LinkBatch here because $this->hasNS may be false
228 $titleWhere = array();
229 $allRedirNs = array();
230 $allRedirDBkey = array();
232 foreach ( $this->redirTitles
as $t ) {
233 $redirNs = $t->getNamespace();
234 $redirDBkey = $t->getDBkey();
235 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $redirDBkey ) .
236 ( $this->hasNS ?
" AND {$this->bl_ns} = {$redirNs}" : '' );
237 $allRedirNs[$redirNs] = true;
238 $allRedirDBkey[$redirDBkey] = true;
240 $this->addWhere( $db->makeList( $titleWhere, LIST_OR
) );
241 $this->addWhereFld( 'page_namespace', $this->params
['namespace'] );
243 if ( count( $this->cont
) >= 6 ) {
244 $op = $this->params
['dir'] == 'descending' ?
'<' : '>';
246 $where = "{$this->bl_from} $op= {$this->cont[5]}";
247 // Don't bother with namespace, title, or from_namespace if it's
248 // otherwise constant in the where clause.
249 if ( count( $this->params
['namespace'] ) > 1 ) {
250 $where = "{$this->bl_from_ns} $op {$this->cont[4]} OR " .
251 "({$this->bl_from_ns} = {$this->cont[4]} AND ($where))";
253 if ( count( $allRedirDBkey ) > 1 ) {
254 $title = $db->addQuotes( $this->cont
[3] );
255 $where = "{$this->bl_title} $op $title OR " .
256 "({$this->bl_title} = $title AND ($where))";
258 if ( $this->hasNS
&& count( $allRedirNs ) > 1 ) {
259 $where = "{$this->bl_ns} $op {$this->cont[2]} OR " .
260 "({$this->bl_ns} = {$this->cont[2]} AND ($where))";
263 $this->addWhere( $where );
265 if ( $this->params
['filterredir'] == 'redirects' ) {
266 $this->addWhereFld( 'page_is_redirect', 1 );
267 } elseif ( $this->params
['filterredir'] == 'nonredirects' ) {
268 $this->addWhereFld( 'page_is_redirect', 0 );
271 $this->addOption( 'LIMIT', $this->params
['limit'] +
1 );
273 $sort = ( $this->params
['dir'] == 'descending' ?
' DESC' : '' );
274 // Don't order by namespace/title/from_namespace if it's constant in the WHERE clause
275 if ( $this->hasNS
&& count( $allRedirNs ) > 1 ) {
276 $orderBy[] = $this->bl_ns
. $sort;
278 if ( count( $allRedirDBkey ) > 1 ) {
279 $orderBy[] = $this->bl_title
. $sort;
281 if ( count( $this->params
['namespace'] ) > 1 ) {
282 $orderBy[] = $this->bl_from_ns
. $sort;
284 $orderBy[] = $this->bl_from
. $sort;
285 $this->addOption( 'ORDER BY', $orderBy );
286 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
288 $res = $this->select( __METHOD__
);
290 foreach ( $res as $row ) {
291 $ns = $this->hasNS ?
$row->{$this->bl_ns
} : NS_FILE
;
293 if ( ++
$count > $this->params
['limit'] ) {
294 // We've reached the one extra which shows that there are
295 // additional pages to be had. Stop here...
296 // Note we must keep the parameters for the first query constant
297 // This may be overridden at a later step
298 $title = $row->{$this->bl_title
};
299 $this->continueStr
= join( '|', array_slice( $this->cont
, 0, 2 ) ) .
300 "|$ns|$title|{$row->from_ns}|{$row->page_id}";
304 // Fill in continuation fields for later steps
305 if ( count( $this->cont
) < 6 ) {
307 $this->cont
[] = $row->{$this->bl_title
};
308 $this->cont
[] = $row->from_ns
;
309 $this->cont
[] = $row->page_id
;
312 if ( is_null( $resultPageSet ) ) {
313 $a['pageid'] = intval( $row->page_id
);
314 ApiQueryBase
::addTitleInfo( $a, Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
315 if ( $row->page_is_redirect
) {
318 $parentID = $this->pageMap
[$ns][$row->{$this->bl_title
}];
319 // Put all the results in an array first
320 $this->resultArr
[$parentID]['redirlinks'][$row->page_id
] = $a;
322 $resultPageSet->processDbRow( $row );
328 * @param ApiPageSet $resultPageSet
331 private function run( $resultPageSet = null ) {
332 $this->params
= $this->extractRequestParams( false );
333 $this->redirect
= isset( $this->params
['redirect'] ) && $this->params
['redirect'];
334 $userMax = ( $this->redirect ? ApiBase
::LIMIT_BIG1
/ 2 : ApiBase
::LIMIT_BIG1
);
335 $botMax = ( $this->redirect ? ApiBase
::LIMIT_BIG2
/ 2 : ApiBase
::LIMIT_BIG2
);
337 $result = $this->getResult();
339 if ( $this->params
['limit'] == 'max' ) {
340 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
341 $result->setParsedLimit( $this->getModuleName(), $this->params
['limit'] );
343 $this->params
['limit'] = intval( $this->params
['limit'] );
344 $this->validateLimit( 'limit', $this->params
['limit'], 1, $userMax, $botMax );
347 $this->rootTitle
= $this->getTitleOrPageId( $this->params
)->getTitle();
349 // only image titles are allowed for the root in imageinfo mode
350 if ( !$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_FILE
) {
352 "The title for {$this->getModuleName()} query must be a file",
357 // Parse and validate continuation parameter
358 $this->cont
= array();
359 if ( $this->params
['continue'] !== null ) {
360 $db = $this->getDB();
361 $cont = explode( '|', $this->params
['continue'] );
363 switch ( count( $cont ) ) {
365 // redirect page ID for result adding
366 $this->cont
[7] = (int)$cont[7];
367 $this->dieContinueUsageIf( $cont[7] !== (string)$this->cont
[7] );
372 // top-level page ID for result adding
373 $this->cont
[6] = (int)$cont[6];
374 $this->dieContinueUsageIf( $cont[6] !== (string)$this->cont
[6] );
379 // ns for 2nd query (even for imageusage)
380 $this->cont
[2] = (int)$cont[2];
381 $this->dieContinueUsageIf( $cont[2] !== (string)$this->cont
[2] );
383 // title for 2nd query
384 $this->cont
[3] = $cont[3];
386 // from_ns for 2nd query
387 $this->cont
[4] = (int)$cont[4];
388 $this->dieContinueUsageIf( $cont[4] !== (string)$this->cont
[4] );
390 // from_id for 1st query
391 $this->cont
[5] = (int)$cont[5];
392 $this->dieContinueUsageIf( $cont[5] !== (string)$this->cont
[5] );
397 // from_ns for 1st query
398 $this->cont
[0] = (int)$cont[0];
399 $this->dieContinueUsageIf( $cont[0] !== (string)$this->cont
[0] );
401 // from_id for 1st query
402 $this->cont
[1] = (int)$cont[1];
403 $this->dieContinueUsageIf( $cont[1] !== (string)$this->cont
[1] );
408 $this->dieContinueUsageIf( true );
411 ksort( $this->cont
);
414 $this->runFirstQuery( $resultPageSet );
415 if ( $this->redirect
&& count( $this->redirTitles
) ) {
416 $this->resetQueryParams();
417 $this->runSecondQuery( $resultPageSet );
420 // Fill in any missing fields in case it's needed below
421 $this->cont +
= array( 0, 0, 0, '', 0, 0, 0 );
423 if ( is_null( $resultPageSet ) ) {
424 // Try to add the result data in one go and pray that it fits
425 $code = $this->bl_code
;
426 $data = array_map( function ( $arr ) use ( $result, $code ) {
427 if ( isset( $arr['redirlinks'] ) ) {
428 $arr['redirlinks'] = array_values( $arr['redirlinks'] );
429 $result->setIndexedTagName( $arr['redirlinks'], $code );
432 }, array_values( $this->resultArr
) );
433 $fit = $result->addValue( 'query', $this->getModuleName(), $data );
435 // It didn't fit. Add elements one by one until the
437 ksort( $this->resultArr
);
438 if ( count( $this->cont
) >= 7 ) {
439 $startAt = $this->cont
[6];
441 reset( $this->resultArr
);
442 $startAt = key( $this->resultArr
);
445 foreach ( $this->resultArr
as $pageID => $arr ) {
446 if ( $pageID < $startAt ) {
450 // Add the basic entry without redirlinks first
451 $fit = $result->addValue(
452 array( 'query', $this->getModuleName() ),
453 $idx, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
455 $this->continueStr
= join( '|', array_slice( $this->cont
, 0, 6 ) ) .
461 $redirLinks = isset( $arr['redirlinks'] ) ?
(array)$arr['redirlinks'] : array();
462 ksort( $redirLinks );
463 if ( count( $this->cont
) >= 8 && $pageID == $startAt ) {
464 $redirStartAt = $this->cont
[7];
466 reset( $redirLinks );
467 $redirStartAt = key( $redirLinks );
469 foreach ( $redirLinks as $key => $redir ) {
470 if ( $key < $redirStartAt ) {
474 $fit = $result->addValue(
475 array( 'query', $this->getModuleName(), $idx, 'redirlinks' ),
478 $this->continueStr
= join( '|', array_slice( $this->cont
, 0, 6 ) ) .
485 $result->setIndexedTagName_internal(
486 array( 'query', $this->getModuleName(), $idx, 'redirlinks' ),
497 $result->setIndexedTagName_internal(
498 array( 'query', $this->getModuleName() ),
502 if ( !is_null( $this->continueStr
) ) {
503 $this->setContinueEnumParameter( 'continue', $this->continueStr
);
507 public function getAllowedParams() {
510 ApiBase
::PARAM_TYPE
=> 'string',
513 ApiBase
::PARAM_TYPE
=> 'integer',
516 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
518 'namespace' => array(
519 ApiBase
::PARAM_ISMULTI
=> true,
520 ApiBase
::PARAM_TYPE
=> 'namespace'
523 ApiBase
::PARAM_DFLT
=> 'ascending',
524 ApiBase
::PARAM_TYPE
=> array(
529 'filterredir' => array(
530 ApiBase
::PARAM_DFLT
=> 'all',
531 ApiBase
::PARAM_TYPE
=> array(
538 ApiBase
::PARAM_DFLT
=> 10,
539 ApiBase
::PARAM_TYPE
=> 'limit',
540 ApiBase
::PARAM_MIN
=> 1,
541 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
542 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
545 if ( $this->getModuleName() == 'embeddedin' ) {
548 $retval['redirect'] = false;
553 public function getExamplesMessages() {
554 static $examples = array(
555 'backlinks' => array(
556 'action=query&list=backlinks&bltitle=Main%20Page'
557 => 'apihelp-query+backlinks-example-simple',
558 'action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
559 => 'apihelp-query+backlinks-example-generator',
561 'embeddedin' => array(
562 'action=query&list=embeddedin&eititle=Template:Stub'
563 => 'apihelp-query+embeddedin-example-simple',
564 'action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
565 => 'apihelp-query+embeddedin-example-generator',
567 'imageusage' => array(
568 'action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg'
569 => 'apihelp-query+imageusage-example-simple',
570 'action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
571 => 'apihelp-query+imageusage-example-generator',
575 return $examples[$this->getModuleName()];
578 public function getHelpUrls() {
579 return $this->helpUrl
;