MediaWiki master
ApiQueryExtLinksUsage.php
Go to the documentation of this file.
1<?php
2
24namespace MediaWiki\Api;
25
35
40
41 private UrlUtils $urlUtils;
42
43 public function __construct( ApiQuery $query, string $moduleName, UrlUtils $urlUtils ) {
44 parent::__construct( $query, $moduleName, 'eu' );
45
46 $this->urlUtils = $urlUtils;
47 }
48
49 public function execute() {
50 $this->run();
51 }
52
53 public function getCacheMode( $params ) {
54 return 'public';
55 }
56
57 public function executeGenerator( $resultPageSet ) {
58 $this->run( $resultPageSet );
59 }
60
65 private function run( $resultPageSet = null ) {
66 $params = $this->extractRequestParams();
67 $db = $this->getDB();
68
69 $query = $params['query'];
70 $protocol = LinkFilter::getProtocolPrefix( $params['protocol'] );
71
72 $this->addTables( [ 'externallinks', 'page' ] );
73 $this->addJoinConds( [ 'page' => [ 'JOIN', 'page_id=el_from' ] ] );
74 $fields = [ 'el_to_domain_index', 'el_to_path' ];
75
76 $miser_ns = [];
77 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
78 $miser_ns = $params['namespace'] ?: [];
79 } else {
80 $this->addWhereFld( 'page_namespace', $params['namespace'] );
81 }
82 if ( $query !== null && $query !== '' ) {
83 // Normalize query to match the normalization applied for the externallinks table
84 $query = Parser::normalizeLinkUrl( $query );
85 $conds = LinkFilter::getQueryConditions( $query, [
86 'protocol' => $protocol,
87 'oneWildcard' => true,
88 'db' => $db
89 ] );
90 if ( !$conds ) {
91 $this->dieWithError( 'apierror-badquery' );
92 }
93 $this->addWhere( $conds );
94 } else {
95 if ( $protocol !== null ) {
96 $this->addWhere(
97 $db->expr( 'el_to_domain_index', IExpression::LIKE, new LikeValue( "$protocol", $db->anyString() ) )
98 );
99 }
100 }
101 $orderBy = [ 'el_id' ];
102
103 $this->addOption( 'ORDER BY', $orderBy );
104 $this->addFields( $orderBy ); // Make sure
105
106 $prop = array_fill_keys( $params['prop'], true );
107 $fld_ids = isset( $prop['ids'] );
108 $fld_title = isset( $prop['title'] );
109 $fld_url = isset( $prop['url'] );
110
111 if ( $resultPageSet === null ) {
112 $this->addFields( [
113 'page_id',
114 'page_namespace',
115 'page_title'
116 ] );
117 foreach ( $fields as $field ) {
118 $this->addFieldsIf( $field, $fld_url );
119 }
120 } else {
121 $this->addFields( $resultPageSet->getPageTableFields() );
122 }
123
124 $limit = $params['limit'];
125 $this->addOption( 'LIMIT', $limit + 1 );
126
127 // T244254: Avoid MariaDB deciding to scan all of `page`.
128 $this->addOption( 'STRAIGHT_JOIN' );
129
130 if ( $params['continue'] !== null ) {
131 $cont = $this->parseContinueParamOrDie( $params['continue'],
132 array_fill( 0, count( $orderBy ), 'string' ) );
133 $conds = array_combine( $orderBy, array_map( 'rawurldecode', $cont ) );
134 $this->addWhere( $db->buildComparison( '>=', $conds ) );
135 }
136
137 $res = $this->select( __METHOD__ );
138
139 $result = $this->getResult();
140
141 if ( $resultPageSet === null ) {
142 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
143 }
144
145 $count = 0;
146 foreach ( $res as $row ) {
147 if ( ++$count > $limit ) {
148 // We've reached the one extra which shows that there are
149 // additional pages to be had. Stop here...
150 $this->setContinue( $orderBy, $row );
151 break;
152 }
153
154 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
155 continue;
156 }
157
158 if ( $resultPageSet === null ) {
159 $vals = [
160 ApiResult::META_TYPE => 'assoc',
161 ];
162 if ( $fld_ids ) {
163 $vals['pageid'] = (int)$row->page_id;
164 }
165 if ( $fld_title ) {
166 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
167 ApiQueryBase::addTitleInfo( $vals, $title );
168 }
169 if ( $fld_url ) {
170 $to = LinkFilter::reverseIndexes( $row->el_to_domain_index ) . $row->el_to_path;
171 // expand protocol-relative urls
172 if ( $params['expandurl'] ) {
173 $to = (string)$this->urlUtils->expand( $to, PROTO_CANONICAL );
174 }
175 $vals['url'] = $to;
176 }
177 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
178 if ( !$fit ) {
179 $this->setContinue( $orderBy, $row );
180 break;
181 }
182 } else {
183 $resultPageSet->processDbRow( $row );
184 }
185 }
186
187 if ( $resultPageSet === null ) {
188 $result->addIndexedTagName( [ 'query', $this->getModuleName() ],
189 $this->getModulePrefix() );
190 }
191 }
192
193 private function setContinue( $orderBy, $row ) {
194 $fields = [];
195 foreach ( $orderBy as $field ) {
196 $fields[] = strtr( $row->$field, [ '%' => '%25', '|' => '%7C' ] );
197 }
198 $this->setContinueEnumParameter( 'continue', implode( '|', $fields ) );
199 }
200
201 public function getAllowedParams() {
202 $ret = [
203 'prop' => [
204 ParamValidator::PARAM_ISMULTI => true,
205 ParamValidator::PARAM_DEFAULT => 'ids|title|url',
206 ParamValidator::PARAM_TYPE => [
207 'ids',
208 'title',
209 'url'
210 ],
212 ],
213 'continue' => [
214 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
215 ],
216 'protocol' => [
217 ParamValidator::PARAM_TYPE => LinkFilter::prepareProtocols(),
218 ParamValidator::PARAM_DEFAULT => '',
219 ],
220 'query' => null,
221 'namespace' => [
222 ParamValidator::PARAM_ISMULTI => true,
223 ParamValidator::PARAM_TYPE => 'namespace'
224 ],
225 'limit' => [
226 ParamValidator::PARAM_DEFAULT => 10,
227 ParamValidator::PARAM_TYPE => 'limit',
228 IntegerDef::PARAM_MIN => 1,
229 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
230 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
231 ],
232 'expandurl' => [
233 ParamValidator::PARAM_TYPE => 'boolean',
234 ParamValidator::PARAM_DEFAULT => false,
235 ParamValidator::PARAM_DEPRECATED => true,
236 ],
237 ];
238
239 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
240 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
241 'api-help-param-limited-in-miser-mode',
242 ];
243 }
244
245 return $ret;
246 }
247
248 protected function getExamplesMessages() {
249 return [
250 'action=query&list=exturlusage&euquery=www.mediawiki.org'
251 => 'apihelp-query+exturlusage-example-simple',
252 ];
253 }
254
255 public function getHelpUrls() {
256 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Exturlusage';
257 }
258}
259
261class_alias( ApiQueryExtLinksUsage::class, 'ApiQueryExtLinksUsage' );
const PROTO_CANONICAL
Definition Defines.php:237
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:566
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:557
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1707
getResult()
Get the result object.
Definition ApiBase.php:696
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:221
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:189
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:181
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:248
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:246
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
getDB()
Get the Query database connection (read-only)
select( $method, $extraQuery=[], ?array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addFields( $value)
Add a set of fields to select to the internal array.
getHelpUrls()
Return links to more detailed help pages about the module.
getCacheMode( $params)
Get the cache mode for the data generated by this module.
executeGenerator( $resultPageSet)
Execute this module as a generator.
getExamplesMessages()
Returns usage examples for this module.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
__construct(ApiQuery $query, string $moduleName, UrlUtils $urlUtils)
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
This is the main query class.
Definition ApiQuery.php:48
const META_TYPE
Key for the 'type' metadata item.
A class containing constants representing the names of configuration variables.
const MiserMode
Name constant for the MiserMode setting, for use with Config::get()
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:147
Represents a title within MediaWiki.
Definition Title.php:78
A service to expand, parse, and otherwise manipulate URLs.
Definition UrlUtils.php:16
Service for formatting and validating API parameters.
Type definition for integer types.
Content of like value.
Definition LikeValue.php:14
array $params
The job parameters.