MediaWiki master
ApiQueryBacklinks.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
18
28
32 private $rootTitle;
33
34 private LinksMigration $linksMigration;
35
37 private $params;
39 private $cont;
41 private $redirect;
42
43 private string $bl_ns;
44 private string $bl_from;
45 private string $bl_from_ns;
46 private string $bl_table;
47 private string $bl_code;
48 private string $bl_title;
50 private $virtual_domain;
51 private bool $hasNS;
52
54 private $helpUrl;
55
61 private $pageMap = [];
63 private $resultArr;
64
66 private $redirTitles = [];
68 private $continueStr = null;
69
71 private $backlinksSettings = [
72 'backlinks' => [
73 'code' => 'bl',
74 'prefix' => 'pl',
75 'linktbl' => 'pagelinks',
76 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Backlinks',
77 'virtualdomain' => PageLinksTable::VIRTUAL_DOMAIN,
78 ],
79 'embeddedin' => [
80 'code' => 'ei',
81 'prefix' => 'tl',
82 'linktbl' => 'templatelinks',
83 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Embeddedin',
84 'virtualdomain' => TemplateLinksTable::VIRTUAL_DOMAIN,
85 ],
86 'imageusage' => [
87 'code' => 'iu',
88 'prefix' => 'il',
89 'linktbl' => 'imagelinks',
90 'helpurl' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageusage',
91 'virtualdomain' => ImageLinksTable::VIRTUAL_DOMAIN,
92 ]
93 ];
94
95 public function __construct(
96 ApiQuery $query,
97 string $moduleName,
98 LinksMigration $linksMigration
99 ) {
100 $settings = $this->backlinksSettings[$moduleName];
101 $prefix = $settings['prefix'];
102 $code = $settings['code'];
103 $this->resultArr = [];
104
105 parent::__construct( $query, $moduleName, $code );
106 $this->bl_table = $settings['linktbl'];
107 $this->hasNS = $moduleName !== 'imageusage';
108 $this->linksMigration = $linksMigration;
109 [ $this->bl_ns, $this->bl_title ] = $this->linksMigration->getTitleFields( $this->bl_table );
110 $this->bl_from = $prefix . '_from';
111 $this->bl_from_ns = $prefix . '_from_namespace';
112 $this->bl_code = $code;
113 $this->helpUrl = $settings['helpurl'];
114 $this->virtual_domain = $settings['virtualdomain'];
115 }
116
117 public function execute() {
118 $this->run();
119 }
120
122 public function getCacheMode( $params ) {
123 return 'public';
124 }
125
127 public function executeGenerator( $resultPageSet ) {
128 $this->run( $resultPageSet );
129 }
130
135 private function runFirstQuery( $resultPageSet = null ) {
136 $this->addTables( [ $this->bl_table, 'page' ] );
137 $this->addWhere( "{$this->bl_from}=page_id" );
138 if ( $resultPageSet === null ) {
139 $this->addFields( [ 'page_id', 'page_title', 'page_namespace' ] );
140 } else {
141 $this->addFields( $resultPageSet->getPageTableFields() );
142 }
143 $this->addFields( [ 'page_is_redirect', 'from_ns' => 'page_namespace' ] );
144
145 $this->addWhere( $this->linksMigration->getLinksConditions( $this->bl_table, $this->rootTitle ) );
146 $this->addWhereFld( $this->bl_from_ns, $this->params['namespace'] );
147
148 if ( count( $this->cont ) >= 2 ) {
149 $db = $this->getDB();
150 $op = $this->params['dir'] == 'descending' ? '<=' : '>=';
151 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
152 $this->addWhere( $db->buildComparison( $op, [
153 $this->bl_from_ns => $this->cont[0],
154 $this->bl_from => $this->cont[1],
155 ] ) );
156 } else {
157 $this->addWhere( $db->buildComparison( $op, [ $this->bl_from => $this->cont[1] ] ) );
158 }
159 }
160
161 if ( $this->params['filterredir'] == 'redirects' ) {
162 $this->addWhereFld( 'page_is_redirect', 1 );
163 } elseif ( $this->params['filterredir'] == 'nonredirects' && !$this->redirect ) {
164 // T24245 - Check for !redirect, as filtering nonredirects, when
165 // getting what links to them is contradictory
166 $this->addWhereFld( 'page_is_redirect', 0 );
167 }
168
169 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
170 $sort = ( $this->params['dir'] == 'descending' ? ' DESC' : '' );
171 $orderBy = [];
172 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
173 $orderBy[] = $this->bl_from_ns . $sort;
174 }
175 $orderBy[] = $this->bl_from . $sort;
176 $this->addOption( 'ORDER BY', $orderBy );
177 $this->addOption( 'STRAIGHT_JOIN' );
178
179 $this->setVirtualDomain( $this->virtual_domain );
180 $res = $this->select( __METHOD__ );
181 $this->resetVirtualDomain();
182
183 if ( $resultPageSet === null ) {
184 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
185 }
186
187 $count = 0;
188 foreach ( $res as $row ) {
189 if ( ++$count > $this->params['limit'] ) {
190 // We've reached the one extra which shows that there are
191 // additional pages to be had. Stop here...
192 // Continue string may be overridden at a later step
193 $this->continueStr = "{$row->from_ns}|{$row->page_id}";
194 break;
195 }
196
197 // Fill in continuation fields for later steps
198 if ( count( $this->cont ) < 2 ) {
199 $this->cont[] = $row->from_ns;
200 $this->cont[] = $row->page_id;
201 }
202
203 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
204 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
205 if ( $row->page_is_redirect ) {
206 $this->redirTitles[] = $t;
207 }
208
209 if ( $resultPageSet === null ) {
210 $a = [ 'pageid' => (int)$row->page_id ];
212 if ( $row->page_is_redirect ) {
213 $a['redirect'] = true;
214 }
215 // Put all the results in an array first
216 $this->resultArr[$a['pageid']] = $a;
217 } else {
218 $resultPageSet->processDbRow( $row );
219 }
220 }
221 }
222
227 private function runSecondQuery( $resultPageSet = null ) {
228 $db = $this->getDB();
229 $queryInfo = $this->linksMigration->getQueryInfo( $this->bl_table, $this->bl_table );
230 $this->addTables( [ ...$queryInfo['tables'], 'page' ] );
231 $this->addJoinConds( [ ...$queryInfo['joins'], 'page' => [ 'JOIN', "{$this->bl_from}=page_id" ] ] );
232
233 if ( $resultPageSet === null ) {
234 $this->addFields( [ 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ] );
235 } else {
236 $this->addFields( $resultPageSet->getPageTableFields() );
237 }
238
239 $this->addFields( [ $this->bl_title, 'from_ns' => 'page_namespace' ] );
240 if ( $this->hasNS ) {
241 $this->addFields( $this->bl_ns );
242 }
243
244 // We can't use LinkBatch here because $this->hasNS may be false
245 $titleWhere = [];
246 $allRedirNs = [];
247 $allRedirDBkey = [];
249 foreach ( $this->redirTitles as $t ) {
250 $redirNs = $t->getNamespace();
251 $redirDBkey = $t->getDBkey();
252 $expr = $db->expr( $this->bl_title, '=', $redirDBkey );
253 if ( $this->hasNS ) {
254 $expr = $expr->and( $this->bl_ns, '=', $redirNs );
255 }
256 $titleWhere[] = $expr;
257 $allRedirNs[$redirNs] = true;
258 $allRedirDBkey[$redirDBkey] = true;
259 }
260 $this->addWhere( $db->orExpr( $titleWhere ) );
261 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
262
263 if ( count( $this->cont ) >= 6 ) {
264 $op = $this->params['dir'] == 'descending' ? '<=' : '>=';
265
266 $conds = [];
267 if ( $this->hasNS && count( $allRedirNs ) > 1 ) {
268 $conds[ $this->bl_ns ] = $this->cont[2];
269 }
270 if ( count( $allRedirDBkey ) > 1 ) {
271 $conds[ $this->bl_title ] = $this->cont[3];
272 }
273 // Don't bother with namespace, title, or from_namespace if it's
274 // otherwise constant in the where clause.
275 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
276 $conds[ $this->bl_from_ns ] = $this->cont[4];
277 }
278 $conds[ $this->bl_from ] = $this->cont[5];
279
280 $this->addWhere( $db->buildComparison( $op, $conds ) );
281 }
282 if ( $this->params['filterredir'] == 'redirects' ) {
283 $this->addWhereFld( 'page_is_redirect', 1 );
284 } elseif ( $this->params['filterredir'] == 'nonredirects' ) {
285 $this->addWhereFld( 'page_is_redirect', 0 );
286 }
287
288 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
289 $orderBy = [];
290 $sort = ( $this->params['dir'] == 'descending' ? ' DESC' : '' );
291 // Don't order by namespace/title/from_namespace if it's constant in the WHERE clause
292 if ( $this->hasNS && count( $allRedirNs ) > 1 ) {
293 $orderBy[] = $this->bl_ns . $sort;
294 }
295 if ( count( $allRedirDBkey ) > 1 ) {
296 $orderBy[] = $this->bl_title . $sort;
297 }
298 if ( $this->params['namespace'] !== null && count( $this->params['namespace'] ) > 1 ) {
299 $orderBy[] = $this->bl_from_ns . $sort;
300 }
301 $orderBy[] = $this->bl_from . $sort;
302 $this->addOption( 'ORDER BY', $orderBy );
303 $this->addOption( 'USE INDEX', [ 'page' => 'PRIMARY' ] );
304 // T290379: Avoid MariaDB deciding to scan all of `page`.
305 $this->addOption( 'STRAIGHT_JOIN' );
306
307 $res = $this->select( __METHOD__ );
308
309 if ( $resultPageSet === null ) {
310 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
311 }
312
313 $count = 0;
314 foreach ( $res as $row ) {
315 $ns = $this->hasNS ? $row->{$this->bl_ns} : NS_FILE;
316
317 if ( ++$count > $this->params['limit'] ) {
318 // We've reached the one extra which shows that there are
319 // additional pages to be had. Stop here...
320 // Note we must keep the parameters for the first query constant
321 // This may be overridden at a later step
322 $title = $row->{$this->bl_title};
323 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 2 ) ) .
324 "|$ns|$title|{$row->from_ns}|{$row->page_id}";
325 break;
326 }
327
328 // Fill in continuation fields for later steps
329 if ( count( $this->cont ) < 6 ) {
330 $this->cont[] = $ns;
331 $this->cont[] = $row->{$this->bl_title};
332 $this->cont[] = $row->from_ns;
333 $this->cont[] = $row->page_id;
334 }
335
336 if ( $resultPageSet === null ) {
337 $a = [ 'pageid' => (int)$row->page_id ];
338 ApiQueryBase::addTitleInfo( $a, Title::makeTitle( $row->page_namespace, $row->page_title ) );
339 if ( $row->page_is_redirect ) {
340 $a['redirect'] = true;
341 }
342 $parentID = $this->pageMap[$ns][$row->{$this->bl_title}];
343 // Put all the results in an array first
344 $this->resultArr[$parentID]['redirlinks'][$row->page_id] = $a;
345 } else {
346 $resultPageSet->processDbRow( $row );
347 }
348 }
349 }
350
355 private function run( $resultPageSet = null ) {
356 $this->params = $this->extractRequestParams( false );
357 $this->redirect = isset( $this->params['redirect'] ) && $this->params['redirect'];
358 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1 / 2 : ApiBase::LIMIT_BIG1 );
359 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2 / 2 : ApiBase::LIMIT_BIG2 );
360
361 $result = $this->getResult();
362
363 if ( $this->params['limit'] == 'max' ) {
364 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
365 $result->addParsedLimit( $this->getModuleName(), $this->params['limit'] );
366 } else {
367 $this->params['limit'] = $this->getMain()->getParamValidator()->validateValue(
368 $this, 'limit', (int)$this->params['limit'], [
369 ParamValidator::PARAM_TYPE => 'limit',
370 IntegerDef::PARAM_MIN => 1,
371 IntegerDef::PARAM_MAX => $userMax,
372 IntegerDef::PARAM_MAX2 => $botMax,
373 IntegerDef::PARAM_IGNORE_RANGE => true,
374 ]
375 );
376 }
377
378 $this->rootTitle = $this->getTitleFromTitleOrPageId( $this->params );
379
380 // only image titles are allowed for the root in imageinfo mode
381 if ( !$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE ) {
382 $this->dieWithError(
383 [ 'apierror-imageusage-badtitle', $this->getModuleName() ],
384 'bad_image_title'
385 );
386 }
387
388 // Parse and validate continuation parameter
389 // (Can't use parseContinueParamOrDie(), because the length is variable)
390 $this->cont = [];
391 if ( $this->params['continue'] !== null ) {
392 $cont = explode( '|', $this->params['continue'] );
393
394 switch ( count( $cont ) ) {
395 case 8:
396 // redirect page ID for result adding
397 $this->cont[7] = (int)$cont[7];
398 $this->dieContinueUsageIf( $cont[7] !== (string)$this->cont[7] );
399
400 /* Fall through */
401
402 case 7:
403 // top-level page ID for result adding
404 $this->cont[6] = (int)$cont[6];
405 $this->dieContinueUsageIf( $cont[6] !== (string)$this->cont[6] );
406
407 /* Fall through */
408
409 case 6:
410 // ns for 2nd query (even for imageusage)
411 $this->cont[2] = (int)$cont[2];
412 $this->dieContinueUsageIf( $cont[2] !== (string)$this->cont[2] );
413
414 // title for 2nd query
415 $this->cont[3] = $cont[3];
416
417 // from_ns for 2nd query
418 $this->cont[4] = (int)$cont[4];
419 $this->dieContinueUsageIf( $cont[4] !== (string)$this->cont[4] );
420
421 // from_id for 1st query
422 $this->cont[5] = (int)$cont[5];
423 $this->dieContinueUsageIf( $cont[5] !== (string)$this->cont[5] );
424
425 /* Fall through */
426
427 case 2:
428 // from_ns for 1st query
429 $this->cont[0] = (int)$cont[0];
430 $this->dieContinueUsageIf( $cont[0] !== (string)$this->cont[0] );
431
432 // from_id for 1st query
433 $this->cont[1] = (int)$cont[1];
434 $this->dieContinueUsageIf( $cont[1] !== (string)$this->cont[1] );
435
436 break;
437
438 default:
439 // @phan-suppress-next-line PhanImpossibleCondition
440 $this->dieContinueUsageIf( true );
441 }
442
443 ksort( $this->cont );
444 }
445
446 $this->runFirstQuery( $resultPageSet );
447 if ( $this->redirect && count( $this->redirTitles ) ) {
448 $this->resetQueryParams();
449 $this->runSecondQuery( $resultPageSet );
450 }
451
452 // Fill in any missing fields in case it's needed below
453 $this->cont += [ 0, 0, 0, '', 0, 0, 0 ];
454
455 if ( $resultPageSet === null ) {
456 // Try to add the result data in one go and pray that it fits
457 $code = $this->bl_code;
458 $data = array_map( static function ( $arr ) use ( $code ) {
459 if ( isset( $arr['redirlinks'] ) ) {
460 $arr['redirlinks'] = array_values( $arr['redirlinks'] );
461 ApiResult::setIndexedTagName( $arr['redirlinks'], $code );
462 }
463 return $arr;
464 }, array_values( $this->resultArr ) );
465 $fit = $result->addValue( 'query', $this->getModuleName(), $data );
466 if ( !$fit ) {
467 // It didn't fit. Add elements one by one until the
468 // result is full.
469 ksort( $this->resultArr );
470 // @phan-suppress-next-line PhanSuspiciousValueComparison
471 if ( count( $this->cont ) >= 7 ) {
472 $startAt = $this->cont[6];
473 } else {
474 $startAt = array_key_first( $this->resultArr );
475 }
476 $idx = 0;
477 foreach ( $this->resultArr as $pageID => $arr ) {
478 if ( $pageID < $startAt ) {
479 continue;
480 }
481
482 // Add the basic entry without redirlinks first
483 $fit = $result->addValue(
484 [ 'query', $this->getModuleName() ],
485 $idx, array_diff_key( $arr, [ 'redirlinks' => '' ] ) );
486 if ( !$fit ) {
487 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 6 ) ) .
488 "|$pageID";
489 break;
490 }
491
492 $hasRedirs = false;
493 $redirLinks = isset( $arr['redirlinks'] ) ? (array)$arr['redirlinks'] : [];
494 ksort( $redirLinks );
495 // @phan-suppress-next-line PhanSuspiciousValueComparisonInLoop
496 if ( count( $this->cont ) >= 8 && $pageID == $startAt ) {
497 $redirStartAt = $this->cont[7];
498 } else {
499 $redirStartAt = array_key_first( $redirLinks );
500 }
501 foreach ( $redirLinks as $key => $redir ) {
502 if ( $key < $redirStartAt ) {
503 continue;
504 }
505
506 $fit = $result->addValue(
507 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
508 null, $redir );
509 if ( !$fit ) {
510 $this->continueStr = implode( '|', array_slice( $this->cont, 0, 6 ) ) .
511 "|$pageID|$key";
512 break;
513 }
514 $hasRedirs = true;
515 }
516 if ( $hasRedirs ) {
517 $result->addIndexedTagName(
518 [ 'query', $this->getModuleName(), $idx, 'redirlinks' ],
519 $this->bl_code );
520 }
521 if ( !$fit ) {
522 break;
523 }
524
525 $idx++;
526 }
527 }
528
529 $result->addIndexedTagName(
530 [ 'query', $this->getModuleName() ],
531 $this->bl_code
532 );
533 }
534 if ( $this->continueStr !== null ) {
535 $this->setContinueEnumParameter( 'continue', $this->continueStr );
536 }
537 }
538
540 public function getAllowedParams() {
541 $retval = [
542 'title' => [
543 ParamValidator::PARAM_TYPE => 'string',
544 ],
545 'pageid' => [
546 ParamValidator::PARAM_TYPE => 'integer',
547 ],
548 'continue' => [
549 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
550 ],
551 'namespace' => [
552 ParamValidator::PARAM_ISMULTI => true,
553 ParamValidator::PARAM_TYPE => 'namespace'
554 ],
555 'dir' => [
556 ParamValidator::PARAM_DEFAULT => 'ascending',
557 ParamValidator::PARAM_TYPE => [
558 'ascending',
559 'descending'
560 ]
561 ],
562 'filterredir' => [
563 ParamValidator::PARAM_DEFAULT => 'all',
564 ParamValidator::PARAM_TYPE => [
565 'all',
566 'redirects',
567 'nonredirects'
568 ]
569 ],
570 'limit' => [
571 ParamValidator::PARAM_DEFAULT => 10,
572 ParamValidator::PARAM_TYPE => 'limit',
573 IntegerDef::PARAM_MIN => 1,
574 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
575 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
576 ]
577 ];
578 if ( $this->getModuleName() !== 'embeddedin' ) {
579 $retval['redirect'] = false;
580 }
581
582 return $retval;
583 }
584
586 protected function getExamplesMessages() {
587 $title = Title::newMainPage()->getPrefixedText();
588 $mp = rawurlencode( $title );
589 $examples = [
590 'backlinks' => [
591 "action=query&list=backlinks&bltitle={$mp}"
592 => 'apihelp-query+backlinks-example-simple',
593 "action=query&generator=backlinks&gbltitle={$mp}&prop=info"
594 => 'apihelp-query+backlinks-example-generator',
595 ],
596 'embeddedin' => [
597 'action=query&list=embeddedin&eititle=Template:Stub'
598 => 'apihelp-query+embeddedin-example-simple',
599 'action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
600 => 'apihelp-query+embeddedin-example-generator',
601 ],
602 'imageusage' => [
603 'action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg'
604 => 'apihelp-query+imageusage-example-simple',
605 'action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
606 => 'apihelp-query+imageusage-example-generator',
607 ]
608 ];
609
610 return $examples[$this->getModuleName()];
611 }
612
614 public function getHelpUrls() {
615 return $this->helpUrl;
616 }
617}
618
620class_alias( ApiQueryBacklinks::class, 'ApiQueryBacklinks' );
const NS_FILE
Definition Defines.php:57
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
resetVirtualDomain()
Reset the virtual domain to the main database.
setVirtualDomain(string|false $virtualDomain)
Set the Query database connection (read-only)
getDB()
Get the Query database connection (read-only).
select( $method, $extraQuery=[], ?array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addFields( $value)
Add a set of fields to select to the internal array.
This is the main query class.
Definition ApiQuery.php:36
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
Service for compat reading of links tables.
Represents a title within MediaWiki.
Definition Title.php:69
Service for formatting and validating API parameters.
Type definition for integer types.