MediaWiki master
ApiQueryExtLinksUsage.php
Go to the documentation of this file.
1<?php
2
10namespace MediaWiki\Api;
11
22
27
28 private UrlUtils $urlUtils;
29
30 public function __construct(
31 ApiQuery $query,
32 string $moduleName,
33 UrlUtils $urlUtils
34 ) {
35 parent::__construct( $query, $moduleName, 'eu' );
36
37 $this->urlUtils = $urlUtils;
38 }
39
40 public function execute() {
41 $this->run();
42 }
43
45 public function getCacheMode( $params ) {
46 return 'public';
47 }
48
50 public function executeGenerator( $resultPageSet ) {
51 $this->run( $resultPageSet );
52 }
53
58 private function run( $resultPageSet = null ) {
59 $params = $this->extractRequestParams();
60 $db = $this->getDB();
61
62 $query = $params['query'];
63 $protocol = LinkFilter::getProtocolPrefix( $params['protocol'] );
64
65 $this->addTables( [ 'externallinks', 'page' ] );
66 $this->addJoinConds( [ 'page' => [ 'JOIN', 'page_id=el_from' ] ] );
67 $fields = [ 'el_to_domain_index', 'el_to_path' ];
68
69 $miser_ns = [];
70 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
71 $miser_ns = $params['namespace'] ?: [];
72 } else {
73 $this->addWhereFld( 'page_namespace', $params['namespace'] );
74 }
75 if ( $query !== null && $query !== '' ) {
76 // Normalize query to match the normalization applied for the externallinks table
77 $query = Parser::normalizeLinkUrl( $query );
78 $conds = LinkFilter::getQueryConditions( $query, [
79 'protocol' => $protocol,
80 'oneWildcard' => true,
81 'db' => $db
82 ] );
83 if ( !$conds ) {
84 $this->dieWithError( 'apierror-badquery' );
85 }
86 $this->addWhere( $conds );
87 } else {
88 if ( $protocol !== null ) {
89 $this->addWhere(
90 $db->expr( 'el_to_domain_index', IExpression::LIKE, new LikeValue( "$protocol", $db->anyString() ) )
91 );
92 }
93 }
94 $orderBy = [ 'el_id' ];
95
96 $this->addOption( 'ORDER BY', $orderBy );
97 $this->addFields( $orderBy ); // Make sure
98
99 $prop = array_fill_keys( $params['prop'], true );
100 $fld_ids = isset( $prop['ids'] );
101 $fld_title = isset( $prop['title'] );
102 $fld_url = isset( $prop['url'] );
103
104 if ( $resultPageSet === null ) {
105 $this->addFields( [
106 'page_id',
107 'page_namespace',
108 'page_title'
109 ] );
110 foreach ( $fields as $field ) {
111 $this->addFieldsIf( $field, $fld_url );
112 }
113 } else {
114 $this->addFields( $resultPageSet->getPageTableFields() );
115 }
116
117 $limit = $params['limit'];
118 $this->addOption( 'LIMIT', $limit + 1 );
119
120 // T244254: Avoid MariaDB deciding to scan all of `page`.
121 $this->addOption( 'STRAIGHT_JOIN' );
122
123 if ( $params['continue'] !== null ) {
124 $cont = $this->parseContinueParamOrDie( $params['continue'],
125 array_fill( 0, count( $orderBy ), 'string' ) );
126 $conds = array_combine( $orderBy, array_map( 'rawurldecode', $cont ) );
127 $this->addWhere( $db->buildComparison( '>=', $conds ) );
128 }
129
130 $this->setVirtualDomain( ExternalLinksTable::VIRTUAL_DOMAIN );
131 $res = $this->select( __METHOD__ );
132 $this->resetVirtualDomain();
133
134 $result = $this->getResult();
135
136 if ( $resultPageSet === null ) {
137 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
138 }
139
140 $count = 0;
141 foreach ( $res as $row ) {
142 if ( ++$count > $limit ) {
143 // We've reached the one extra which shows that there are
144 // additional pages to be had. Stop here...
145 $this->setContinue( $orderBy, $row );
146 break;
147 }
148
149 if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
150 continue;
151 }
152
153 if ( $resultPageSet === null ) {
154 $vals = [
155 ApiResult::META_TYPE => 'assoc',
156 ];
157 if ( $fld_ids ) {
158 $vals['pageid'] = (int)$row->page_id;
159 }
160 if ( $fld_title ) {
161 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
162 ApiQueryBase::addTitleInfo( $vals, $title );
163 }
164 if ( $fld_url ) {
165 $to = LinkFilter::reverseIndexes( $row->el_to_domain_index ) . $row->el_to_path;
166 // expand protocol-relative urls
167 if ( $params['expandurl'] ) {
168 $to = (string)$this->urlUtils->expand( $to, PROTO_CANONICAL );
169 }
170 $vals['url'] = $to;
171 }
172 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
173 if ( !$fit ) {
174 $this->setContinue( $orderBy, $row );
175 break;
176 }
177 } else {
178 $resultPageSet->processDbRow( $row );
179 }
180 }
181
182 if ( $resultPageSet === null ) {
183 $result->addIndexedTagName( [ 'query', $this->getModuleName() ],
184 $this->getModulePrefix() );
185 }
186 }
187
188 private function setContinue( array $orderBy, \stdClass $row ) {
189 $fields = [];
190 foreach ( $orderBy as $field ) {
191 $fields[] = strtr( $row->$field, [ '%' => '%25', '|' => '%7C' ] );
192 }
193 $this->setContinueEnumParameter( 'continue', implode( '|', $fields ) );
194 }
195
197 public function getAllowedParams() {
198 $ret = [
199 'prop' => [
200 ParamValidator::PARAM_ISMULTI => true,
201 ParamValidator::PARAM_DEFAULT => 'ids|title|url',
202 ParamValidator::PARAM_TYPE => [
203 'ids',
204 'title',
205 'url'
206 ],
208 ],
209 'continue' => [
210 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
211 ],
212 'protocol' => [
213 ParamValidator::PARAM_TYPE => LinkFilter::prepareProtocols(),
214 ParamValidator::PARAM_DEFAULT => '',
215 ],
216 'query' => null,
217 'namespace' => [
218 ParamValidator::PARAM_ISMULTI => true,
219 ParamValidator::PARAM_TYPE => 'namespace'
220 ],
221 'limit' => [
222 ParamValidator::PARAM_DEFAULT => 10,
223 ParamValidator::PARAM_TYPE => 'limit',
224 IntegerDef::PARAM_MIN => 1,
225 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
226 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
227 ],
228 'expandurl' => [
229 ParamValidator::PARAM_TYPE => 'boolean',
230 ParamValidator::PARAM_DEFAULT => false,
231 ParamValidator::PARAM_DEPRECATED => true,
232 ],
233 ];
234
235 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
236 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
237 'api-help-param-limited-in-miser-mode',
238 ];
239 }
240
241 return $ret;
242 }
243
245 protected function getExamplesMessages() {
246 return [
247 'action=query&list=exturlusage&euquery=www.mediawiki.org'
248 => 'apihelp-query+exturlusage-example-simple',
249 ];
250 }
251
253 public function getHelpUrls() {
254 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Exturlusage';
255 }
256}
257
259class_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:1511
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:552
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:543
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1696
getResult()
Get the result object.
Definition ApiBase.php:682
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:207
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:175
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:167
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:234
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:823
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:232
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...
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: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:135
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.