Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 211
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryBacklinksprop
0.00% covered (danger)
0.00%
0 / 210
0.00% covered (danger)
0.00%
0 / 9
4556
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 executeGenerator
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 run
0.00% covered (danger)
0.00%
0 / 136
0.00% covered (danger)
0.00%
0 / 1
2652
 setContinue
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getCacheMode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
72
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * API module to handle links table back-queries
4 *
5 * Copyright © 2014 Wikimedia Foundation and contributors
6 *
7 * @license GPL-2.0-or-later
8 * @file
9 * @since 1.24
10 */
11
12namespace MediaWiki\Api;
13
14use MediaWiki\Deferred\LinksUpdate\ImageLinksTable;
15use MediaWiki\Deferred\LinksUpdate\PageLinksTable;
16use MediaWiki\Deferred\LinksUpdate\TemplateLinksTable;
17use MediaWiki\Linker\LinksMigration;
18use MediaWiki\MainConfigNames;
19use MediaWiki\Title\Title;
20use Wikimedia\ParamValidator\ParamValidator;
21use Wikimedia\ParamValidator\TypeDef\IntegerDef;
22
23/**
24 * This implements prop=redirects, prop=linkshere, prop=catmembers,
25 * prop=transcludedin, and prop=fileusage
26 *
27 * @ingroup API
28 * @since 1.24
29 */
30class ApiQueryBacklinksprop extends ApiQueryGeneratorBase {
31
32    /** @var array Data for the various modules implemented by this class */
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            'index' => 'pl_backlinks_namespace_target_id',
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            'index' => 'il_backlinks_namespace_target_id',
69            'from_namespace' => true,
70            'exampletitle' => 'File:Example.jpg',
71            'showredirects' => true,
72            'virtualdomain' => ImageLinksTable::VIRTUAL_DOMAIN,
73        ],
74    ];
75
76    public function __construct(
77        ApiQuery $query,
78        string $moduleName,
79        private readonly LinksMigration $linksMigration,
80    ) {
81        parent::__construct( $query, $moduleName, self::$settings[$moduleName]['code'] );
82    }
83
84    public function execute() {
85        $this->run();
86    }
87
88    /** @inheritDoc */
89    public function executeGenerator( $resultPageSet ) {
90        $this->run( $resultPageSet );
91    }
92
93    /**
94     * @param ApiPageSet|null $resultPageSet
95     */
96    private function run( ?ApiPageSet $resultPageSet = null ) {
97        $settings = self::$settings[$this->getModuleName()];
98
99        $domain = $settings['virtualdomain'] ?? false;
100        $this->setVirtualDomain( $domain );
101        $db = $this->getDB();
102
103        $params = $this->extractRequestParams();
104        $prop = array_fill_keys( $params['prop'], true );
105
106        $pageSet = $this->getPageSet();
107        $titles = $pageSet->getGoodAndMissingPages();
108        $map = $pageSet->getGoodAndMissingTitlesByNamespace();
109
110        // Add in special pages, they can theoretically have backlinks too.
111        // (although currently they only do for prop=redirects)
112        foreach ( $pageSet->getSpecialPages() as $id => $title ) {
113            $titles[] = $title;
114            $map[$title->getNamespace()][$title->getDBkey()] = $id;
115        }
116
117        // Determine our fields to query on
118        $p = $settings['prefix'];
119
120        if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
121            [ $bl_namespace, $bl_title ] = $this->linksMigration->getTitleFields( $settings['linktable'] );
122        } else {
123            $bl_namespace = "{$p}_namespace";
124            $bl_title = "{$p}_title";
125        }
126        $bl_from = "{$p}_from";
127
128        $hasNS = !is_int( $bl_namespace );
129        if ( !$hasNS ) {
130            $titles = array_filter( $titles, static function ( $t ) use ( $bl_namespace ) {
131                return $t->getNamespace() === $bl_namespace;
132            } );
133            $map = array_intersect_key( $map, [ $bl_namespace => true ] );
134        }
135
136        if ( !$titles ) {
137            return; // nothing to do
138        }
139        if ( $params['namespace'] !== null && count( $params['namespace'] ) === 0 ) {
140            return; // nothing to do
141        }
142
143        // Figure out what we're sorting by, and add associated WHERE clauses.
144        // MySQL's query planner screws up if we include a field in ORDER BY
145        // when it's constant in WHERE, so we have to test that for each field.
146        $sortby = [];
147        if ( $hasNS && count( $map ) > 1 ) {
148            $sortby[$bl_namespace] = 'int';
149        }
150        $theTitle = null;
151        foreach ( $map as $nsTitles ) {
152            $key = array_key_first( $nsTitles );
153            $theTitle ??= $key;
154            if ( count( $nsTitles ) > 1 || $key !== $theTitle ) {
155                $sortby[$bl_title] = 'string';
156                break;
157            }
158        }
159        $miser_ns = null;
160        if ( $params['namespace'] !== null ) {
161            if ( empty( $settings['from_namespace'] ) ) {
162                if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
163                    $miser_ns = $params['namespace'];
164                } else {
165                    $this->addWhereFld( 'page_namespace', $params['namespace'] );
166                }
167            } else {
168                $this->addWhereFld( "{$p}_from_namespace", $params['namespace'] );
169                if ( !empty( $settings['from_namespace'] )
170                    && $params['namespace'] !== null && count( $params['namespace'] ) > 1
171                ) {
172                    $sortby["{$p}_from_namespace"] = 'int';
173                }
174            }
175        }
176        $sortby[$bl_from] = 'int';
177
178        // Now use the $sortby to figure out the continuation
179        $continueFields = array_keys( $sortby );
180        $continueTypes = array_values( $sortby );
181        if ( $params['continue'] !== null ) {
182            $continueValues = $this->parseContinueParamOrDie( $params['continue'], $continueTypes );
183            $conds = array_combine( $continueFields, $continueValues );
184            $this->addWhere( $db->buildComparison( '>=', $conds ) );
185        }
186
187        // Populate the rest of the query
188        if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
189            $queryInfo = $this->linksMigration->getQueryInfo( $settings['linktable'] );
190            $this->addTables( [ 'page', ...$queryInfo['tables'] ] );
191            $this->addJoinConds( $queryInfo['joins'] );
192        } else {
193            $this->addTables( [ $settings['linktable'], 'page' ] );
194        }
195        $this->addWhere( "$bl_from = page_id" );
196
197        if ( $this->getModuleName() === 'redirects' ) {
198            $this->addWhereFld( 'rd_interwiki', '' );
199        }
200
201        $this->addFields( array_keys( $sortby ) );
202        $this->addFields( [ 'bl_namespace' => $bl_namespace, 'bl_title' => $bl_title ] );
203        if ( $resultPageSet === null ) {
204            $fld_pageid = isset( $prop['pageid'] );
205            $fld_title = isset( $prop['title'] );
206            $fld_redirect = isset( $prop['redirect'] );
207
208            $this->addFieldsIf( 'page_id', $fld_pageid );
209            $this->addFieldsIf( [ 'page_title', 'page_namespace' ], $fld_title );
210            $this->addFieldsIf( 'page_is_redirect', $fld_redirect );
211
212            // prop=redirects
213            $fld_fragment = isset( $prop['fragment'] );
214            $this->addFieldsIf( 'rd_fragment', $fld_fragment );
215        } else {
216            $this->addFields( $resultPageSet->getPageTableFields() );
217        }
218
219        $this->addFieldsIf( 'page_namespace', $miser_ns !== null );
220
221        if ( $hasNS && $map ) {
222            // Can't use LinkBatch because it throws away Special titles.
223            // And we already have the needed data structure anyway.
224            $this->addWhere( $db->makeWhereFrom2d( $map, $bl_namespace, $bl_title ) );
225        } else {
226            $where = [];
227            foreach ( $titles as $t ) {
228                if ( $t->getNamespace() == $bl_namespace ) {
229                    $where[] = $db->expr( $bl_title, '=', $t->getDBkey() );
230                }
231            }
232            $this->addWhere( $db->orExpr( $where ) );
233        }
234
235        if ( $params['show'] !== null ) {
236            // prop=redirects only
237            $show = array_fill_keys( $params['show'], true );
238            if ( ( isset( $show['fragment'] ) && isset( $show['!fragment'] ) ) ||
239                ( isset( $show['redirect'] ) && isset( $show['!redirect'] ) )
240            ) {
241                $this->dieWithError( 'apierror-show' );
242            }
243            $this->addWhereIf( $db->expr( 'rd_fragment', '!=', '' ), isset( $show['fragment'] ) );
244            $this->addWhereIf( [ 'rd_fragment' => '' ], isset( $show['!fragment'] ) );
245            $this->addWhereIf( [ 'page_is_redirect' => 1 ], isset( $show['redirect'] ) );
246            $this->addWhereIf( [ 'page_is_redirect' => 0 ], isset( $show['!redirect'] ) );
247        }
248
249        // Override any ORDER BY from above with what we calculated earlier.
250        $this->addOption( 'ORDER BY', array_keys( $sortby ) );
251
252        // MySQL's optimizer chokes if we have too many values in "$bl_title IN
253        // (...)" and chooses the wrong index, so specify the correct index to
254        // use for the query. See T139056 for details.
255        if ( array_key_exists( 'index', $settings ) &&
256            $params['namespace'] !== null &&
257            count( $params['namespace'] ) == 1 &&
258            !empty( $settings['from_namespace'] )
259        ) {
260            $this->addOption( 'USE INDEX', [ $settings['linktable'] => $settings['index'] ] );
261        }
262
263        $this->addOption( 'LIMIT', $params['limit'] + 1 );
264
265        $res = $this->select( __METHOD__ );
266
267        if ( $resultPageSet === null ) {
268            // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
269            if ( $fld_title ) {
270                $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
271            }
272
273            $count = 0;
274            foreach ( $res as $row ) {
275                if ( ++$count > $params['limit'] ) {
276                    // We've reached the one extra which shows that
277                    // there are additional pages to be had. Stop here...
278                    $this->setContinue( $row, $sortby );
279                    break;
280                }
281
282                if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
283                    // Miser mode namespace check
284                    continue;
285                }
286
287                // Get the ID of the current page
288                $id = $map[$row->bl_namespace][$row->bl_title];
289
290                $vals = [];
291                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
292                if ( $fld_pageid ) {
293                    $vals['pageid'] = (int)$row->page_id;
294                }
295                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
296                if ( $fld_title ) {
297                    ApiQueryBase::addTitleInfo( $vals,
298                        Title::makeTitle( $row->page_namespace, $row->page_title )
299                    );
300                }
301                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
302                if ( $fld_fragment && $row->rd_fragment !== '' ) {
303                    $vals['fragment'] = $row->rd_fragment;
304                }
305                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
306                if ( $fld_redirect ) {
307                    $vals['redirect'] = (bool)$row->page_is_redirect;
308                }
309                $fit = $this->addPageSubItem( $id, $vals );
310                if ( !$fit ) {
311                    $this->setContinue( $row, $sortby );
312                    break;
313                }
314            }
315        } else {
316            $titles = [];
317            $count = 0;
318            foreach ( $res as $row ) {
319                if ( ++$count > $params['limit'] ) {
320                    // We've reached the one extra which shows that
321                    // there are additional pages to be had. Stop here...
322                    $this->setContinue( $row, $sortby );
323                    break;
324                }
325
326                if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
327                    // Miser mode namespace check
328                    continue;
329                }
330
331                $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
332            }
333            $resultPageSet->populateFromTitles( $titles );
334        }
335    }
336
337    private function setContinue( \stdClass $row, array $sortby ) {
338        $cont = [];
339        foreach ( $sortby as $field => $v ) {
340            $cont[] = $row->$field;
341        }
342        $this->setContinueEnumParameter( 'continue', implode( '|', $cont ) );
343    }
344
345    /** @inheritDoc */
346    public function getCacheMode( $params ) {
347        return 'public';
348    }
349
350    /** @inheritDoc */
351    public function getAllowedParams() {
352        $settings = self::$settings[$this->getModuleName()];
353
354        $ret = [
355            'prop' => [
356                ParamValidator::PARAM_TYPE => [
357                    'pageid',
358                    'title',
359                ],
360                ParamValidator::PARAM_ISMULTI => true,
361                ParamValidator::PARAM_DEFAULT => 'pageid|title',
362                ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
363            ],
364            'namespace' => [
365                ParamValidator::PARAM_ISMULTI => true,
366                ParamValidator::PARAM_TYPE => 'namespace',
367            ],
368            'show' => null, // Will be filled/removed below
369            'limit' => [
370                ParamValidator::PARAM_DEFAULT => 10,
371                ParamValidator::PARAM_TYPE => 'limit',
372                IntegerDef::PARAM_MIN => 1,
373                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
374                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
375            ],
376            'continue' => [
377                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
378            ],
379        ];
380
381        if ( empty( $settings['from_namespace'] ) &&
382        $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
383            $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
384                'api-help-param-limited-in-miser-mode',
385            ];
386        }
387
388        if ( !empty( $settings['showredirects'] ) ) {
389            $ret['prop'][ParamValidator::PARAM_TYPE][] = 'redirect';
390            $ret['prop'][ParamValidator::PARAM_DEFAULT] .= '|redirect';
391        }
392        if ( isset( $settings['props'] ) ) {
393            $ret['prop'][ParamValidator::PARAM_TYPE] = array_merge(
394                $ret['prop'][ParamValidator::PARAM_TYPE], $settings['props']
395            );
396        }
397
398        $show = [];
399        if ( !empty( $settings['showredirects'] ) ) {
400            $show[] = 'redirect';
401            $show[] = '!redirect';
402        }
403        if ( isset( $settings['show'] ) ) {
404            $show = array_merge( $show, $settings['show'] );
405        }
406        if ( $show ) {
407            $ret['show'] = [
408                ParamValidator::PARAM_TYPE => $show,
409                ParamValidator::PARAM_ISMULTI => true,
410                ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
411            ];
412        } else {
413            unset( $ret['show'] );
414        }
415
416        return $ret;
417    }
418
419    /** @inheritDoc */
420    protected function getExamplesMessages() {
421        $settings = self::$settings[$this->getModuleName()];
422        $name = $this->getModuleName();
423        $path = $this->getModulePath();
424        $title = $settings['exampletitle'] ?? Title::newMainPage()->getPrefixedText();
425        $etitle = rawurlencode( $title );
426
427        return [
428            "action=query&prop={$name}&titles={$etitle}"
429                => "apihelp-$path-example-simple",
430            "action=query&generator={$name}&titles={$etitle}&prop=info"
431                => "apihelp-$path-example-generator",
432        ];
433    }
434
435    /** @inheritDoc */
436    public function getHelpUrls() {
437        $name = ucfirst( $this->getModuleName() );
438        return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
439    }
440}
441
442/** @deprecated class alias since 1.43 */
443class_alias( ApiQueryBacklinksprop::class, 'ApiQueryBacklinksprop' );