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', '' );
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[] = $db->expr( $bl_title, '=', $t->getDBkey() );
252 }
253 }
254 $this->addWhere( $db->orExpr( $where ) );
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( $db->expr( 'rd_fragment', '!=', '' ), isset( $show['fragment'] ) );
266 $this->addWhereIf( [ 'rd_fragment' => '' ], isset( $show['!fragment'] ) );
267 $this->addWhereIf( [ 'page_is_redirect' => 1 ], isset( $show['redirect'] ) );
268 $this->addWhereIf( [ 'page_is_redirect' => 0 ], isset( $show['!redirect'] ) );
269 }
270
271 // Override any ORDER BY from above with what we calculated earlier.
272 $this->addOption( 'ORDER BY', array_keys( $sortby ) );
273
274 // MySQL's optimizer chokes if we have too many values in "$bl_title IN
275 // (...)" and chooses the wrong index, so specify the correct index to
276 // use for the query. See T139056 for details.
277 if ( !empty( $settings['indexes'] ) ) {
278 if (
279 $params['namespace'] !== null &&
280 count( $params['namespace'] ) == 1 &&
281 !empty( $settings['from_namespace'] )
282 ) {
283 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
284 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxWithFromNS ] );
285 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
286 } elseif ( !isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
287 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
288 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxNoFromNS ] );
289 }
290 }
291
292 $this->addOption( 'LIMIT', $params['limit'] + 1 );
293
294 $res = $this->select( __METHOD__ );
295
296 if ( $resultPageSet === null ) {
297 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
298 if ( $fld_title ) {
299 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
300 }
301
302 $count = 0;
303 foreach ( $res as $row ) {
304 if ( ++$count > $params['limit'] ) {
305 // We've reached the one extra which shows that
306 // there are additional pages to be had. Stop here...
307 $this->setContinue( $row, $sortby );
308 break;
309 }
310
311 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
312 // Miser mode namespace check
313 continue;
314 }
315
316 // Get the ID of the current page
317 $id = $map[$row->bl_namespace][$row->bl_title];
318
319 $vals = [];
320 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
321 if ( $fld_pageid ) {
322 $vals['pageid'] = (int)$row->page_id;
323 }
324 if ( $fld_title ) {
326 Title::makeTitle( $row->page_namespace, $row->page_title )
327 );
328 }
329 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
330 if ( $fld_fragment && $row->rd_fragment !== '' ) {
331 $vals['fragment'] = $row->rd_fragment;
332 }
333 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
334 if ( $fld_redirect ) {
335 $vals['redirect'] = (bool)$row->page_is_redirect;
336 }
337 $fit = $this->addPageSubItem( $id, $vals );
338 if ( !$fit ) {
339 $this->setContinue( $row, $sortby );
340 break;
341 }
342 }
343 } else {
344 $titles = [];
345 $count = 0;
346 foreach ( $res as $row ) {
347 if ( ++$count > $params['limit'] ) {
348 // We've reached the one extra which shows that
349 // there are additional pages to be had. Stop here...
350 $this->setContinue( $row, $sortby );
351 break;
352 }
353
354 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
355 // Miser mode namespace check
356 continue;
357 }
358
359 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
360 }
361 $resultPageSet->populateFromTitles( $titles );
362 }
363 }
364
365 private function setContinue( $row, $sortby ) {
366 $cont = [];
367 foreach ( $sortby as $field => $v ) {
368 $cont[] = $row->$field;
369 }
370 $this->setContinueEnumParameter( 'continue', implode( '|', $cont ) );
371 }
372
373 public function getCacheMode( $params ) {
374 return 'public';
375 }
376
377 public function getAllowedParams() {
378 $settings = self::$settings[$this->getModuleName()];
379
380 $ret = [
381 'prop' => [
382 ParamValidator::PARAM_TYPE => [
383 'pageid',
384 'title',
385 ],
386 ParamValidator::PARAM_ISMULTI => true,
387 ParamValidator::PARAM_DEFAULT => 'pageid|title',
389 ],
390 'namespace' => [
391 ParamValidator::PARAM_ISMULTI => true,
392 ParamValidator::PARAM_TYPE => 'namespace',
393 ],
394 'show' => null, // Will be filled/removed below
395 'limit' => [
396 ParamValidator::PARAM_DEFAULT => 10,
397 ParamValidator::PARAM_TYPE => 'limit',
398 IntegerDef::PARAM_MIN => 1,
399 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
400 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
401 ],
402 'continue' => [
403 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
404 ],
405 ];
406
407 if ( empty( $settings['from_namespace'] ) &&
408 $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
409 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
410 'api-help-param-limited-in-miser-mode',
411 ];
412 }
413
414 if ( !empty( $settings['showredirects'] ) ) {
415 $ret['prop'][ParamValidator::PARAM_TYPE][] = 'redirect';
416 $ret['prop'][ParamValidator::PARAM_DEFAULT] .= '|redirect';
417 }
418 if ( isset( $settings['props'] ) ) {
419 $ret['prop'][ParamValidator::PARAM_TYPE] = array_merge(
420 $ret['prop'][ParamValidator::PARAM_TYPE], $settings['props']
421 );
422 }
423
424 $show = [];
425 if ( !empty( $settings['showredirects'] ) ) {
426 $show[] = 'redirect';
427 $show[] = '!redirect';
428 }
429 if ( isset( $settings['show'] ) ) {
430 $show = array_merge( $show, $settings['show'] );
431 }
432 if ( $show ) {
433 $ret['show'] = [
434 ParamValidator::PARAM_TYPE => $show,
435 ParamValidator::PARAM_ISMULTI => true,
437 ];
438 } else {
439 unset( $ret['show'] );
440 }
441
442 return $ret;
443 }
444
445 protected function getExamplesMessages() {
446 $settings = self::$settings[$this->getModuleName()];
447 $name = $this->getModuleName();
448 $path = $this->getModulePath();
449 $title = $settings['exampletitle'] ?? Title::newMainPage()->getPrefixedText();
450 $etitle = rawurlencode( $title );
451
452 return [
453 "action=query&prop={$name}&titles={$etitle}"
454 => "apihelp-$path-example-simple",
455 "action=query&generator={$name}&titles={$etitle}&prop=info"
456 => "apihelp-$path-example-generator",
457 ];
458 }
459
460 public function getHelpUrls() {
461 $name = ucfirst( $this->getModuleName() );
462 return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
463 }
464}
const NS_FILE
Definition Defines.php:71
array $params
The job parameters.
run()
Run the job.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1540
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:179
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1731
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:212
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:237
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:821
getModulePath()
Get the path to this module.
Definition ApiBase.php:621
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:172
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:239
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:542
This class contains a list of pages that the client has requested.
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:79
Service for formatting and validating API parameters.
Type definition for integer types.