MediaWiki REL1_39
ApiQueryAllLinks.php
Go to the documentation of this file.
1<?php
27
34
35 private $table, $tablePrefix, $indexTag;
36 private $fieldTitle = 'title';
37 private $dfltNamespace = NS_MAIN;
38 private $hasNamespace = true;
39 private $useIndex = null;
40 private $props = [];
41
43 private $namespaceInfo;
44
46 private $genderCache;
47
49 private $linksMigration;
50
58 public function __construct(
59 ApiQuery $query,
60 $moduleName,
61 NamespaceInfo $namespaceInfo,
62 GenderCache $genderCache,
63 LinksMigration $linksMigration
64 ) {
65 switch ( $moduleName ) {
66 case 'alllinks':
67 $prefix = 'al';
68 $this->table = 'pagelinks';
69 $this->tablePrefix = 'pl_';
70 $this->useIndex = 'pl_namespace';
71 $this->indexTag = 'l';
72 break;
73 case 'alltransclusions':
74 $prefix = 'at';
75 $this->table = 'templatelinks';
76 $this->tablePrefix = 'tl_';
77 $this->dfltNamespace = NS_TEMPLATE;
78 $this->useIndex = 'tl_namespace';
79 $this->indexTag = 't';
80 break;
81 case 'allfileusages':
82 $prefix = 'af';
83 $this->table = 'imagelinks';
84 $this->tablePrefix = 'il_';
85 $this->fieldTitle = 'to';
86 $this->dfltNamespace = NS_FILE;
87 $this->hasNamespace = false;
88 $this->indexTag = 'f';
89 break;
90 case 'allredirects':
91 $prefix = 'ar';
92 $this->table = 'redirect';
93 $this->tablePrefix = 'rd_';
94 $this->indexTag = 'r';
95 $this->props = [
96 'fragment' => 'rd_fragment',
97 'interwiki' => 'rd_interwiki',
98 ];
99 break;
100 default:
101 ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
102 }
103
104 parent::__construct( $query, $moduleName, $prefix );
105 $this->namespaceInfo = $namespaceInfo;
106 $this->genderCache = $genderCache;
107 $this->linksMigration = $linksMigration;
108 }
109
110 public function execute() {
111 $this->run();
112 }
113
114 public function getCacheMode( $params ) {
115 return 'public';
116 }
117
118 public function executeGenerator( $resultPageSet ) {
119 $this->run( $resultPageSet );
120 }
121
126 private function run( $resultPageSet = null ) {
127 $db = $this->getDB();
128 $params = $this->extractRequestParams();
129
130 $pfx = $this->tablePrefix;
131
132 $nsField = $pfx . 'namespace';
133 $titleField = $pfx . $this->fieldTitle;
134 if ( isset( $this->linksMigration::$mapping[$this->table] ) ) {
135 list( $nsField, $titleField ) = $this->linksMigration->getTitleFields( $this->table );
136 $queryInfo = $this->linksMigration->getQueryInfo( $this->table );
137 $this->addTables( $queryInfo['tables'] );
138 $this->addJoinConds( $queryInfo['joins'] );
139 } else {
140 if ( $this->useIndex ) {
141 $this->addOption( 'USE INDEX', $this->useIndex );
142 }
143 $this->addTables( $this->table );
144 }
145
146 $prop = array_fill_keys( $params['prop'], true );
147 $fld_ids = isset( $prop['ids'] );
148 $fld_title = isset( $prop['title'] );
149 if ( $this->hasNamespace ) {
150 $namespace = $params['namespace'];
151 } else {
152 $namespace = $this->dfltNamespace;
153 }
154
155 if ( $params['unique'] ) {
156 $matches = array_intersect_key( $prop, $this->props + [ 'ids' => 1 ] );
157 if ( $matches ) {
158 $p = $this->getModulePrefix();
159 $this->dieWithError(
160 [
161 'apierror-invalidparammix-cannotusewith',
162 "{$p}prop=" . implode( '|', array_keys( $matches ) ),
163 "{$p}unique"
164 ],
165 'invalidparammix'
166 );
167 }
168 $this->addOption( 'DISTINCT' );
169 }
170
171 if ( $this->hasNamespace ) {
172 $this->addWhereFld( $nsField, $namespace );
173 }
174
175 $continue = $params['continue'] !== null;
176 if ( $continue ) {
177 $continueArr = explode( '|', $params['continue'] );
178 $op = $params['dir'] == 'descending' ? '<' : '>';
179 if ( $params['unique'] ) {
180 $this->dieContinueUsageIf( count( $continueArr ) != 1 );
181 $continueTitle = $db->addQuotes( $continueArr[0] );
182 $this->addWhere( "{$titleField} $op= $continueTitle" );
183 } else {
184 $this->dieContinueUsageIf( count( $continueArr ) != 2 );
185 $continueTitle = $db->addQuotes( $continueArr[0] );
186 $continueFrom = (int)$continueArr[1];
187 $this->addWhere(
188 "{$titleField} $op $continueTitle OR " .
189 "({$titleField} = $continueTitle AND " .
190 "{$pfx}from $op= $continueFrom)"
191 );
192 }
193 }
194
195 // 'continue' always overrides 'from'
196 $from = $continue || $params['from'] === null ? null :
197 $this->titlePartToKey( $params['from'], $namespace );
198 $to = $params['to'] === null ? null :
199 $this->titlePartToKey( $params['to'], $namespace );
200 $this->addWhereRange( $titleField, 'newer', $from, $to );
201
202 if ( isset( $params['prefix'] ) ) {
203 $this->addWhere( $titleField . $db->buildLike( $this->titlePartToKey(
204 $params['prefix'], $namespace ), $db->anyString() ) );
205 }
206
207 $this->addFields( [ 'pl_title' => $titleField ] );
208 $this->addFieldsIf( [ 'pl_from' => $pfx . 'from' ], !$params['unique'] );
209 foreach ( $this->props as $name => $field ) {
210 $this->addFieldsIf( $field, isset( $prop[$name] ) );
211 }
212
213 $limit = $params['limit'];
214 $this->addOption( 'LIMIT', $limit + 1 );
215
216 $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
217 $orderBy = [];
218 $orderBy[] = $titleField . $sort;
219 if ( !$params['unique'] ) {
220 $orderBy[] = $pfx . 'from' . $sort;
221 }
222 $this->addOption( 'ORDER BY', $orderBy );
223
224 $res = $this->select( __METHOD__ );
225
226 // Get gender information
227 if ( $resultPageSet === null && $res->numRows() && $this->namespaceInfo->hasGenderDistinction( $namespace ) ) {
228 $users = [];
229 foreach ( $res as $row ) {
230 $users[] = $row->pl_title;
231 }
232 if ( $users !== [] ) {
233 $this->genderCache->doQuery( $users, __METHOD__ );
234 }
235 }
236
237 $pageids = [];
238 $titles = [];
239 $count = 0;
240 $result = $this->getResult();
241 foreach ( $res as $row ) {
242 if ( ++$count > $limit ) {
243 // We've reached the one extra which shows that there are
244 // additional pages to be had. Stop here...
245 if ( $params['unique'] ) {
246 $this->setContinueEnumParameter( 'continue', $row->pl_title );
247 } else {
248 $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
249 }
250 break;
251 }
252
253 if ( $resultPageSet === null ) {
254 $vals = [
255 ApiResult::META_TYPE => 'assoc',
256 ];
257 if ( $fld_ids ) {
258 $vals['fromid'] = (int)$row->pl_from;
259 }
260 if ( $fld_title ) {
261 $title = Title::makeTitle( $namespace, $row->pl_title );
263 }
264 foreach ( $this->props as $name => $field ) {
265 if ( isset( $prop[$name] ) && $row->$field !== null && $row->$field !== '' ) {
266 $vals[$name] = $row->$field;
267 }
268 }
269 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
270 if ( !$fit ) {
271 if ( $params['unique'] ) {
272 $this->setContinueEnumParameter( 'continue', $row->pl_title );
273 } else {
274 $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
275 }
276 break;
277 }
278 } elseif ( $params['unique'] ) {
279 $titles[] = Title::makeTitle( $namespace, $row->pl_title );
280 } else {
281 $pageids[] = $row->pl_from;
282 }
283 }
284
285 if ( $resultPageSet === null ) {
286 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], $this->indexTag );
287 } elseif ( $params['unique'] ) {
288 $resultPageSet->populateFromTitles( $titles );
289 } else {
290 $resultPageSet->populateFromPageIDs( $pageids );
291 }
292 }
293
294 public function getAllowedParams() {
295 $allowedParams = [
296 'continue' => [
297 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
298 ],
299 'from' => null,
300 'to' => null,
301 'prefix' => null,
302 'unique' => false,
303 'prop' => [
304 ParamValidator::PARAM_ISMULTI => true,
305 ParamValidator::PARAM_DEFAULT => 'title',
306 ParamValidator::PARAM_TYPE => array_merge(
307 [ 'ids', 'title' ], array_keys( $this->props )
308 ),
310 ],
311 'namespace' => [
312 ParamValidator::PARAM_DEFAULT => $this->dfltNamespace,
313 ParamValidator::PARAM_TYPE => 'namespace',
314 NamespaceDef::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
315 ],
316 'limit' => [
317 ParamValidator::PARAM_DEFAULT => 10,
318 ParamValidator::PARAM_TYPE => 'limit',
319 IntegerDef::PARAM_MIN => 1,
320 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
321 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
322 ],
323 'dir' => [
324 ParamValidator::PARAM_DEFAULT => 'ascending',
325 ParamValidator::PARAM_TYPE => [
326 'ascending',
327 'descending'
328 ]
329 ],
330 ];
331 if ( !$this->hasNamespace ) {
332 unset( $allowedParams['namespace'] );
333 }
334
335 return $allowedParams;
336 }
337
338 protected function getExamplesMessages() {
339 $p = $this->getModulePrefix();
340 $name = $this->getModuleName();
341 $path = $this->getModulePath();
342
343 return [
344 "action=query&list={$name}&{$p}from=B&{$p}prop=ids|title"
345 => "apihelp-$path-example-b",
346 "action=query&list={$name}&{$p}unique=&{$p}from=B"
347 => "apihelp-$path-example-unique",
348 "action=query&generator={$name}&g{$p}unique=&g{$p}from=B"
349 => "apihelp-$path-example-unique-generator",
350 "action=query&generator={$name}&g{$p}from=B"
351 => "apihelp-$path-example-generator",
352 ];
353 }
354
355 public function getHelpUrls() {
356 $name = ucfirst( $this->getModuleName() );
357
358 return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
359 }
360}
const NS_FILE
Definition Defines.php:70
const NS_MAIN
Definition Defines.php:64
const NS_TEMPLATE
Definition Defines.php:74
const NS_SPECIAL
Definition Defines.php:53
const NS_MEDIA
Definition Defines.php:52
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1454
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:1643
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1656
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
getModulePath()
Get the path to this module.
Definition ApiBase.php:573
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.
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
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)
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 ] )
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
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.
Caches user genders when needed to use correct namespace aliases.
Service for compat reading of links tables.
Type definition for namespace types.
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
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.