Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\IDatabase;
24 use Wikimedia\Rdbms\IResultWrapper;
25
26 /**
27 * This is a base class for all Query modules.
28 * It provides some common functionality such as constructing various SQL
29 * queries.
30 *
31 * @ingroup API
32 */
33 abstract class ApiQueryBase extends ApiBase {
34
35 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
36
37 /**
38 * @param ApiQuery $queryModule
39 * @param string $moduleName
40 * @param string $paramPrefix
41 */
42 public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
43 parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule = $queryModule;
45 $this->mDb = null;
46 $this->resetQueryParams();
47 }
48
49 /************************************************************************//**
50 * @name Methods to implement
51 * @{
52 */
53
54 /**
55 * Get the cache mode for the data generated by this module. Override
56 * this in the module subclass. For possible return values and other
57 * details about cache modes, see ApiMain::setCacheMode()
58 *
59 * Public caching will only be allowed if *all* the modules that supply
60 * data for a given request return a cache mode of public.
61 *
62 * @param array $params
63 * @return string
64 */
65 public function getCacheMode( $params ) {
66 return 'private';
67 }
68
69 /**
70 * Override this method to request extra fields from the pageSet
71 * using $pageSet->requestField('fieldName')
72 *
73 * Note this only makes sense for 'prop' modules, as 'list' and 'meta'
74 * modules should not be using the pageset.
75 *
76 * @param ApiPageSet $pageSet
77 */
78 public function requestExtraData( $pageSet ) {
79 }
80
81 /**@}*/
82
83 /************************************************************************//**
84 * @name Data access
85 * @{
86 */
87
88 /**
89 * Get the main Query module
90 * @return ApiQuery
91 */
92 public function getQuery() {
93 return $this->mQueryModule;
94 }
95
96 /** @inheritDoc */
97 public function getParent() {
98 return $this->getQuery();
99 }
100
101 /**
102 * Get the Query database connection (read-only)
103 * @return IDatabase
104 */
105 protected function getDB() {
106 if ( is_null( $this->mDb ) ) {
107 $this->mDb = $this->getQuery()->getDB();
108 }
109
110 return $this->mDb;
111 }
112
113 /**
114 * Selects the query database connection with the given name.
115 * See ApiQuery::getNamedDB() for more information
116 * @param string $name Name to assign to the database connection
117 * @param int $db One of the DB_* constants
118 * @param string|string[] $groups Query groups
119 * @return IDatabase
120 */
121 public function selectNamedDB( $name, $db, $groups ) {
122 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
123 return $this->mDb;
124 }
125
126 /**
127 * Get the PageSet object to work on
128 * @return ApiPageSet
129 */
130 protected function getPageSet() {
131 return $this->getQuery()->getPageSet();
132 }
133
134 /**@}*/
135
136 /************************************************************************//**
137 * @name Querying
138 * @{
139 */
140
141 /**
142 * Blank the internal arrays with query parameters
143 */
144 protected function resetQueryParams() {
145 $this->tables = [];
146 $this->where = [];
147 $this->fields = [];
148 $this->options = [];
149 $this->join_conds = [];
150 }
151
152 /**
153 * Add a set of tables to the internal array
154 * @param string|array $tables Table name or array of table names
155 * or nested arrays for joins using parentheses for grouping
156 * @param string|null $alias Table alias, or null for no alias. Cannot be
157 * used with multiple tables
158 */
159 protected function addTables( $tables, $alias = null ) {
160 if ( is_array( $tables ) ) {
161 if ( $alias !== null ) {
162 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
163 }
164 $this->tables = array_merge( $this->tables, $tables );
165 } elseif ( $alias !== null ) {
166 $this->tables[$alias] = $tables;
167 } else {
168 $this->tables[] = $tables;
169 }
170 }
171
172 /**
173 * Add a set of JOIN conditions to the internal array
174 *
175 * JOIN conditions are formatted as [ tablename => [ jointype, conditions ] ]
176 * e.g. [ 'page' => [ 'LEFT JOIN', 'page_id=rev_page' ] ].
177 * Conditions may be a string or an addWhere()-style array.
178 * @param array $join_conds JOIN conditions
179 */
180 protected function addJoinConds( $join_conds ) {
181 if ( !is_array( $join_conds ) ) {
182 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
183 }
184 $this->join_conds = array_merge( $this->join_conds, $join_conds );
185 }
186
187 /**
188 * Add a set of fields to select to the internal array
189 * @param array|string $value Field name or array of field names
190 */
191 protected function addFields( $value ) {
192 if ( is_array( $value ) ) {
193 $this->fields = array_merge( $this->fields, $value );
194 } else {
195 $this->fields[] = $value;
196 }
197 }
198
199 /**
200 * Same as addFields(), but add the fields only if a condition is met
201 * @param array|string $value See addFields()
202 * @param bool $condition If false, do nothing
203 * @return bool $condition
204 */
205 protected function addFieldsIf( $value, $condition ) {
206 if ( $condition ) {
207 $this->addFields( $value );
208
209 return true;
210 }
211
212 return false;
213 }
214
215 /**
216 * Add a set of WHERE clauses to the internal array.
217 * Clauses can be formatted as 'foo=bar' or [ 'foo' => 'bar' ],
218 * the latter only works if the value is a constant (i.e. not another field)
219 *
220 * If $value is an empty array, this function does nothing.
221 *
222 * For example, [ 'foo=bar', 'baz' => 3, 'bla' => 'foo' ] translates
223 * to "foo=bar AND baz='3' AND bla='foo'"
224 * @param string|array $value
225 */
226 protected function addWhere( $value ) {
227 if ( is_array( $value ) ) {
228 // Sanity check: don't insert empty arrays,
229 // Database::makeList() chokes on them
230 if ( count( $value ) ) {
231 $this->where = array_merge( $this->where, $value );
232 }
233 } else {
234 $this->where[] = $value;
235 }
236 }
237
238 /**
239 * Same as addWhere(), but add the WHERE clauses only if a condition is met
240 * @param string|array $value
241 * @param bool $condition If false, do nothing
242 * @return bool $condition
243 */
244 protected function addWhereIf( $value, $condition ) {
245 if ( $condition ) {
246 $this->addWhere( $value );
247
248 return true;
249 }
250
251 return false;
252 }
253
254 /**
255 * Equivalent to addWhere( [ $field => $value ] )
256 * @param string $field Field name
257 * @param string|string[] $value Value; ignored if null or empty array
258 */
259 protected function addWhereFld( $field, $value ) {
260 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
261 $this->where[$field] = $value;
262 }
263 }
264
265 /**
266 * Like addWhereFld for an integer list of IDs
267 * @since 1.33
268 * @param string $table Table name
269 * @param string $field Field name
270 * @param int[] $ids IDs
271 * @return int Count of IDs actually included
272 */
273 protected function addWhereIDsFld( $table, $field, $ids ) {
274 // Use count() to its full documented capabilities to simultaneously
275 // test for null, empty array or empty countable object
276 if ( count( $ids ) ) {
277 $ids = $this->filterIDs( [ [ $table, $field ] ], $ids );
278
279 if ( $ids === [] ) {
280 // Return nothing, no IDs are valid
281 $this->where[] = '0 = 1';
282 } else {
283 $this->where[$field] = $ids;
284 }
285 }
286 return count( $ids );
287 }
288
289 /**
290 * Add a WHERE clause corresponding to a range, and an ORDER BY
291 * clause to sort in the right direction
292 * @param string $field Field name
293 * @param string $dir If 'newer', sort in ascending order, otherwise
294 * sort in descending order
295 * @param string $start Value to start the list at. If $dir == 'newer'
296 * this is the lower boundary, otherwise it's the upper boundary
297 * @param string $end Value to end the list at. If $dir == 'newer' this
298 * is the upper boundary, otherwise it's the lower boundary
299 * @param bool $sort If false, don't add an ORDER BY clause
300 */
301 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
302 $isDirNewer = ( $dir === 'newer' );
303 $after = ( $isDirNewer ? '>=' : '<=' );
304 $before = ( $isDirNewer ? '<=' : '>=' );
305 $db = $this->getDB();
306
307 if ( !is_null( $start ) ) {
308 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
309 }
310
311 if ( !is_null( $end ) ) {
312 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
313 }
314
315 if ( $sort ) {
316 $order = $field . ( $isDirNewer ? '' : ' DESC' );
317 // Append ORDER BY
318 $optionOrderBy = isset( $this->options['ORDER BY'] )
319 ? (array)$this->options['ORDER BY']
320 : [];
321 $optionOrderBy[] = $order;
322 $this->addOption( 'ORDER BY', $optionOrderBy );
323 }
324 }
325
326 /**
327 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
328 * but converts $start and $end to database timestamps.
329 * @see addWhereRange
330 * @param string $field
331 * @param string $dir
332 * @param string $start
333 * @param string $end
334 * @param bool $sort
335 */
336 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
337 $db = $this->getDB();
338 $this->addWhereRange( $field, $dir,
339 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
340 }
341
342 /**
343 * Add an option such as LIMIT or USE INDEX. If an option was set
344 * before, the old value will be overwritten
345 * @param string $name Option name
346 * @param string|string[]|null $value Option value
347 */
348 protected function addOption( $name, $value = null ) {
349 if ( is_null( $value ) ) {
350 $this->options[] = $name;
351 } else {
352 $this->options[$name] = $value;
353 }
354 }
355
356 /**
357 * Execute a SELECT query based on the values in the internal arrays
358 * @param string $method Function the query should be attributed to.
359 * You should usually use __METHOD__ here
360 * @param array $extraQuery Query data to add but not store in the object
361 * Format is [
362 * 'tables' => ...,
363 * 'fields' => ...,
364 * 'where' => ...,
365 * 'options' => ...,
366 * 'join_conds' => ...
367 * ]
368 * @param array|null &$hookData If set, the ApiQueryBaseBeforeQuery and
369 * ApiQueryBaseAfterQuery hooks will be called, and the
370 * ApiQueryBaseProcessRow hook will be expected.
371 * @return IResultWrapper
372 */
373 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
374 $tables = array_merge(
375 $this->tables,
376 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : []
377 );
378 $fields = array_merge(
379 $this->fields,
380 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : []
381 );
382 $where = array_merge(
383 $this->where,
384 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : []
385 );
386 $options = array_merge(
387 $this->options,
388 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : []
389 );
390 $join_conds = array_merge(
391 $this->join_conds,
392 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : []
393 );
394
395 if ( $hookData !== null ) {
396 Hooks::run( 'ApiQueryBaseBeforeQuery',
397 [ $this, &$tables, &$fields, &$where, &$options, &$join_conds, &$hookData ]
398 );
399 }
400
401 $res = $this->getDB()->select( $tables, $fields, $where, $method, $options, $join_conds );
402
403 if ( $hookData !== null ) {
404 Hooks::run( 'ApiQueryBaseAfterQuery', [ $this, $res, &$hookData ] );
405 }
406
407 return $res;
408 }
409
410 /**
411 * Call the ApiQueryBaseProcessRow hook
412 *
413 * Generally, a module that passed $hookData to self::select() will call
414 * this just before calling ApiResult::addValue(), and treat a false return
415 * here in the same way it treats a false return from addValue().
416 *
417 * @since 1.28
418 * @param object $row Database row
419 * @param array &$data Data to be added to the result
420 * @param array &$hookData Hook data from ApiQueryBase::select()
421 * @return bool Return false if row processing should end with continuation
422 */
423 protected function processRow( $row, array &$data, array &$hookData ) {
424 return Hooks::run( 'ApiQueryBaseProcessRow', [ $this, $row, &$data, &$hookData ] );
425 }
426
427 /**
428 * Filters hidden users (where the user doesn't have the right to view them)
429 * Also adds relevant block information
430 *
431 * @param bool $showBlockInfo
432 * @return void
433 */
434 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
435 $db = $this->getDB();
436
437 $tables = [ 'ipblocks' ];
438 $fields = [ 'ipb_deleted' ];
439 $joinConds = [
440 'blk' => [ 'LEFT JOIN', [
441 'ipb_user=user_id',
442 'ipb_expiry > ' . $db->addQuotes( $db->timestamp() ),
443 ] ],
444 ];
445
446 if ( $showBlockInfo ) {
447 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
448 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
449 $tables += $actorQuery['tables'] + $commentQuery['tables'];
450 $joinConds += $actorQuery['joins'] + $commentQuery['joins'];
451 $fields = array_merge( $fields, [
452 'ipb_id',
453 'ipb_expiry',
454 'ipb_timestamp'
455 ], $actorQuery['fields'], $commentQuery['fields'] );
456 }
457
458 $this->addTables( [ 'blk' => $tables ] );
459 $this->addFields( $fields );
460 $this->addJoinConds( $joinConds );
461
462 // Don't show hidden names
463 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
464 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
465 }
466 }
467
468 /**@}*/
469
470 /************************************************************************//**
471 * @name Utility methods
472 * @{
473 */
474
475 /**
476 * Add information (title and namespace) about a Title object to a
477 * result array
478 * @param array &$arr Result array à la ApiResult
479 * @param Title $title
480 * @param string $prefix Module prefix
481 */
482 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
483 $arr[$prefix . 'ns'] = (int)$title->getNamespace();
484 $arr[$prefix . 'title'] = $title->getPrefixedText();
485 }
486
487 /**
488 * Add a sub-element under the page element with the given page ID
489 * @param int $pageId Page ID
490 * @param array $data Data array à la ApiResult
491 * @return bool Whether the element fit in the result
492 */
493 protected function addPageSubItems( $pageId, $data ) {
494 $result = $this->getResult();
495 ApiResult::setIndexedTagName( $data, $this->getModulePrefix() );
496
497 return $result->addValue( [ 'query', 'pages', (int)$pageId ],
498 $this->getModuleName(),
499 $data );
500 }
501
502 /**
503 * Same as addPageSubItems(), but one element of $data at a time
504 * @param int $pageId Page ID
505 * @param mixed $item Data à la ApiResult
506 * @param string|null $elemname XML element name. If null, getModuleName()
507 * is used
508 * @return bool Whether the element fit in the result
509 */
510 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
511 if ( is_null( $elemname ) ) {
512 $elemname = $this->getModulePrefix();
513 }
514 $result = $this->getResult();
515 $fit = $result->addValue( [ 'query', 'pages', $pageId,
516 $this->getModuleName() ], null, $item );
517 if ( !$fit ) {
518 return false;
519 }
520 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
521 $this->getModuleName() ], $elemname );
522
523 return true;
524 }
525
526 /**
527 * Set a query-continue value
528 * @param string $paramName Parameter name
529 * @param string|array $paramValue Parameter value
530 */
531 protected function setContinueEnumParameter( $paramName, $paramValue ) {
532 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
533 }
534
535 /**
536 * Convert an input title or title prefix into a dbkey.
537 *
538 * $namespace should always be specified in order to handle per-namespace
539 * capitalization settings.
540 *
541 * @param string $titlePart Title part
542 * @param int $namespace Namespace of the title
543 * @return string DBkey (no namespace prefix)
544 */
545 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
546 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
547 if ( !$t || $t->hasFragment() ) {
548 // Invalid title (e.g. bad chars) or contained a '#'.
549 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
550 }
551 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
552 // This can happen in two cases. First, if you call titlePartToKey with a title part
553 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
554 // difficult to handle such a case. Such cases cannot exist and are therefore treated
555 // as invalid user input. The second case is when somebody specifies a title interwiki
556 // prefix.
557 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
558 }
559
560 return substr( $t->getDBkey(), 0, -1 );
561 }
562
563 /**
564 * Convert an input title or title prefix into a namespace constant and dbkey.
565 *
566 * @since 1.26
567 * @param string $titlePart Title part
568 * @param int $defaultNamespace Default namespace if none is given
569 * @return array (int, string) Namespace number and DBkey
570 */
571 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
572 $t = Title::newFromText( $titlePart . 'x', $defaultNamespace );
573 if ( !$t || $t->hasFragment() || $t->isExternal() ) {
574 // Invalid title (e.g. bad chars) or contained a '#'.
575 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
576 }
577
578 return [ $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) ];
579 }
580
581 /**
582 * @param string $hash
583 * @return bool
584 */
585 public function validateSha1Hash( $hash ) {
586 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
587 }
588
589 /**
590 * @param string $hash
591 * @return bool
592 */
593 public function validateSha1Base36Hash( $hash ) {
594 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
595 }
596
597 /**
598 * Check whether the current user has permission to view revision-deleted
599 * fields.
600 * @return bool
601 */
602 public function userCanSeeRevDel() {
603 return $this->getUser()->isAllowedAny(
604 'deletedhistory',
605 'deletedtext',
606 'suppressrevision',
607 'viewsuppressed'
608 );
609 }
610
611 /**@}*/
612 }