Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 143
0.00% covered (danger)
0.00%
0 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryLinks
0.00% covered (danger)
0.00%
0 / 142
0.00% covered (danger)
0.00%
0 / 8
1332
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 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 / 83
0.00% covered (danger)
0.00%
0 / 1
702
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
2
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
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\Deferred\LinksUpdate\PageLinksTable;
12use MediaWiki\Deferred\LinksUpdate\TemplateLinksTable;
13use MediaWiki\Linker\LinksMigration;
14use MediaWiki\Page\LinkBatchFactory;
15use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
16use MediaWiki\Title\Title;
17use Wikimedia\ParamValidator\ParamValidator;
18use Wikimedia\ParamValidator\TypeDef\IntegerDef;
19
20/**
21 * A query module to list all wiki links on a given set of pages.
22 *
23 * @ingroup API
24 */
25class ApiQueryLinks extends ApiQueryGeneratorBase {
26
27    private const LINKS = 'links';
28    private const TEMPLATES = 'templates';
29
30    private string $table;
31    private string $prefix;
32    private string $titlesParam;
33    private string $helpUrl;
34    private ?string $virtualdomain;
35
36    private LinkBatchFactory $linkBatchFactory;
37    private LinksMigration $linksMigration;
38
39    public function __construct(
40        ApiQuery $query,
41        string $moduleName,
42        LinkBatchFactory $linkBatchFactory,
43        LinksMigration $linksMigration
44    ) {
45        switch ( $moduleName ) {
46            case self::LINKS:
47                $this->table = 'pagelinks';
48                $this->prefix = 'pl';
49                $this->titlesParam = 'titles';
50                $this->helpUrl = 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Links';
51                $this->virtualdomain = PageLinksTable::VIRTUAL_DOMAIN;
52                break;
53            case self::TEMPLATES:
54                $this->table = 'templatelinks';
55                $this->prefix = 'tl';
56                $this->titlesParam = 'templates';
57                $this->helpUrl = 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Templates';
58                $this->virtualdomain = TemplateLinksTable::VIRTUAL_DOMAIN;
59                break;
60            default:
61                ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
62        }
63
64        parent::__construct( $query, $moduleName, $this->prefix );
65        $this->linkBatchFactory = $linkBatchFactory;
66        $this->linksMigration = $linksMigration;
67    }
68
69    public function execute() {
70        $this->run();
71    }
72
73    /** @inheritDoc */
74    public function getCacheMode( $params ) {
75        return 'public';
76    }
77
78    /** @inheritDoc */
79    public function executeGenerator( $resultPageSet ) {
80        $this->run( $resultPageSet );
81    }
82
83    /**
84     * @param ApiPageSet|null $resultPageSet
85     */
86    private function run( $resultPageSet = null ) {
87        $pages = $this->getPageSet()->getGoodPages();
88        if ( $pages === [] ) {
89            return; // nothing to do
90        }
91
92        $params = $this->extractRequestParams();
93
94        $this->setVirtualDomain( $this->virtualdomain );
95
96        if ( isset( $this->linksMigration::$mapping[$this->table] ) ) {
97            [ $nsField, $titleField ] = $this->linksMigration->getTitleFields( $this->table );
98            $queryInfo = $this->linksMigration->getQueryInfo( $this->table );
99            $this->addTables( $queryInfo['tables'] );
100            $this->addJoinConds( $queryInfo['joins'] );
101        } else {
102            $this->addTables( $this->table );
103            $nsField = $this->prefix . '_namespace';
104            $titleField = $this->prefix . '_title';
105        }
106
107        $this->addFields( [
108            'pl_from' => $this->prefix . '_from',
109            'pl_namespace' => $nsField,
110            'pl_title' => $titleField,
111        ] );
112
113        $this->addWhereFld( $this->prefix . '_from', array_keys( $pages ) );
114
115        $multiNS = true;
116        $multiTitle = true;
117        if ( $params[$this->titlesParam] ) {
118            // Filter the titles in PHP so our ORDER BY bug avoidance below works right.
119            $filterNS = $params['namespace'] ? array_fill_keys( $params['namespace'], true ) : false;
120
121            $lb = $this->linkBatchFactory->newLinkBatch();
122            foreach ( $params[$this->titlesParam] as $t ) {
123                $title = Title::newFromText( $t );
124                if ( !$title || $title->isExternal() ) {
125                    $this->addWarning( [ 'apiwarn-invalidtitle', wfEscapeWikiText( $t ) ] );
126                } elseif ( !$filterNS || isset( $filterNS[$title->getNamespace()] ) ) {
127                    $lb->addObj( $title );
128                }
129            }
130            if ( $lb->isEmpty() ) {
131                // No titles, no results!
132                return;
133            }
134            $cond = $lb->constructSet( $this->prefix, $this->getDB() );
135            $this->addWhere( $cond );
136            $multiNS = count( $lb->data ) !== 1;
137            $multiTitle = count( array_merge( ...$lb->data ) ) !== 1;
138        } elseif ( $params['namespace'] ) {
139            $this->addWhereFld( $nsField, $params['namespace'] );
140            $multiNS = $params['namespace'] === null || count( $params['namespace'] ) !== 1;
141        }
142
143        if ( $params['continue'] !== null ) {
144            $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'int', 'string' ] );
145            $op = $params['dir'] == 'descending' ? '<=' : '>=';
146            $this->addWhere( $this->getDB()->buildComparison( $op, [
147                "{$this->prefix}_from" => $cont[0],
148                $nsField => $cont[1],
149                $titleField => $cont[2],
150            ] ) );
151        }
152
153        $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
154        // Here's some MySQL craziness going on: if you use WHERE foo='bar'
155        // and later ORDER BY foo MySQL doesn't notice the ORDER BY is pointless
156        // but instead goes and filesorts, because the index for foo was used
157        // already. To work around this, we drop constant fields in the WHERE
158        // clause from the ORDER BY clause
159        $order = [];
160        if ( count( $pages ) !== 1 ) {
161            $order[] = $this->prefix . '_from' . $sort;
162        }
163        if ( $multiNS ) {
164            $order[] = $nsField . $sort;
165        }
166        if ( $multiTitle ) {
167            $order[] = $titleField . $sort;
168        }
169        if ( $order ) {
170            $this->addOption( 'ORDER BY', $order );
171        }
172        $this->addOption( 'LIMIT', $params['limit'] + 1 );
173
174        $res = $this->select( __METHOD__ );
175
176        if ( $resultPageSet === null ) {
177            $this->executeGenderCacheFromResultWrapper( $res, __METHOD__, 'pl' );
178
179            $count = 0;
180            foreach ( $res as $row ) {
181                if ( ++$count > $params['limit'] ) {
182                    // We've reached the one extra which shows that
183                    // there are additional pages to be had. Stop here...
184                    $this->setContinueEnumParameter( 'continue',
185                        "{$row->pl_from}|{$row->pl_namespace}|{$row->pl_title}" );
186                    break;
187                }
188                $vals = [];
189                ApiQueryBase::addTitleInfo( $vals, Title::makeTitle( $row->pl_namespace, $row->pl_title ) );
190                $fit = $this->addPageSubItem( $row->pl_from, $vals );
191                if ( !$fit ) {
192                    $this->setContinueEnumParameter( 'continue',
193                        "{$row->pl_from}|{$row->pl_namespace}|{$row->pl_title}" );
194                    break;
195                }
196            }
197        } else {
198            $titles = [];
199            $count = 0;
200            foreach ( $res as $row ) {
201                if ( ++$count > $params['limit'] ) {
202                    // We've reached the one extra which shows that
203                    // there are additional pages to be had. Stop here...
204                    $this->setContinueEnumParameter( 'continue',
205                        "{$row->pl_from}|{$row->pl_namespace}|{$row->pl_title}" );
206                    break;
207                }
208                $titles[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
209            }
210            $resultPageSet->populateFromTitles( $titles );
211        }
212    }
213
214    /** @inheritDoc */
215    public function getAllowedParams() {
216        return [
217            'namespace' => [
218                ParamValidator::PARAM_TYPE => 'namespace',
219                ParamValidator::PARAM_ISMULTI => true,
220                NamespaceDef::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
221            ],
222            'limit' => [
223                ParamValidator::PARAM_DEFAULT => 10,
224                ParamValidator::PARAM_TYPE => 'limit',
225                IntegerDef::PARAM_MIN => 1,
226                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
227                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
228            ],
229            'continue' => [
230                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
231            ],
232            $this->titlesParam => [
233                ParamValidator::PARAM_ISMULTI => true,
234            ],
235            'dir' => [
236                ParamValidator::PARAM_DEFAULT => 'ascending',
237                ParamValidator::PARAM_TYPE => [
238                    'ascending',
239                    'descending'
240                ]
241            ],
242        ];
243    }
244
245    /** @inheritDoc */
246    protected function getExamplesMessages() {
247        $name = $this->getModuleName();
248        $path = $this->getModulePath();
249        $title = Title::newMainPage()->getPrefixedText();
250        $mp = rawurlencode( $title );
251
252        return [
253            "action=query&prop={$name}&titles={$mp}"
254                => "apihelp-{$path}-example-simple",
255            "action=query&generator={$name}&titles={$mp}&prop=info"
256                => "apihelp-{$path}-example-generator",
257            "action=query&prop={$name}&titles={$mp}&{$this->prefix}namespace=2|10"
258                => "apihelp-{$path}-example-namespaces",
259        ];
260    }
261
262    /** @inheritDoc */
263    public function getHelpUrls() {
264        return $this->helpUrl;
265    }
266}
267
268/** @deprecated class alias since 1.43 */
269class_alias( ApiQueryLinks::class, 'ApiQueryLinks' );