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