MediaWiki REL1_39
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 list( $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] = 'ns';
164 }
165 $theTitle = null;
166 foreach ( $map as $nsTitles ) {
167 reset( $nsTitles );
168 $key = key( $nsTitles );
169 if ( $theTitle === null ) {
170 $theTitle = $key;
171 }
172 if ( count( $nsTitles ) > 1 || $key !== $theTitle ) {
173 $sortby[$bl_title] = 'title';
174 break;
175 }
176 }
177 $miser_ns = null;
178 if ( $params['namespace'] !== null ) {
179 if ( empty( $settings['from_namespace'] ) ) {
180 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
181 $miser_ns = $params['namespace'];
182 } else {
183 $this->addWhereFld( 'page_namespace', $params['namespace'] );
184 }
185 } else {
186 $this->addWhereFld( "{$p}_from_namespace", $params['namespace'] );
187 if ( !empty( $settings['from_namespace'] )
188 && $params['namespace'] !== null && count( $params['namespace'] ) > 1
189 ) {
190 $sortby["{$p}_from_namespace"] = 'int';
191 }
192 }
193 }
194 $sortby[$bl_from] = 'int';
195
196 // Now use the $sortby to figure out the continuation
197 if ( $params['continue'] !== null ) {
198 $cont = explode( '|', $params['continue'] );
199 $this->dieContinueUsageIf( count( $cont ) != count( $sortby ) );
200 $where = '';
201 $i = count( $sortby ) - 1;
202 foreach ( array_reverse( $sortby, true ) as $field => $type ) {
203 $v = $cont[$i];
204 switch ( $type ) {
205 case 'ns':
206 case 'int':
207 $v = (int)$v;
208 $this->dieContinueUsageIf( $v != $cont[$i] );
209 break;
210 default:
211 $v = $db->addQuotes( $v );
212 break;
213 }
214
215 if ( $where === '' ) {
216 $where = "$field >= $v";
217 } else {
218 $where = "$field > $v OR ($field = $v AND ($where))";
219 }
220
221 $i--;
222 }
223 $this->addWhere( $where );
224 }
225
226 // Populate the rest of the query
227 list( $idxNoFromNS, $idxWithFromNS ) = $settings['indexes'] ?? [ '', '' ];
228 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
229 if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
230 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
231 $queryInfo = $this->linksMigration->getQueryInfo( $settings['linktable'] );
232 $this->addTables( array_merge( [ 'page' ], $queryInfo['tables'] ) );
233 $this->addJoinConds( $queryInfo['joins'] );
234 // TODO: Move to links migration
235 if ( in_array( 'linktarget', $queryInfo['tables'] ) ) {
236 $idxWithFromNS .= '_target_id';
237 }
238 } else {
239 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
240 $this->addTables( [ $settings['linktable'], 'page' ] );
241 }
242 $this->addWhere( "$bl_from = page_id" );
243
244 if ( $this->getModuleName() === 'redirects' ) {
245 $this->addWhere( "rd_interwiki = $emptyString OR rd_interwiki IS NULL" );
246 }
247
248 $this->addFields( array_keys( $sortby ) );
249 $this->addFields( [ 'bl_namespace' => $bl_namespace, 'bl_title' => $bl_title ] );
250 if ( $resultPageSet === null ) {
251 $fld_pageid = isset( $prop['pageid'] );
252 $fld_title = isset( $prop['title'] );
253 $fld_redirect = isset( $prop['redirect'] );
254
255 $this->addFieldsIf( 'page_id', $fld_pageid );
256 $this->addFieldsIf( [ 'page_title', 'page_namespace' ], $fld_title );
257 $this->addFieldsIf( 'page_is_redirect', $fld_redirect );
258
259 // prop=redirects
260 $fld_fragment = isset( $prop['fragment'] );
261 $this->addFieldsIf( 'rd_fragment', $fld_fragment );
262 } else {
263 $this->addFields( $resultPageSet->getPageTableFields() );
264 }
265
266 $this->addFieldsIf( 'page_namespace', $miser_ns !== null );
267
268 if ( $hasNS ) {
269 // Can't use LinkBatch because it throws away Special titles.
270 // And we already have the needed data structure anyway.
271 $this->addWhere( $db->makeWhereFrom2d( $map, $bl_namespace, $bl_title ) );
272 } else {
273 $where = [];
274 foreach ( $titles as $t ) {
275 if ( $t->getNamespace() == $bl_namespace ) {
276 $where[] = "$bl_title = " . $db->addQuotes( $t->getDBkey() );
277 }
278 }
279 $this->addWhere( $db->makeList( $where, LIST_OR ) );
280 }
281
282 if ( $params['show'] !== null ) {
283 // prop=redirects only
284 $show = array_fill_keys( $params['show'], true );
285 if ( isset( $show['fragment'] ) && isset( $show['!fragment'] ) ||
286 isset( $show['redirect'] ) && isset( $show['!redirect'] )
287 ) {
288 $this->dieWithError( 'apierror-show' );
289 }
290 $this->addWhereIf( "rd_fragment != $emptyString", isset( $show['fragment'] ) );
291 $this->addWhereIf(
292 "rd_fragment = $emptyString OR rd_fragment IS NULL",
293 isset( $show['!fragment'] )
294 );
295 $this->addWhereIf( [ 'page_is_redirect' => 1 ], isset( $show['redirect'] ) );
296 $this->addWhereIf( [ 'page_is_redirect' => 0 ], isset( $show['!redirect'] ) );
297 }
298
299 // Override any ORDER BY from above with what we calculated earlier.
300 $this->addOption( 'ORDER BY', array_keys( $sortby ) );
301
302 // MySQL's optimizer chokes if we have too many values in "$bl_title IN
303 // (...)" and chooses the wrong index, so specify the correct index to
304 // use for the query. See T139056 for details.
305 if ( !empty( $settings['indexes'] ) ) {
306 if ( $params['namespace'] !== null && !empty( $settings['from_namespace'] ) ) {
307 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
308 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxWithFromNS ] );
309 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
310 } elseif ( !isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
311 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
312 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $idxNoFromNS ] );
313 }
314 }
315
316 $this->addOption( 'LIMIT', $params['limit'] + 1 );
317
318 $res = $this->select( __METHOD__ );
319
320 if ( $resultPageSet === null ) {
321 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
322 if ( $fld_title ) {
323 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
324 }
325
326 $count = 0;
327 foreach ( $res as $row ) {
328 if ( ++$count > $params['limit'] ) {
329 // We've reached the one extra which shows that
330 // there are additional pages to be had. Stop here...
331 $this->setContinue( $row, $sortby );
332 break;
333 }
334
335 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
336 // Miser mode namespace check
337 continue;
338 }
339
340 // Get the ID of the current page
341 $id = $map[$row->bl_namespace][$row->bl_title];
342
343 $vals = [];
344 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
345 if ( $fld_pageid ) {
346 $vals['pageid'] = (int)$row->page_id;
347 }
348 if ( $fld_title ) {
350 Title::makeTitle( $row->page_namespace, $row->page_title )
351 );
352 }
353 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
354 if ( $fld_fragment && $row->rd_fragment !== null && $row->rd_fragment !== '' ) {
355 $vals['fragment'] = $row->rd_fragment;
356 }
357 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
358 if ( $fld_redirect ) {
359 $vals['redirect'] = (bool)$row->page_is_redirect;
360 }
361 $fit = $this->addPageSubItem( $id, $vals );
362 if ( !$fit ) {
363 $this->setContinue( $row, $sortby );
364 break;
365 }
366 }
367 } else {
368 $titles = [];
369 $count = 0;
370 foreach ( $res as $row ) {
371 if ( ++$count > $params['limit'] ) {
372 // We've reached the one extra which shows that
373 // there are additional pages to be had. Stop here...
374 $this->setContinue( $row, $sortby );
375 break;
376 }
377
378 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
379 // Miser mode namespace check
380 continue;
381 }
382
383 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
384 }
385 $resultPageSet->populateFromTitles( $titles );
386 }
387 }
388
389 private function setContinue( $row, $sortby ) {
390 $cont = [];
391 foreach ( $sortby as $field => $v ) {
392 $cont[] = $row->$field;
393 }
394 $this->setContinueEnumParameter( 'continue', implode( '|', $cont ) );
395 }
396
397 public function getCacheMode( $params ) {
398 return 'public';
399 }
400
401 public function getAllowedParams() {
402 $settings = self::$settings[$this->getModuleName()];
403
404 $ret = [
405 'prop' => [
406 ParamValidator::PARAM_TYPE => [
407 'pageid',
408 'title',
409 ],
410 ParamValidator::PARAM_ISMULTI => true,
411 ParamValidator::PARAM_DEFAULT => 'pageid|title',
413 ],
414 'namespace' => [
415 ParamValidator::PARAM_ISMULTI => true,
416 ParamValidator::PARAM_TYPE => 'namespace',
417 ],
418 'show' => null, // Will be filled/removed below
419 'limit' => [
420 ParamValidator::PARAM_DEFAULT => 10,
421 ParamValidator::PARAM_TYPE => 'limit',
422 IntegerDef::PARAM_MIN => 1,
423 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
424 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
425 ],
426 'continue' => [
427 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
428 ],
429 ];
430
431 if ( empty( $settings['from_namespace'] ) &&
432 $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
433 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
434 'api-help-param-limited-in-miser-mode',
435 ];
436 }
437
438 if ( !empty( $settings['showredirects'] ) ) {
439 $ret['prop'][ParamValidator::PARAM_TYPE][] = 'redirect';
440 $ret['prop'][ParamValidator::PARAM_DEFAULT] .= '|redirect';
441 }
442 if ( isset( $settings['props'] ) ) {
443 $ret['prop'][ParamValidator::PARAM_TYPE] = array_merge(
444 $ret['prop'][ParamValidator::PARAM_TYPE], $settings['props']
445 );
446 }
447
448 $show = [];
449 if ( !empty( $settings['showredirects'] ) ) {
450 $show[] = 'redirect';
451 $show[] = '!redirect';
452 }
453 if ( isset( $settings['show'] ) ) {
454 $show = array_merge( $show, $settings['show'] );
455 }
456 if ( $show ) {
457 $ret['show'] = [
458 ParamValidator::PARAM_TYPE => $show,
459 ParamValidator::PARAM_ISMULTI => true,
461 ];
462 } else {
463 unset( $ret['show'] );
464 }
465
466 return $ret;
467 }
468
469 protected function getExamplesMessages() {
470 $settings = self::$settings[$this->getModuleName()];
471 $name = $this->getModuleName();
472 $path = $this->getModulePath();
473 $title = $settings['exampletitle'] ?? Title::newMainPage()->getPrefixedText();
474 $etitle = rawurlencode( $title );
475
476 return [
477 "action=query&prop={$name}&titles={$etitle}"
478 => "apihelp-$path-example-simple",
479 "action=query&generator={$name}&titles={$etitle}&prop=info"
480 => "apihelp-$path-example-generator",
481 ];
482 }
483
484 public function getHelpUrls() {
485 $name = ucfirst( $this->getModuleName() );
486 return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
487 }
488}
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:1454
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1643
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:170
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:196
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:221
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:765
getModulePath()
Get the path to this module.
Definition ApiBase.php:573
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:163
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:223
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:498
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: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:638
Service for formatting and validating API parameters.
Type definition for integer types.