MediaWiki  master
ApiQueryExtLinksUsage.php
Go to the documentation of this file.
1 <?php
2 
28 
33 
38  public function __construct( ApiQuery $query, $moduleName ) {
39  parent::__construct( $query, $moduleName, 'eu' );
40  }
41 
42  public function execute() {
43  $this->run();
44  }
45 
46  public function getCacheMode( $params ) {
47  return 'public';
48  }
49 
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 = self::getProtocolPrefix( $params['protocol'] );
64 
65  $this->addTables( [ 'externallinks', 'page' ] );
66  $this->addJoinConds( [ 'page' => [ 'JOIN', 'page_id=el_from' ] ] );
67 
68  $miser_ns = [];
69  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
70  $miser_ns = $params['namespace'] ?: [];
71  } else {
72  $this->addWhereFld( 'page_namespace', $params['namespace'] );
73  }
74 
75  $orderBy = [];
76 
77  if ( $query !== null && $query !== '' ) {
78  if ( $protocol === null ) {
79  $protocol = 'http://';
80  }
81 
82  // Normalize query to match the normalization applied for the externallinks table
83  $query = Parser::normalizeLinkUrl( $protocol . $query );
84 
85  $conds = LinkFilter::getQueryConditions( $query, [
86  'protocol' => '',
87  'oneWildcard' => true,
88  'db' => $db
89  ] );
90  if ( !$conds ) {
91  $this->dieWithError( 'apierror-badquery' );
92  }
93  $this->addWhere( $conds );
94  if ( !isset( $conds['el_index_60'] ) ) {
95  $orderBy[] = 'el_index_60';
96  }
97  } else {
98  $orderBy[] = 'el_index_60';
99 
100  if ( $protocol !== null ) {
101  $this->addWhere( 'el_index_60' . $db->buildLike( "$protocol", $db->anyString() ) );
102  } else {
103  // We're querying all protocols, filter out duplicate protocol-relative links
104  $this->addWhere( $db->makeList( [
105  'el_to NOT' . $db->buildLike( '//', $db->anyString() ),
106  'el_index_60 ' . $db->buildLike( 'http://', $db->anyString() ),
107  ], LIST_OR ) );
108  }
109  }
110 
111  $orderBy[] = 'el_id';
112  $this->addOption( 'ORDER BY', $orderBy );
113  $this->addFields( $orderBy ); // Make sure
114 
115  $prop = array_fill_keys( $params['prop'], true );
116  $fld_ids = isset( $prop['ids'] );
117  $fld_title = isset( $prop['title'] );
118  $fld_url = isset( $prop['url'] );
119 
120  if ( $resultPageSet === null ) {
121  $this->addFields( [
122  'page_id',
123  'page_namespace',
124  'page_title'
125  ] );
126  $this->addFieldsIf( 'el_to', $fld_url );
127  } else {
128  $this->addFields( $resultPageSet->getPageTableFields() );
129  }
130 
131  $limit = $params['limit'];
132  $this->addOption( 'LIMIT', $limit + 1 );
133 
134  // T244254: Avoid MariaDB deciding to scan all of `page`.
135  $this->addOption( 'STRAIGHT_JOIN' );
136 
137  if ( $params['continue'] !== null ) {
138  $cont = explode( '|', $params['continue'] );
139  $this->dieContinueUsageIf( count( $cont ) !== count( $orderBy ) );
140  $i = count( $cont ) - 1;
141  $cond = $orderBy[$i] . ' >= ' . $db->addQuotes( rawurldecode( $cont[$i] ) );
142  while ( $i-- > 0 ) {
143  $field = $orderBy[$i];
144  $v = $db->addQuotes( rawurldecode( $cont[$i] ) );
145  $cond = "($field > $v OR ($field = $v AND $cond))";
146  }
147  $this->addWhere( $cond );
148  }
149 
150  $res = $this->select( __METHOD__ );
151 
152  $result = $this->getResult();
153 
154  if ( $resultPageSet === null ) {
155  $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
156  }
157 
158  $count = 0;
159  foreach ( $res as $row ) {
160  if ( ++$count > $limit ) {
161  // We've reached the one extra which shows that there are
162  // additional pages to be had. Stop here...
163  $this->setContinue( $orderBy, $row );
164  break;
165  }
166 
167  if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
168  continue;
169  }
170 
171  if ( $resultPageSet === null ) {
172  $vals = [
173  ApiResult::META_TYPE => 'assoc',
174  ];
175  if ( $fld_ids ) {
176  $vals['pageid'] = (int)$row->page_id;
177  }
178  if ( $fld_title ) {
179  $title = Title::makeTitle( $row->page_namespace, $row->page_title );
181  }
182  if ( $fld_url ) {
183  $to = $row->el_to;
184  // expand protocol-relative urls
185  if ( $params['expandurl'] ) {
186  $to = wfExpandUrl( $to, PROTO_CANONICAL );
187  }
188  $vals['url'] = $to;
189  }
190  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
191  if ( !$fit ) {
192  $this->setContinue( $orderBy, $row );
193  break;
194  }
195  } else {
196  $resultPageSet->processDbRow( $row );
197  }
198  }
199 
200  if ( $resultPageSet === null ) {
201  $result->addIndexedTagName( [ 'query', $this->getModuleName() ],
202  $this->getModulePrefix() );
203  }
204  }
205 
206  private function setContinue( $orderBy, $row ) {
207  $fields = [];
208  foreach ( $orderBy as $field ) {
209  $fields[] = strtr( $row->$field, [ '%' => '%25', '|' => '%7C' ] );
210  }
211  $this->setContinueEnumParameter( 'continue', implode( '|', $fields ) );
212  }
213 
214  public function getAllowedParams() {
215  $ret = [
216  'prop' => [
217  ParamValidator::PARAM_ISMULTI => true,
218  ParamValidator::PARAM_DEFAULT => 'ids|title|url',
219  ParamValidator::PARAM_TYPE => [
220  'ids',
221  'title',
222  'url'
223  ],
225  ],
226  'continue' => [
227  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
228  ],
229  'protocol' => [
230  ParamValidator::PARAM_TYPE => self::prepareProtocols(),
231  ParamValidator::PARAM_DEFAULT => '',
232  ],
233  'query' => null,
234  'namespace' => [
235  ParamValidator::PARAM_ISMULTI => true,
236  ParamValidator::PARAM_TYPE => 'namespace'
237  ],
238  'limit' => [
239  ParamValidator::PARAM_DEFAULT => 10,
240  ParamValidator::PARAM_TYPE => 'limit',
241  IntegerDef::PARAM_MIN => 1,
242  IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
243  IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
244  ],
245  'expandurl' => false,
246  ];
247 
248  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
249  $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
250  'api-help-param-limited-in-miser-mode',
251  ];
252  }
253 
254  return $ret;
255  }
256 
257  public static function prepareProtocols() {
258  $urlProtocols = MediaWikiServices::getInstance()->getMainConfig()
259  ->get( MainConfigNames::UrlProtocols );
260  $protocols = [ '' ];
261  foreach ( $urlProtocols as $p ) {
262  if ( $p !== '//' ) {
263  $protocols[] = substr( $p, 0, strpos( $p, ':' ) );
264  }
265  }
266 
267  return $protocols;
268  }
269 
270  public static function getProtocolPrefix( $protocol ) {
271  // Find the right prefix
272  $urlProtocols = MediaWikiServices::getInstance()->getMainConfig()
273  ->get( MainConfigNames::UrlProtocols );
274  if ( $protocol && !in_array( $protocol, $urlProtocols ) ) {
275  foreach ( $urlProtocols as $p ) {
276  if ( str_starts_with( $p, $protocol ) ) {
277  $protocol = $p;
278  break;
279  }
280  }
281 
282  return $protocol;
283  } else {
284  return null;
285  }
286  }
287 
288  protected function getExamplesMessages() {
289  return [
290  'action=query&list=exturlusage&euquery=www.mediawiki.org'
291  => 'apihelp-query+exturlusage-example-simple',
292  ];
293  }
294 
295  public function getHelpUrls() {
296  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Exturlusage';
297  }
298 }
const PROTO_CANONICAL
Definition: Defines.php:199
const LIST_OR
Definition: Defines.php:46
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1453
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:506
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition: ApiBase.php:1645
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:170
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:196
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:221
getResult()
Get the result object.
Definition: ApiBase.php:629
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:765
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:163
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:223
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:498
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addFields( $value)
Add a set of fields to select to the internal array.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
getDB()
Get the Query database connection (read-only)
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addWhere( $value)
Add a set of WHERE clauses to the internal array.
executeGenerator( $resultPageSet)
Execute this module as a generator.
getExamplesMessages()
Returns usage examples for this module.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getHelpUrls()
Return links to more detailed help pages about the module.
getCacheMode( $params)
Get the cache mode for the data generated by this module.
static getProtocolPrefix( $protocol)
__construct(ApiQuery $query, $moduleName)
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
This is the main query class.
Definition: ApiQuery.php:41
const META_TYPE
Key for the 'type' metadata item.
Definition: ApiResult.php:110
static getQueryConditions( $filterEntry, array $options=[])
Return query conditions which will match the specified string.
Definition: LinkFilter.php:252
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
static normalizeLinkUrl( $url)
Replace unusual escape codes in a URL with their equivalent characters.
Definition: Parser.php:2316
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:638
Service for formatting and validating API parameters.
Type definition for integer types.
Definition: IntegerDef.php:23