MediaWiki master
ApiQueryExtLinksUsage.php
Go to the documentation of this file.
1<?php
2
10namespace MediaWiki\Api;
11
22
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
41 public function getCacheMode( $params ) {
42 return 'public';
43 }
44
46 public function executeGenerator( $resultPageSet ) {
47 $this->run( $resultPageSet );
48 }
49
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
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 ],
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
241 protected function getExamplesMessages() {
242 return [
243 'action=query&list=exturlusage&euquery=www.mediawiki.org'
244 => 'apihelp-query+exturlusage-example-simple',
245 ];
246 }
247
249 public function getHelpUrls() {
250 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Exturlusage';
251 }
252}
253
255class_alias( ApiQueryExtLinksUsage::class, 'ApiQueryExtLinksUsage' );
const PROTO_CANONICAL
Definition Defines.php:223
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:206
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:174
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:166
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:233
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:231
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.
resetVirtualDomain()
Reset the virtual domain to the main database.
setVirtualDomain(string|false $virtualDomain)
Set the Query database connection (read-only)
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.1.25, returning boolean false is deprecated...
getCacheMode( $params)
Get the cache mode for the data generated by this module.Override this in the module subclass....
executeGenerator( $resultPageSet)
Execute this module as a generator.
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
__construct(ApiQuery $query, string $moduleName, private readonly UrlUtils $urlUtils,)
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
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:36
const META_TYPE
Key for the 'type' metadata item.
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
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:138
Represents a title within MediaWiki.
Definition Title.php:69
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.