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