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