Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 229
0.00% covered (danger)
0.00%
0 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryAllLinks
0.00% covered (danger)
0.00%
0 / 228
0.00% covered (danger)
0.00%
0 / 8
3080
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
42
 execute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getCacheMode
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 / 132
0.00% covered (danger)
0.00%
0 / 1
1806
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
6
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 13
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 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Api;
10
11use MediaWiki\Cache\GenderCache;
12use MediaWiki\Deferred\LinksUpdate\ImageLinksTable;
13use MediaWiki\Deferred\LinksUpdate\PageLinksTable;
14use MediaWiki\Deferred\LinksUpdate\TemplateLinksTable;
15use MediaWiki\Linker\LinksMigration;
16use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
17use MediaWiki\Title\NamespaceInfo;
18use MediaWiki\Title\Title;
19use Wikimedia\ParamValidator\ParamValidator;
20use Wikimedia\ParamValidator\TypeDef\IntegerDef;
21use Wikimedia\Rdbms\IExpression;
22use Wikimedia\Rdbms\LikeValue;
23
24/**
25 * Query module to enumerate links from all pages together.
26 *
27 * @ingroup API
28 */
29class ApiQueryAllLinks extends ApiQueryGeneratorBase {
30
31    private string $table;
32    private string $tablePrefix;
33    private string $indexTag;
34    /** @var string */
35    private $fieldTitle = 'title';
36    /** @var int */
37    private $dfltNamespace = NS_MAIN;
38    /** @var bool */
39    private $hasNamespace = true;
40    /** @var string|null */
41    private $useIndex = null;
42    /** @var array */
43    private $props = [];
44    /** @var string|bool */
45    private $virtualDomain = false;
46
47    private NamespaceInfo $namespaceInfo;
48    private GenderCache $genderCache;
49    private LinksMigration $linksMigration;
50
51    public function __construct(
52        ApiQuery $query,
53        string $moduleName,
54        NamespaceInfo $namespaceInfo,
55        GenderCache $genderCache,
56        LinksMigration $linksMigration
57    ) {
58        switch ( $moduleName ) {
59            case 'alllinks':
60                $prefix = 'al';
61                $this->table = 'pagelinks';
62                $this->tablePrefix = 'pl_';
63                $this->useIndex = 'pl_namespace';
64                $this->indexTag = 'l';
65                $this->virtualDomain = PageLinksTable::VIRTUAL_DOMAIN;
66                break;
67            case 'alltransclusions':
68                $prefix = 'at';
69                $this->table = 'templatelinks';
70                $this->tablePrefix = 'tl_';
71                $this->dfltNamespace = NS_TEMPLATE;
72                $this->indexTag = 't';
73                $this->virtualDomain = TemplateLinksTable::VIRTUAL_DOMAIN;
74                break;
75            case 'allfileusages':
76                $prefix = 'af';
77                $this->table = 'imagelinks';
78                $this->tablePrefix = 'il_';
79                $this->fieldTitle = 'to';
80                $this->dfltNamespace = NS_FILE;
81                $this->hasNamespace = false;
82                $this->indexTag = 'f';
83                $this->virtualDomain = ImageLinksTable::VIRTUAL_DOMAIN;
84                break;
85            case 'allredirects':
86                $prefix = 'ar';
87                $this->table = 'redirect';
88                $this->tablePrefix = 'rd_';
89                $this->indexTag = 'r';
90                $this->props = [
91                    'fragment' => 'rd_fragment',
92                    'interwiki' => 'rd_interwiki',
93                ];
94                break;
95            default:
96                ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
97        }
98
99        parent::__construct( $query, $moduleName, $prefix );
100        $this->namespaceInfo = $namespaceInfo;
101        $this->genderCache = $genderCache;
102        $this->linksMigration = $linksMigration;
103    }
104
105    public function execute() {
106        $this->run();
107    }
108
109    /** @inheritDoc */
110    public function getCacheMode( $params ) {
111        return 'public';
112    }
113
114    /** @inheritDoc */
115    public function executeGenerator( $resultPageSet ) {
116        $this->run( $resultPageSet );
117    }
118
119    /**
120     * @param ApiPageSet|null $resultPageSet
121     * @return void
122     */
123    private function run( $resultPageSet = null ) {
124        $this->setVirtualDomain( $this->virtualDomain );
125        $db = $this->getDB();
126        $params = $this->extractRequestParams();
127
128        $pfx = $this->tablePrefix;
129
130        $nsField = $pfx . 'namespace';
131        $titleField = $pfx . $this->fieldTitle;
132        $linktargetReadNew = false;
133        $targetIdColumn = '';
134        if ( isset( $this->linksMigration::$mapping[$this->table] ) ) {
135            [ $nsField, $titleField ] = $this->linksMigration->getTitleFields( $this->table );
136            $queryInfo = $this->linksMigration->getQueryInfo( $this->table, 'linktarget', 'STRAIGHT_JOIN' );
137            $this->addTables( $queryInfo['tables'] );
138            $this->addJoinConds( $queryInfo['joins'] );
139            if ( in_array( 'linktarget', $queryInfo['tables'] ) ) {
140                $linktargetReadNew = true;
141                $targetIdColumn = "{$pfx}target_id";
142                $this->addFields( [ $targetIdColumn ] );
143            }
144        } else {
145            if ( $this->useIndex ) {
146                $this->addOption( 'USE INDEX', $this->useIndex );
147            }
148            $this->addTables( $this->table );
149        }
150
151        $prop = array_fill_keys( $params['prop'], true );
152        $fld_ids = isset( $prop['ids'] );
153        $fld_title = isset( $prop['title'] );
154        if ( $this->hasNamespace ) {
155            $namespace = $params['namespace'];
156        } else {
157            $namespace = $this->dfltNamespace;
158        }
159
160        if ( $params['unique'] ) {
161            $matches = array_intersect_key( $prop, $this->props + [ 'ids' => 1 ] );
162            if ( $matches ) {
163                $p = $this->getModulePrefix();
164                $this->dieWithError(
165                    [
166                        'apierror-invalidparammix-cannotusewith',
167                        "{$p}prop=" . implode( '|', array_keys( $matches ) ),
168                        "{$p}unique"
169                    ],
170                    'invalidparammix'
171                );
172            }
173            $this->addOption( 'DISTINCT' );
174        }
175
176        if ( $this->hasNamespace ) {
177            $this->addWhereFld( $nsField, $namespace );
178        }
179
180        $continue = $params['continue'] !== null;
181        if ( $continue ) {
182            $op = $params['dir'] == 'descending' ? '<=' : '>=';
183            if ( $params['unique'] ) {
184                $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string' ] );
185                $this->addWhere( $db->expr( $titleField, $op, $cont[0] ) );
186            } elseif ( !$linktargetReadNew ) {
187                $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'int' ] );
188                $this->addWhere( $db->buildComparison( $op, [
189                    $titleField => $cont[0],
190                    "{$pfx}from" => $cont[1],
191                ] ) );
192            } else {
193                $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'int' ] );
194                $this->addWhere( $db->buildComparison( $op, [
195                    $targetIdColumn => $cont[0],
196                    "{$pfx}from" => $cont[1],
197                ] ) );
198            }
199        }
200
201        // 'continue' always overrides 'from'
202        $from = $continue || $params['from'] === null ? null :
203            $this->titlePartToKey( $params['from'], $namespace );
204        $to = $params['to'] === null ? null :
205            $this->titlePartToKey( $params['to'], $namespace );
206        $this->addWhereRange( $titleField, 'newer', $from, $to );
207
208        if ( isset( $params['prefix'] ) ) {
209            $this->addWhere(
210                $db->expr(
211                    $titleField,
212                    IExpression::LIKE,
213                    new LikeValue( $this->titlePartToKey( $params['prefix'], $namespace ), $db->anyString() )
214                )
215            );
216        }
217
218        $this->addFields( [ 'pl_title' => $titleField ] );
219        $this->addFieldsIf( [ 'pl_from' => $pfx . 'from' ], !$params['unique'] );
220        foreach ( $this->props as $name => $field ) {
221            $this->addFieldsIf( $field, isset( $prop[$name] ) );
222        }
223
224        $limit = $params['limit'];
225        $this->addOption( 'LIMIT', $limit + 1 );
226
227        $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
228        $orderBy = [];
229        if ( $linktargetReadNew ) {
230            $orderBy[] = $targetIdColumn;
231        } else {
232            $orderBy[] = $titleField . $sort;
233        }
234        if ( !$params['unique'] ) {
235            $orderBy[] = $pfx . 'from' . $sort;
236        }
237        $this->addOption( 'ORDER BY', $orderBy );
238
239        $res = $this->select( __METHOD__ );
240
241        // Get gender information
242        if ( $resultPageSet === null && $res->numRows() && $this->namespaceInfo->hasGenderDistinction( $namespace ) ) {
243            $users = [];
244            foreach ( $res as $row ) {
245                $users[] = $row->pl_title;
246            }
247            if ( $users !== [] ) {
248                $this->genderCache->doQuery( $users, __METHOD__ );
249            }
250        }
251
252        $pageids = [];
253        $titles = [];
254        $count = 0;
255        $result = $this->getResult();
256
257        foreach ( $res as $row ) {
258            if ( ++$count > $limit ) {
259                // We've reached the one extra which shows that there are
260                // additional pages to be had. Stop here...
261                if ( $params['unique'] ) {
262                    $this->setContinueEnumParameter( 'continue', $row->pl_title );
263                } elseif ( $linktargetReadNew ) {
264                    $this->setContinueEnumParameter( 'continue', $row->{$targetIdColumn} . '|' . $row->pl_from );
265                } else {
266                    $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
267                }
268                break;
269            }
270
271            if ( $resultPageSet === null ) {
272                $vals = [
273                    ApiResult::META_TYPE => 'assoc',
274                ];
275                if ( $fld_ids ) {
276                    $vals['fromid'] = (int)$row->pl_from;
277                }
278                if ( $fld_title ) {
279                    $title = Title::makeTitle( $namespace, $row->pl_title );
280                    ApiQueryBase::addTitleInfo( $vals, $title );
281                }
282                foreach ( $this->props as $name => $field ) {
283                    if ( isset( $prop[$name] ) && $row->$field !== null && $row->$field !== '' ) {
284                        $vals[$name] = $row->$field;
285                    }
286                }
287                $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
288                if ( !$fit ) {
289                    if ( $params['unique'] ) {
290                        $this->setContinueEnumParameter( 'continue', $row->pl_title );
291                    } elseif ( $linktargetReadNew ) {
292                        $this->setContinueEnumParameter( 'continue', $row->{$targetIdColumn} . '|' . $row->pl_from );
293                    } else {
294                        $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
295                    }
296                    break;
297                }
298            } elseif ( $params['unique'] ) {
299                $titles[] = Title::makeTitle( $namespace, $row->pl_title );
300            } else {
301                $pageids[] = $row->pl_from;
302            }
303        }
304
305        if ( $resultPageSet === null ) {
306            $result->addIndexedTagName( [ 'query', $this->getModuleName() ], $this->indexTag );
307        } elseif ( $params['unique'] ) {
308            $resultPageSet->populateFromTitles( $titles );
309        } else {
310            $resultPageSet->populateFromPageIDs( $pageids );
311        }
312    }
313
314    /** @inheritDoc */
315    public function getAllowedParams() {
316        $allowedParams = [
317            'continue' => [
318                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
319            ],
320            'from' => null,
321            'to' => null,
322            'prefix' => null,
323            'unique' => false,
324            'prop' => [
325                ParamValidator::PARAM_ISMULTI => true,
326                ParamValidator::PARAM_DEFAULT => 'title',
327                ParamValidator::PARAM_TYPE => [ 'ids', 'title', ...array_keys( $this->props ) ],
328                ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
329            ],
330            'namespace' => [
331                ParamValidator::PARAM_DEFAULT => $this->dfltNamespace,
332                ParamValidator::PARAM_TYPE => 'namespace',
333                NamespaceDef::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
334            ],
335            'limit' => [
336                ParamValidator::PARAM_DEFAULT => 10,
337                ParamValidator::PARAM_TYPE => 'limit',
338                IntegerDef::PARAM_MIN => 1,
339                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
340                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
341            ],
342            'dir' => [
343                ParamValidator::PARAM_DEFAULT => 'ascending',
344                ParamValidator::PARAM_TYPE => [
345                    'ascending',
346                    'descending'
347                ]
348            ],
349        ];
350        if ( !$this->hasNamespace ) {
351            unset( $allowedParams['namespace'] );
352        }
353
354        return $allowedParams;
355    }
356
357    /** @inheritDoc */
358    protected function getExamplesMessages() {
359        $p = $this->getModulePrefix();
360        $name = $this->getModuleName();
361        $path = $this->getModulePath();
362
363        return [
364            "action=query&list={$name}&{$p}from=B&{$p}prop=ids|title"
365                => "apihelp-$path-example-b",
366            "action=query&list={$name}&{$p}unique=&{$p}from=B"
367                => "apihelp-$path-example-unique",
368            "action=query&generator={$name}&g{$p}unique=&g{$p}from=B"
369                => "apihelp-$path-example-unique-generator",
370            "action=query&generator={$name}&g{$p}from=B"
371                => "apihelp-$path-example-generator",
372        ];
373    }
374
375    /** @inheritDoc */
376    public function getHelpUrls() {
377        $name = ucfirst( $this->getModuleName() );
378
379        return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
380    }
381}
382
383/** @deprecated class alias since 1.43 */
384class_alias( ApiQueryAllLinks::class, 'ApiQueryAllLinks' );