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