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