Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 139
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryExtLinksUsage
0.00% covered (danger)
0.00%
0 / 138
0.00% covered (danger)
0.00%
0 / 9
1056
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
 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 / 84
0.00% covered (danger)
0.00%
0 / 1
506
 setContinue
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
6
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 4
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/**
4 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 *
6 * @license GPL-2.0-or-later
7 * @file
8 */
9
10namespace MediaWiki\Api;
11
12use MediaWiki\Deferred\LinksUpdate\ExternalLinksTable;
13use MediaWiki\ExternalLinks\LinkFilter;
14use MediaWiki\MainConfigNames;
15use MediaWiki\Parser\Parser;
16use MediaWiki\Title\Title;
17use MediaWiki\Utils\UrlUtils;
18use Wikimedia\ParamValidator\ParamValidator;
19use Wikimedia\ParamValidator\TypeDef\IntegerDef;
20use Wikimedia\Rdbms\IExpression;
21use Wikimedia\Rdbms\LikeValue;
22
23/**
24 * @ingroup API
25 */
26class ApiQueryExtLinksUsage extends ApiQueryGeneratorBase {
27
28    public function __construct(
29        ApiQuery $query,
30        string $moduleName,
31        private readonly UrlUtils $urlUtils,
32    ) {
33        parent::__construct( $query, $moduleName, 'eu' );
34    }
35
36    public function execute() {
37        $this->run();
38    }
39
40    /** @inheritDoc */
41    public function getCacheMode( $params ) {
42        return 'public';
43    }
44
45    /** @inheritDoc */
46    public function executeGenerator( $resultPageSet ) {
47        $this->run( $resultPageSet );
48    }
49
50    /**
51     * @param ApiPageSet|null $resultPageSet
52     * @return void
53     */
54    private function run( $resultPageSet = null ) {
55        $params = $this->extractRequestParams();
56        $db = $this->getDB();
57
58        $query = $params['query'];
59        $protocol = LinkFilter::getProtocolPrefix( $params['protocol'] );
60
61        $this->addTables( [ 'externallinks', 'page' ] );
62        $this->addJoinConds( [ 'page' => [ 'JOIN', 'page_id=el_from' ] ] );
63        $fields = [ 'el_to_domain_index', 'el_to_path' ];
64
65        $miser_ns = [];
66        if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
67            $miser_ns = $params['namespace'] ?: [];
68        } else {
69            $this->addWhereFld( 'page_namespace', $params['namespace'] );
70        }
71        if ( $query !== null && $query !== '' ) {
72            // Normalize query to match the normalization applied for the externallinks table
73            $query = Parser::normalizeLinkUrl( $query );
74            $conds = LinkFilter::getQueryConditions( $query, [
75                'protocol' => $protocol,
76                'oneWildcard' => true,
77                'db' => $db
78            ] );
79            if ( !$conds ) {
80                $this->dieWithError( 'apierror-badquery' );
81            }
82            $this->addWhere( $conds );
83        } else {
84            if ( $protocol !== null ) {
85                $this->addWhere(
86                    $db->expr( 'el_to_domain_index', IExpression::LIKE, new LikeValue( "$protocol", $db->anyString() ) )
87                );
88            }
89        }
90        $orderBy = [ 'el_id' ];
91
92        $this->addOption( 'ORDER BY', $orderBy );
93        $this->addFields( $orderBy ); // Make sure
94
95        $prop = array_fill_keys( $params['prop'], true );
96        $fld_ids = isset( $prop['ids'] );
97        $fld_title = isset( $prop['title'] );
98        $fld_url = isset( $prop['url'] );
99
100        if ( $resultPageSet === null ) {
101            $this->addFields( [
102                'page_id',
103                'page_namespace',
104                'page_title'
105            ] );
106            foreach ( $fields as $field ) {
107                $this->addFieldsIf( $field, $fld_url );
108            }
109        } else {
110            $this->addFields( $resultPageSet->getPageTableFields() );
111        }
112
113        $limit = $params['limit'];
114        $this->addOption( 'LIMIT', $limit + 1 );
115
116        // T244254: Avoid MariaDB deciding to scan all of `page`.
117        $this->addOption( 'STRAIGHT_JOIN' );
118
119        if ( $params['continue'] !== null ) {
120            $cont = $this->parseContinueParamOrDie( $params['continue'],
121                array_fill( 0, count( $orderBy ), 'string' ) );
122            $conds = array_combine( $orderBy, array_map( 'rawurldecode', $cont ) );
123            $this->addWhere( $db->buildComparison( '>=', $conds ) );
124        }
125
126        $this->setVirtualDomain( ExternalLinksTable::VIRTUAL_DOMAIN );
127        $res = $this->select( __METHOD__ );
128        $this->resetVirtualDomain();
129
130        $result = $this->getResult();
131
132        if ( $resultPageSet === null ) {
133            $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
134        }
135
136        $count = 0;
137        foreach ( $res as $row ) {
138            if ( ++$count > $limit ) {
139                // We've reached the one extra which shows that there are
140                // additional pages to be had. Stop here...
141                $this->setContinue( $orderBy, $row );
142                break;
143            }
144
145            if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
146                continue;
147            }
148
149            if ( $resultPageSet === null ) {
150                $vals = [
151                    ApiResult::META_TYPE => 'assoc',
152                ];
153                if ( $fld_ids ) {
154                    $vals['pageid'] = (int)$row->page_id;
155                }
156                if ( $fld_title ) {
157                    $title = Title::makeTitle( $row->page_namespace, $row->page_title );
158                    ApiQueryBase::addTitleInfo( $vals, $title );
159                }
160                if ( $fld_url ) {
161                    $to = LinkFilter::reverseIndexes( $row->el_to_domain_index ) . $row->el_to_path;
162                    // expand protocol-relative urls
163                    if ( $params['expandurl'] ) {
164                        $to = (string)$this->urlUtils->expand( $to, PROTO_CANONICAL );
165                    }
166                    $vals['url'] = $to;
167                }
168                $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
169                if ( !$fit ) {
170                    $this->setContinue( $orderBy, $row );
171                    break;
172                }
173            } else {
174                $resultPageSet->processDbRow( $row );
175            }
176        }
177
178        if ( $resultPageSet === null ) {
179            $result->addIndexedTagName( [ 'query', $this->getModuleName() ],
180                $this->getModulePrefix() );
181        }
182    }
183
184    private function setContinue( array $orderBy, \stdClass $row ) {
185        $fields = [];
186        foreach ( $orderBy as $field ) {
187            $fields[] = strtr( $row->$field, [ '%' => '%25', '|' => '%7C' ] );
188        }
189        $this->setContinueEnumParameter( 'continue', implode( '|', $fields ) );
190    }
191
192    /** @inheritDoc */
193    public function getAllowedParams() {
194        $ret = [
195            'prop' => [
196                ParamValidator::PARAM_ISMULTI => true,
197                ParamValidator::PARAM_DEFAULT => 'ids|title|url',
198                ParamValidator::PARAM_TYPE => [
199                    'ids',
200                    'title',
201                    'url'
202                ],
203                ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
204            ],
205            'continue' => [
206                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
207            ],
208            'protocol' => [
209                ParamValidator::PARAM_TYPE => LinkFilter::prepareProtocols(),
210                ParamValidator::PARAM_DEFAULT => '',
211            ],
212            'query' => null,
213            'namespace' => [
214                ParamValidator::PARAM_ISMULTI => true,
215                ParamValidator::PARAM_TYPE => 'namespace'
216            ],
217            'limit' => [
218                ParamValidator::PARAM_DEFAULT => 10,
219                ParamValidator::PARAM_TYPE => 'limit',
220                IntegerDef::PARAM_MIN => 1,
221                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
222                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
223            ],
224            'expandurl' => [
225                ParamValidator::PARAM_TYPE => 'boolean',
226                ParamValidator::PARAM_DEFAULT => false,
227                ParamValidator::PARAM_DEPRECATED => true,
228            ],
229        ];
230
231        if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
232            $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
233                'api-help-param-limited-in-miser-mode',
234            ];
235        }
236
237        return $ret;
238    }
239
240    /** @inheritDoc */
241    protected function getExamplesMessages() {
242        return [
243            'action=query&list=exturlusage&euquery=www.mediawiki.org'
244                => 'apihelp-query+exturlusage-example-simple',
245        ];
246    }
247
248    /** @inheritDoc */
249    public function getHelpUrls() {
250        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Exturlusage';
251    }
252}
253
254/** @deprecated class alias since 1.43 */
255class_alias( ApiQueryExtLinksUsage::class, 'ApiQueryExtLinksUsage' );