MediaWiki  master
ApiQueryBacklinksprop.php
Go to the documentation of this file.
1 <?php
31 
40 
42  private static $settings = [
43  'redirects' => [
44  'code' => 'rd',
45  'prefix' => 'rd',
46  'linktable' => 'redirect',
47  'props' => [
48  'fragment',
49  ],
50  'showredirects' => false,
51  'show' => [
52  'fragment',
53  '!fragment',
54  ],
55  ],
56  'linkshere' => [
57  'code' => 'lh',
58  'prefix' => 'pl',
59  'linktable' => 'pagelinks',
60  'indexes' => [ 'pl_namespace', 'pl_backlinks_namespace' ],
61  'from_namespace' => true,
62  'showredirects' => true,
63  ],
64  'transcludedin' => [
65  'code' => 'ti',
66  'prefix' => 'tl',
67  'linktable' => 'templatelinks',
68  'from_namespace' => true,
69  'showredirects' => true,
70  ],
71  'fileusage' => [
72  'code' => 'fu',
73  'prefix' => 'il',
74  'linktable' => 'imagelinks',
75  'indexes' => [ 'il_to', 'il_backlinks_namespace' ],
76  'from_namespace' => true,
77  'to_namespace' => NS_FILE,
78  'exampletitle' => 'File:Example.jpg',
79  'showredirects' => true,
80  ],
81  ];
82 
83  private LinksMigration $linksMigration;
84 
90  public function __construct(
91  ApiQuery $query,
92  $moduleName,
93  LinksMigration $linksMigration
94  ) {
95  parent::__construct( $query, $moduleName, self::$settings[$moduleName]['code'] );
96  $this->linksMigration = $linksMigration;
97  }
98 
99  public function execute() {
100  $this->run();
101  }
102 
103  public function executeGenerator( $resultPageSet ) {
104  $this->run( $resultPageSet );
105  }
106 
110  private function run( ApiPageSet $resultPageSet = null ) {
111  $settings = self::$settings[$this->getModuleName()];
112 
113  $db = $this->getDB();
114  $params = $this->extractRequestParams();
115  $prop = array_fill_keys( $params['prop'], true );
116 
117  $pageSet = $this->getPageSet();
118  $titles = $pageSet->getGoodAndMissingPages();
119  $map = $pageSet->getGoodAndMissingTitlesByNamespace();
120 
121  // Add in special pages, they can theoretically have backlinks too.
122  // (although currently they only do for prop=redirects)
123  foreach ( $pageSet->getSpecialPages() as $id => $title ) {
124  $titles[] = $title;
125  $map[$title->getNamespace()][$title->getDBkey()] = $id;
126  }
127 
128  // Determine our fields to query on
129  $p = $settings['prefix'];
130  $hasNS = !isset( $settings['to_namespace'] );
131  if ( $hasNS ) {
132  if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
133  [ $bl_namespace, $bl_title ] = $this->linksMigration->getTitleFields( $settings['linktable'] );
134  } else {
135  $bl_namespace = "{$p}_namespace";
136  $bl_title = "{$p}_title";
137  }
138  } else {
139  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
140  $bl_namespace = $settings['to_namespace'];
141  $bl_title = "{$p}_to";
142 
143  $titles = array_filter( $titles, static function ( $t ) use ( $bl_namespace ) {
144  return $t->getNamespace() === $bl_namespace;
145  } );
146  $map = array_intersect_key( $map, [ $bl_namespace => true ] );
147  }
148  $bl_from = "{$p}_from";
149 
150  if ( !$titles ) {
151  return; // nothing to do
152  }
153  if ( $params['namespace'] !== null && count( $params['namespace'] ) === 0 ) {
154  return; // nothing to do
155  }
156 
157  // Figure out what we're sorting by, and add associated WHERE clauses.
158  // MySQL's query planner screws up if we include a field in ORDER BY
159  // when it's constant in WHERE, so we have to test that for each field.
160  $sortby = [];
161  if ( $hasNS && count( $map ) > 1 ) {
162  $sortby[$bl_namespace] = 'int';
163  }
164  $theTitle = null;
165  foreach ( $map as $nsTitles ) {
166  $key = array_key_first( $nsTitles );
167  $theTitle ??= $key;
168  if ( count( $nsTitles ) > 1 || $key !== $theTitle ) {
169  $sortby[$bl_title] = 'string';
170  break;
171  }
172  }
173  $miser_ns = null;
174  if ( $params['namespace'] !== null ) {
175  if ( empty( $settings['from_namespace'] ) ) {
176  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
177  $miser_ns = $params['namespace'];
178  } else {
179  $this->addWhereFld( 'page_namespace', $params['namespace'] );
180  }
181  } else {
182  $this->addWhereFld( "{$p}_from_namespace", $params['namespace'] );
183  if ( !empty( $settings['from_namespace'] )
184  && $params['namespace'] !== null && count( $params['namespace'] ) > 1
185  ) {
186  $sortby["{$p}_from_namespace"] = 'int';
187  }
188  }
189  }
190  $sortby[$bl_from] = 'int';
191 
192  // Now use the $sortby to figure out the continuation
193  $continueFields = array_keys( $sortby );
194  $continueTypes = array_values( $sortby );
195  if ( $params['continue'] !== null ) {
196  $continueValues = $this->parseContinueParamOrDie( $params['continue'], $continueTypes );
197  $conds = array_combine( $continueFields, $continueValues );
198  $this->addWhere( $db->buildComparison( '>=', $conds ) );
199  }
200 
201  // Populate the rest of the query
202  [ $idxNoFromNS, $idxWithFromNS ] = $settings['indexes'] ?? [ '', '' ];
203  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
204  if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
205  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
206  $queryInfo = $this->linksMigration->getQueryInfo( $settings['linktable'] );
207  $this->addTables( array_merge( [ 'page' ], $queryInfo['tables'] ) );
208  $this->addJoinConds( $queryInfo['joins'] );
209  // TODO: Move to links migration
210  if ( in_array( 'linktarget', $queryInfo['tables'] ) ) {
211  $idxWithFromNS .= '_target_id';
212  }
213  } else {
214  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
215  $this->addTables( [ $settings['linktable'], 'page' ] );
216  }
217  $this->addWhere( "$bl_from = page_id" );
218 
219  if ( $this->getModuleName() === 'redirects' ) {
220  $this->addWhereFld( 'rd_interwiki', [ '', null ] );
221  }
222 
223  $this->addFields( array_keys( $sortby ) );
224  $this->addFields( [ 'bl_namespace' => $bl_namespace, 'bl_title' => $bl_title ] );
225  if ( $resultPageSet === null ) {
226  $fld_pageid = isset( $prop['pageid'] );
227  $fld_title = isset( $prop['title'] );
228  $fld_redirect = isset( $prop['redirect'] );
229 
230  $this->addFieldsIf( 'page_id', $fld_pageid );
231  $this->addFieldsIf( [ 'page_title', 'page_namespace' ], $fld_title );
232  $this->addFieldsIf( 'page_is_redirect', $fld_redirect );
233 
234  // prop=redirects
235  $fld_fragment = isset( $prop['fragment'] );
236  $this->addFieldsIf( 'rd_fragment', $fld_fragment );
237  } else {
238  $this->addFields( $resultPageSet->getPageTableFields() );
239  }
240 
241  $this->addFieldsIf( 'page_namespace', $miser_ns !== null );
242 
243  if ( $hasNS && $map ) {
244  // Can't use LinkBatch because it throws away Special titles.
245  // And we already have the needed data structure anyway.
246  $this->addWhere( $db->makeWhereFrom2d( $map, $bl_namespace, $bl_title ) );
247  } else {
248  $where = [];
249  foreach ( $titles as $t ) {
250  if ( $t->getNamespace() == $bl_namespace ) {
251  $where[] = "$bl_title = " . $db->addQuotes( $t->getDBkey() );
252  }
253  }
254  $this->addWhere( $db->makeList( $where, LIST_OR ) );
255  }
256 
257  if ( $params['show'] !== null ) {
258  // prop=redirects only
259  $show = array_fill_keys( $params['show'], true );
260  if ( isset( $show['fragment'] ) && isset( $show['!fragment'] ) ||
261  isset( $show['redirect'] ) && isset( $show['!redirect'] )
262  ) {
263  $this->dieWithError( 'apierror-show' );
264  }
265  $this->addWhereIf( "rd_fragment != " . $db->addQuotes( '' ), isset( $show['fragment'] ) );
266  $this->addWhereIf(
267  [ 'rd_fragment' => [ '', null ] ],
268  isset( $show['!fragment'] )
269  );
270  $this->addWhereIf( [ 'page_is_redirect' => 1 ], isset( $show['redirect'] ) );
271  $this->addWhereIf( [ 'page_is_redirect' => 0 ], isset( $show['!redirect'] ) );
272  }
273 
274  // Override any ORDER BY from above with what we calculated earlier.
275  $this->addOption( 'ORDER BY', array_keys( $sortby ) );
276 
277  // MySQL's optimizer chokes if we have too many values in "$bl_title IN
278  // (...)" and chooses the wrong index, so specify the correct index to
279  // use for the query. See T139056 for details.
280  if ( !empty( $settings['indexes'] ) ) {
281  if ( $params['namespace'] !== null && !empty( $settings['from_namespace'] ) ) {
282  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
283  $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxWithFromNS ] );
284  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
285  } elseif ( !isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
286  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
287  $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxNoFromNS ] );
288  }
289  }
290 
291  $this->addOption( 'LIMIT', $params['limit'] + 1 );
292 
293  $res = $this->select( __METHOD__ );
294 
295  if ( $resultPageSet === null ) {
296  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
297  if ( $fld_title ) {
298  $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
299  }
300 
301  $count = 0;
302  foreach ( $res as $row ) {
303  if ( ++$count > $params['limit'] ) {
304  // We've reached the one extra which shows that
305  // there are additional pages to be had. Stop here...
306  $this->setContinue( $row, $sortby );
307  break;
308  }
309 
310  if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
311  // Miser mode namespace check
312  continue;
313  }
314 
315  // Get the ID of the current page
316  $id = $map[$row->bl_namespace][$row->bl_title];
317 
318  $vals = [];
319  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
320  if ( $fld_pageid ) {
321  $vals['pageid'] = (int)$row->page_id;
322  }
323  if ( $fld_title ) {
325  Title::makeTitle( $row->page_namespace, $row->page_title )
326  );
327  }
328  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
329  if ( $fld_fragment && $row->rd_fragment !== null && $row->rd_fragment !== '' ) {
330  $vals['fragment'] = $row->rd_fragment;
331  }
332  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
333  if ( $fld_redirect ) {
334  $vals['redirect'] = (bool)$row->page_is_redirect;
335  }
336  $fit = $this->addPageSubItem( $id, $vals );
337  if ( !$fit ) {
338  $this->setContinue( $row, $sortby );
339  break;
340  }
341  }
342  } else {
343  $titles = [];
344  $count = 0;
345  foreach ( $res as $row ) {
346  if ( ++$count > $params['limit'] ) {
347  // We've reached the one extra which shows that
348  // there are additional pages to be had. Stop here...
349  $this->setContinue( $row, $sortby );
350  break;
351  }
352 
353  if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
354  // Miser mode namespace check
355  continue;
356  }
357 
358  $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
359  }
360  $resultPageSet->populateFromTitles( $titles );
361  }
362  }
363 
364  private function setContinue( $row, $sortby ) {
365  $cont = [];
366  foreach ( $sortby as $field => $v ) {
367  $cont[] = $row->$field;
368  }
369  $this->setContinueEnumParameter( 'continue', implode( '|', $cont ) );
370  }
371 
372  public function getCacheMode( $params ) {
373  return 'public';
374  }
375 
376  public function getAllowedParams() {
377  $settings = self::$settings[$this->getModuleName()];
378 
379  $ret = [
380  'prop' => [
381  ParamValidator::PARAM_TYPE => [
382  'pageid',
383  'title',
384  ],
385  ParamValidator::PARAM_ISMULTI => true,
386  ParamValidator::PARAM_DEFAULT => 'pageid|title',
388  ],
389  'namespace' => [
390  ParamValidator::PARAM_ISMULTI => true,
391  ParamValidator::PARAM_TYPE => 'namespace',
392  ],
393  'show' => null, // Will be filled/removed below
394  'limit' => [
395  ParamValidator::PARAM_DEFAULT => 10,
396  ParamValidator::PARAM_TYPE => 'limit',
397  IntegerDef::PARAM_MIN => 1,
398  IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
399  IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
400  ],
401  'continue' => [
402  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
403  ],
404  ];
405 
406  if ( empty( $settings['from_namespace'] ) &&
407  $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
408  $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
409  'api-help-param-limited-in-miser-mode',
410  ];
411  }
412 
413  if ( !empty( $settings['showredirects'] ) ) {
414  $ret['prop'][ParamValidator::PARAM_TYPE][] = 'redirect';
415  $ret['prop'][ParamValidator::PARAM_DEFAULT] .= '|redirect';
416  }
417  if ( isset( $settings['props'] ) ) {
418  $ret['prop'][ParamValidator::PARAM_TYPE] = array_merge(
419  $ret['prop'][ParamValidator::PARAM_TYPE], $settings['props']
420  );
421  }
422 
423  $show = [];
424  if ( !empty( $settings['showredirects'] ) ) {
425  $show[] = 'redirect';
426  $show[] = '!redirect';
427  }
428  if ( isset( $settings['show'] ) ) {
429  $show = array_merge( $show, $settings['show'] );
430  }
431  if ( $show ) {
432  $ret['show'] = [
433  ParamValidator::PARAM_TYPE => $show,
434  ParamValidator::PARAM_ISMULTI => true,
436  ];
437  } else {
438  unset( $ret['show'] );
439  }
440 
441  return $ret;
442  }
443 
444  protected function getExamplesMessages() {
445  $settings = self::$settings[$this->getModuleName()];
446  $name = $this->getModuleName();
447  $path = $this->getModulePath();
448  $title = $settings['exampletitle'] ?? Title::newMainPage()->getPrefixedText();
449  $etitle = rawurlencode( $title );
450 
451  return [
452  "action=query&prop={$name}&titles={$etitle}"
453  => "apihelp-$path-example-simple",
454  "action=query&generator={$name}&titles={$etitle}&prop=info"
455  => "apihelp-$path-example-generator",
456  ];
457  }
458 
459  public function getHelpUrls() {
460  $name = ucfirst( $this->getModuleName() );
461  return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
462  }
463 }
const NS_FILE
Definition: Defines.php:70
const LIST_OR
Definition: Defines.php:46
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1516
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:177
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition: ApiBase.php:1718
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition: ApiBase.php:210
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:235
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:808
getModulePath()
Get the path to this module.
Definition: ApiBase.php:608
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:170
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:237
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:529
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:55
This implements prop=redirects, prop=linkshere, prop=catmembers, prop=transcludedin,...
executeGenerator( $resultPageSet)
Execute this module as a generator.
getHelpUrls()
Return links to more detailed help pages about the module.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getExamplesMessages()
Returns usage examples for this module.
__construct(ApiQuery $query, $moduleName, LinksMigration $linksMigration)
getCacheMode( $params)
Get the cache mode for the data generated by this module.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
addFields( $value)
Add a set of fields to select to the internal array.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
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.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
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.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
getPageSet()
Get the PageSet object to work on.
This is the main query class.
Definition: ApiQuery.php:43
Service for compat reading of links tables.
A class containing constants representing the names of configuration variables.
Represents a title within MediaWiki.
Definition: Title.php:76
Service for formatting and validating API parameters.
Type definition for integer types.
Definition: IntegerDef.php:23