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