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