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