MediaWiki  master
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  $op = $params['dir'] == 'descending' ? '<=' : '>=';
178  if ( $params['unique'] ) {
179  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string' ] );
180  $this->addWhere( $db->buildComparison( $op, [ $titleField => $cont[0] ] ) );
181  } else {
182  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'int' ] );
183  $this->addWhere( $db->buildComparison( $op, [
184  $titleField => $cont[0],
185  "{$pfx}from" => $cont[1],
186  ] ) );
187  }
188  }
189 
190  // 'continue' always overrides 'from'
191  $from = $continue || $params['from'] === null ? null :
192  $this->titlePartToKey( $params['from'], $namespace );
193  $to = $params['to'] === null ? null :
194  $this->titlePartToKey( $params['to'], $namespace );
195  $this->addWhereRange( $titleField, 'newer', $from, $to );
196 
197  if ( isset( $params['prefix'] ) ) {
198  $this->addWhere( $titleField . $db->buildLike( $this->titlePartToKey(
199  $params['prefix'], $namespace ), $db->anyString() ) );
200  }
201 
202  $this->addFields( [ 'pl_title' => $titleField ] );
203  $this->addFieldsIf( [ 'pl_from' => $pfx . 'from' ], !$params['unique'] );
204  foreach ( $this->props as $name => $field ) {
205  $this->addFieldsIf( $field, isset( $prop[$name] ) );
206  }
207 
208  $limit = $params['limit'];
209  $this->addOption( 'LIMIT', $limit + 1 );
210 
211  $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
212  $orderBy = [];
213  $orderBy[] = $titleField . $sort;
214  if ( !$params['unique'] ) {
215  $orderBy[] = $pfx . 'from' . $sort;
216  }
217  $this->addOption( 'ORDER BY', $orderBy );
218 
219  $res = $this->select( __METHOD__ );
220 
221  // Get gender information
222  if ( $resultPageSet === null && $res->numRows() && $this->namespaceInfo->hasGenderDistinction( $namespace ) ) {
223  $users = [];
224  foreach ( $res as $row ) {
225  $users[] = $row->pl_title;
226  }
227  if ( $users !== [] ) {
228  $this->genderCache->doQuery( $users, __METHOD__ );
229  }
230  }
231 
232  $pageids = [];
233  $titles = [];
234  $count = 0;
235  $result = $this->getResult();
236  foreach ( $res as $row ) {
237  if ( ++$count > $limit ) {
238  // We've reached the one extra which shows that there are
239  // additional pages to be had. Stop here...
240  if ( $params['unique'] ) {
241  $this->setContinueEnumParameter( 'continue', $row->pl_title );
242  } else {
243  $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
244  }
245  break;
246  }
247 
248  if ( $resultPageSet === null ) {
249  $vals = [
250  ApiResult::META_TYPE => 'assoc',
251  ];
252  if ( $fld_ids ) {
253  $vals['fromid'] = (int)$row->pl_from;
254  }
255  if ( $fld_title ) {
256  $title = Title::makeTitle( $namespace, $row->pl_title );
258  }
259  foreach ( $this->props as $name => $field ) {
260  if ( isset( $prop[$name] ) && $row->$field !== null && $row->$field !== '' ) {
261  $vals[$name] = $row->$field;
262  }
263  }
264  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
265  if ( !$fit ) {
266  if ( $params['unique'] ) {
267  $this->setContinueEnumParameter( 'continue', $row->pl_title );
268  } else {
269  $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
270  }
271  break;
272  }
273  } elseif ( $params['unique'] ) {
274  $titles[] = Title::makeTitle( $namespace, $row->pl_title );
275  } else {
276  $pageids[] = $row->pl_from;
277  }
278  }
279 
280  if ( $resultPageSet === null ) {
281  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], $this->indexTag );
282  } elseif ( $params['unique'] ) {
283  $resultPageSet->populateFromTitles( $titles );
284  } else {
285  $resultPageSet->populateFromPageIDs( $pageids );
286  }
287  }
288 
289  public function getAllowedParams() {
290  $allowedParams = [
291  'continue' => [
292  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
293  ],
294  'from' => null,
295  'to' => null,
296  'prefix' => null,
297  'unique' => false,
298  'prop' => [
299  ParamValidator::PARAM_ISMULTI => true,
300  ParamValidator::PARAM_DEFAULT => 'title',
301  ParamValidator::PARAM_TYPE => array_merge(
302  [ 'ids', 'title' ], array_keys( $this->props )
303  ),
305  ],
306  'namespace' => [
307  ParamValidator::PARAM_DEFAULT => $this->dfltNamespace,
308  ParamValidator::PARAM_TYPE => 'namespace',
309  NamespaceDef::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
310  ],
311  'limit' => [
312  ParamValidator::PARAM_DEFAULT => 10,
313  ParamValidator::PARAM_TYPE => 'limit',
314  IntegerDef::PARAM_MIN => 1,
315  IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
316  IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
317  ],
318  'dir' => [
319  ParamValidator::PARAM_DEFAULT => 'ascending',
320  ParamValidator::PARAM_TYPE => [
321  'ascending',
322  'descending'
323  ]
324  ],
325  ];
326  if ( !$this->hasNamespace ) {
327  unset( $allowedParams['namespace'] );
328  }
329 
330  return $allowedParams;
331  }
332 
333  protected function getExamplesMessages() {
334  $p = $this->getModulePrefix();
335  $name = $this->getModuleName();
336  $path = $this->getModulePath();
337 
338  return [
339  "action=query&list={$name}&{$p}from=B&{$p}prop=ids|title"
340  => "apihelp-$path-example-b",
341  "action=query&list={$name}&{$p}unique=&{$p}from=B"
342  => "apihelp-$path-example-unique",
343  "action=query&generator={$name}&g{$p}unique=&g{$p}from=B"
344  => "apihelp-$path-example-unique-generator",
345  "action=query&generator={$name}&g{$p}from=B"
346  => "apihelp-$path-example-generator",
347  ];
348  }
349 
350  public function getHelpUrls() {
351  $name = ucfirst( $this->getModuleName() );
352 
353  return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
354  }
355 }
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
$matches
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
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1689
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition: ApiBase.php:1645
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.
Definition: ApiResult.php:110
Caches user genders when needed to use correct namespace aliases.
Definition: GenderCache.php:34
Service for compat reading of links tables.
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.
Definition: IntegerDef.php:23