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