MediaWiki REL1_40
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
84 private $linksMigration;
85
91 public function __construct(
92 ApiQuery $query,
93 $moduleName,
94 LinksMigration $linksMigration
95 ) {
96 parent::__construct( $query, $moduleName, self::$settings[$moduleName]['code'] );
97 $this->linksMigration = $linksMigration;
98 }
99
100 public function execute() {
101 $this->run();
102 }
103
104 public function executeGenerator( $resultPageSet ) {
105 $this->run( $resultPageSet );
106 }
107
111 private function run( ApiPageSet $resultPageSet = null ) {
112 $settings = self::$settings[$this->getModuleName()];
113
114 $db = $this->getDB();
115 $params = $this->extractRequestParams();
116 $prop = array_fill_keys( $params['prop'], true );
117 $emptyString = $db->addQuotes( '' );
118
119 $pageSet = $this->getPageSet();
120 $titles = $pageSet->getGoodAndMissingPages();
121 $map = $pageSet->getGoodAndMissingTitlesByNamespace();
122
123 // Add in special pages, they can theoretically have backlinks too.
124 // (although currently they only do for prop=redirects)
125 foreach ( $pageSet->getSpecialPages() as $id => $title ) {
126 $titles[] = $title;
127 $map[$title->getNamespace()][$title->getDBkey()] = $id;
128 }
129
130 // Determine our fields to query on
131 $p = $settings['prefix'];
132 $hasNS = !isset( $settings['to_namespace'] );
133 if ( $hasNS ) {
134 if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
135 [ $bl_namespace, $bl_title ] = $this->linksMigration->getTitleFields( $settings['linktable'] );
136 } else {
137 $bl_namespace = "{$p}_namespace";
138 $bl_title = "{$p}_title";
139 }
140 } else {
141 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
142 $bl_namespace = $settings['to_namespace'];
143 $bl_title = "{$p}_to";
144
145 $titles = array_filter( $titles, static function ( $t ) use ( $bl_namespace ) {
146 return $t->getNamespace() === $bl_namespace;
147 } );
148 $map = array_intersect_key( $map, [ $bl_namespace => true ] );
149 }
150 $bl_from = "{$p}_from";
151
152 if ( !$titles ) {
153 return; // nothing to do
154 }
155 if ( $params['namespace'] !== null && count( $params['namespace'] ) === 0 ) {
156 return; // nothing to do
157 }
158
159 // Figure out what we're sorting by, and add associated WHERE clauses.
160 // MySQL's query planner screws up if we include a field in ORDER BY
161 // when it's constant in WHERE, so we have to test that for each field.
162 $sortby = [];
163 if ( $hasNS && count( $map ) > 1 ) {
164 $sortby[$bl_namespace] = 'int';
165 }
166 $theTitle = null;
167 foreach ( $map as $nsTitles ) {
168 $key = array_key_first( $nsTitles );
169 $theTitle ??= $key;
170 if ( count( $nsTitles ) > 1 || $key !== $theTitle ) {
171 $sortby[$bl_title] = 'string';
172 break;
173 }
174 }
175 $miser_ns = null;
176 if ( $params['namespace'] !== null ) {
177 if ( empty( $settings['from_namespace'] ) ) {
178 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
179 $miser_ns = $params['namespace'];
180 } else {
181 $this->addWhereFld( 'page_namespace', $params['namespace'] );
182 }
183 } else {
184 $this->addWhereFld( "{$p}_from_namespace", $params['namespace'] );
185 if ( !empty( $settings['from_namespace'] )
186 && $params['namespace'] !== null && count( $params['namespace'] ) > 1
187 ) {
188 $sortby["{$p}_from_namespace"] = 'int';
189 }
190 }
191 }
192 $sortby[$bl_from] = 'int';
193
194 // Now use the $sortby to figure out the continuation
195 $continueFields = array_keys( $sortby );
196 $continueTypes = array_values( $sortby );
197 if ( $params['continue'] !== null ) {
198 $continueValues = $this->parseContinueParamOrDie( $params['continue'], $continueTypes );
199 $conds = array_combine( $continueFields, $continueValues );
200 $this->addWhere( $db->buildComparison( '>=', $conds ) );
201 }
202
203 // Populate the rest of the query
204 [ $idxNoFromNS, $idxWithFromNS ] = $settings['indexes'] ?? [ '', '' ];
205 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
206 if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
207 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
208 $queryInfo = $this->linksMigration->getQueryInfo( $settings['linktable'] );
209 $this->addTables( array_merge( [ 'page' ], $queryInfo['tables'] ) );
210 $this->addJoinConds( $queryInfo['joins'] );
211 // TODO: Move to links migration
212 if ( in_array( 'linktarget', $queryInfo['tables'] ) ) {
213 $idxWithFromNS .= '_target_id';
214 }
215 } else {
216 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
217 $this->addTables( [ $settings['linktable'], 'page' ] );
218 }
219 $this->addWhere( "$bl_from = page_id" );
220
221 if ( $this->getModuleName() === 'redirects' ) {
222 $this->addWhere( "rd_interwiki = $emptyString OR rd_interwiki IS NULL" );
223 }
224
225 $this->addFields( array_keys( $sortby ) );
226 $this->addFields( [ 'bl_namespace' => $bl_namespace, 'bl_title' => $bl_title ] );
227 if ( $resultPageSet === null ) {
228 $fld_pageid = isset( $prop['pageid'] );
229 $fld_title = isset( $prop['title'] );
230 $fld_redirect = isset( $prop['redirect'] );
231
232 $this->addFieldsIf( 'page_id', $fld_pageid );
233 $this->addFieldsIf( [ 'page_title', 'page_namespace' ], $fld_title );
234 $this->addFieldsIf( 'page_is_redirect', $fld_redirect );
235
236 // prop=redirects
237 $fld_fragment = isset( $prop['fragment'] );
238 $this->addFieldsIf( 'rd_fragment', $fld_fragment );
239 } else {
240 $this->addFields( $resultPageSet->getPageTableFields() );
241 }
242
243 $this->addFieldsIf( 'page_namespace', $miser_ns !== null );
244
245 if ( $hasNS ) {
246 // Can't use LinkBatch because it throws away Special titles.
247 // And we already have the needed data structure anyway.
248 $this->addWhere( $db->makeWhereFrom2d( $map, $bl_namespace, $bl_title ) );
249 } else {
250 $where = [];
251 foreach ( $titles as $t ) {
252 if ( $t->getNamespace() == $bl_namespace ) {
253 $where[] = "$bl_title = " . $db->addQuotes( $t->getDBkey() );
254 }
255 }
256 $this->addWhere( $db->makeList( $where, LIST_OR ) );
257 }
258
259 if ( $params['show'] !== null ) {
260 // prop=redirects only
261 $show = array_fill_keys( $params['show'], true );
262 if ( isset( $show['fragment'] ) && isset( $show['!fragment'] ) ||
263 isset( $show['redirect'] ) && isset( $show['!redirect'] )
264 ) {
265 $this->dieWithError( 'apierror-show' );
266 }
267 $this->addWhereIf( "rd_fragment != $emptyString", isset( $show['fragment'] ) );
268 $this->addWhereIf(
269 "rd_fragment = $emptyString OR rd_fragment IS NULL",
270 isset( $show['!fragment'] )
271 );
272 $this->addWhereIf( [ 'page_is_redirect' => 1 ], isset( $show['redirect'] ) );
273 $this->addWhereIf( [ 'page_is_redirect' => 0 ], isset( $show['!redirect'] ) );
274 }
275
276 // Override any ORDER BY from above with what we calculated earlier.
277 $this->addOption( 'ORDER BY', array_keys( $sortby ) );
278
279 // MySQL's optimizer chokes if we have too many values in "$bl_title IN
280 // (...)" and chooses the wrong index, so specify the correct index to
281 // use for the query. See T139056 for details.
282 if ( !empty( $settings['indexes'] ) ) {
283 if ( $params['namespace'] !== null && !empty( $settings['from_namespace'] ) ) {
284 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
285 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxWithFromNS ] );
286 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
287 } elseif ( !isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
288 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
289 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxNoFromNS ] );
290 }
291 }
292
293 $this->addOption( 'LIMIT', $params['limit'] + 1 );
294
295 $res = $this->select( __METHOD__ );
296
297 if ( $resultPageSet === null ) {
298 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
299 if ( $fld_title ) {
300 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
301 }
302
303 $count = 0;
304 foreach ( $res as $row ) {
305 if ( ++$count > $params['limit'] ) {
306 // We've reached the one extra which shows that
307 // there are additional pages to be had. Stop here...
308 $this->setContinue( $row, $sortby );
309 break;
310 }
311
312 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
313 // Miser mode namespace check
314 continue;
315 }
316
317 // Get the ID of the current page
318 $id = $map[$row->bl_namespace][$row->bl_title];
319
320 $vals = [];
321 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
322 if ( $fld_pageid ) {
323 $vals['pageid'] = (int)$row->page_id;
324 }
325 if ( $fld_title ) {
327 Title::makeTitle( $row->page_namespace, $row->page_title )
328 );
329 }
330 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
331 if ( $fld_fragment && $row->rd_fragment !== null && $row->rd_fragment !== '' ) {
332 $vals['fragment'] = $row->rd_fragment;
333 }
334 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
335 if ( $fld_redirect ) {
336 $vals['redirect'] = (bool)$row->page_is_redirect;
337 }
338 $fit = $this->addPageSubItem( $id, $vals );
339 if ( !$fit ) {
340 $this->setContinue( $row, $sortby );
341 break;
342 }
343 }
344 } else {
345 $titles = [];
346 $count = 0;
347 foreach ( $res as $row ) {
348 if ( ++$count > $params['limit'] ) {
349 // We've reached the one extra which shows that
350 // there are additional pages to be had. Stop here...
351 $this->setContinue( $row, $sortby );
352 break;
353 }
354
355 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
356 // Miser mode namespace check
357 continue;
358 }
359
360 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
361 }
362 $resultPageSet->populateFromTitles( $titles );
363 }
364 }
365
366 private function setContinue( $row, $sortby ) {
367 $cont = [];
368 foreach ( $sortby as $field => $v ) {
369 $cont[] = $row->$field;
370 }
371 $this->setContinueEnumParameter( 'continue', implode( '|', $cont ) );
372 }
373
374 public function getCacheMode( $params ) {
375 return 'public';
376 }
377
378 public function getAllowedParams() {
379 $settings = self::$settings[$this->getModuleName()];
380
381 $ret = [
382 'prop' => [
383 ParamValidator::PARAM_TYPE => [
384 'pageid',
385 'title',
386 ],
387 ParamValidator::PARAM_ISMULTI => true,
388 ParamValidator::PARAM_DEFAULT => 'pageid|title',
390 ],
391 'namespace' => [
392 ParamValidator::PARAM_ISMULTI => true,
393 ParamValidator::PARAM_TYPE => 'namespace',
394 ],
395 'show' => null, // Will be filled/removed below
396 'limit' => [
397 ParamValidator::PARAM_DEFAULT => 10,
398 ParamValidator::PARAM_TYPE => 'limit',
399 IntegerDef::PARAM_MIN => 1,
400 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
401 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
402 ],
403 'continue' => [
404 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
405 ],
406 ];
407
408 if ( empty( $settings['from_namespace'] ) &&
409 $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
410 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
411 'api-help-param-limited-in-miser-mode',
412 ];
413 }
414
415 if ( !empty( $settings['showredirects'] ) ) {
416 $ret['prop'][ParamValidator::PARAM_TYPE][] = 'redirect';
417 $ret['prop'][ParamValidator::PARAM_DEFAULT] .= '|redirect';
418 }
419 if ( isset( $settings['props'] ) ) {
420 $ret['prop'][ParamValidator::PARAM_TYPE] = array_merge(
421 $ret['prop'][ParamValidator::PARAM_TYPE], $settings['props']
422 );
423 }
424
425 $show = [];
426 if ( !empty( $settings['showredirects'] ) ) {
427 $show[] = 'redirect';
428 $show[] = '!redirect';
429 }
430 if ( isset( $settings['show'] ) ) {
431 $show = array_merge( $show, $settings['show'] );
432 }
433 if ( $show ) {
434 $ret['show'] = [
435 ParamValidator::PARAM_TYPE => $show,
436 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'] ?? Title::newMainPage()->getPrefixedText();
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:1460
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:173
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1649
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:204
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:229
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:773
getModulePath()
Get the path to this module.
Definition ApiBase.php:581
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:166
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:231
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:506
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:42
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:82
Service for formatting and validating API parameters.
Type definition for integer types.