Merge "Warn if stateful ParserOutput transforms are used"
[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\ResultWrapper;
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|string[] $tables Table name or array of table names
155 * @param string|null $alias Table alias, or null for no alias. Cannot be
156 * used with multiple tables
157 */
158 protected function addTables( $tables, $alias = null ) {
159 if ( is_array( $tables ) ) {
160 if ( !is_null( $alias ) ) {
161 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
162 }
163 $this->tables = array_merge( $this->tables, $tables );
164 } else {
165 if ( !is_null( $alias ) ) {
166 $this->tables[$alias] = $tables;
167 } else {
168 $this->tables[] = $tables;
169 }
170 }
171 }
172
173 /**
174 * Add a set of JOIN conditions to the internal array
175 *
176 * JOIN conditions are formatted as [ tablename => [ jointype, conditions ] ]
177 * e.g. [ 'page' => [ 'LEFT JOIN', 'page_id=rev_page' ] ].
178 * Conditions may be a string or an addWhere()-style array.
179 * @param array $join_conds JOIN conditions
180 */
181 protected function addJoinConds( $join_conds ) {
182 if ( !is_array( $join_conds ) ) {
183 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
184 }
185 $this->join_conds = array_merge( $this->join_conds, $join_conds );
186 }
187
188 /**
189 * Add a set of fields to select to the internal array
190 * @param array|string $value Field name or array of field names
191 */
192 protected function addFields( $value ) {
193 if ( is_array( $value ) ) {
194 $this->fields = array_merge( $this->fields, $value );
195 } else {
196 $this->fields[] = $value;
197 }
198 }
199
200 /**
201 * Same as addFields(), but add the fields only if a condition is met
202 * @param array|string $value See addFields()
203 * @param bool $condition If false, do nothing
204 * @return bool $condition
205 */
206 protected function addFieldsIf( $value, $condition ) {
207 if ( $condition ) {
208 $this->addFields( $value );
209
210 return true;
211 }
212
213 return false;
214 }
215
216 /**
217 * Add a set of WHERE clauses to the internal array.
218 * Clauses can be formatted as 'foo=bar' or [ 'foo' => 'bar' ],
219 * the latter only works if the value is a constant (i.e. not another field)
220 *
221 * If $value is an empty array, this function does nothing.
222 *
223 * For example, [ 'foo=bar', 'baz' => 3, 'bla' => 'foo' ] translates
224 * to "foo=bar AND baz='3' AND bla='foo'"
225 * @param string|array $value
226 */
227 protected function addWhere( $value ) {
228 if ( is_array( $value ) ) {
229 // Sanity check: don't insert empty arrays,
230 // Database::makeList() chokes on them
231 if ( count( $value ) ) {
232 $this->where = array_merge( $this->where, $value );
233 }
234 } else {
235 $this->where[] = $value;
236 }
237 }
238
239 /**
240 * Same as addWhere(), but add the WHERE clauses only if a condition is met
241 * @param string|array $value
242 * @param bool $condition If false, do nothing
243 * @return bool $condition
244 */
245 protected function addWhereIf( $value, $condition ) {
246 if ( $condition ) {
247 $this->addWhere( $value );
248
249 return true;
250 }
251
252 return false;
253 }
254
255 /**
256 * Equivalent to addWhere(array($field => $value))
257 * @param string $field Field name
258 * @param string|string[] $value Value; ignored if null or empty array;
259 */
260 protected function addWhereFld( $field, $value ) {
261 if ( $value !== null && !( is_array( $value ) && !$value ) ) {
262 $this->where[$field] = $value;
263 }
264 }
265
266 /**
267 * Add a WHERE clause corresponding to a range, and an ORDER BY
268 * clause to sort in the right direction
269 * @param string $field Field name
270 * @param string $dir If 'newer', sort in ascending order, otherwise
271 * sort in descending order
272 * @param string $start Value to start the list at. If $dir == 'newer'
273 * this is the lower boundary, otherwise it's the upper boundary
274 * @param string $end Value to end the list at. If $dir == 'newer' this
275 * is the upper boundary, otherwise it's the lower boundary
276 * @param bool $sort If false, don't add an ORDER BY clause
277 */
278 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
279 $isDirNewer = ( $dir === 'newer' );
280 $after = ( $isDirNewer ? '>=' : '<=' );
281 $before = ( $isDirNewer ? '<=' : '>=' );
282 $db = $this->getDB();
283
284 if ( !is_null( $start ) ) {
285 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
286 }
287
288 if ( !is_null( $end ) ) {
289 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
290 }
291
292 if ( $sort ) {
293 $order = $field . ( $isDirNewer ? '' : ' DESC' );
294 // Append ORDER BY
295 $optionOrderBy = isset( $this->options['ORDER BY'] )
296 ? (array)$this->options['ORDER BY']
297 : [];
298 $optionOrderBy[] = $order;
299 $this->addOption( 'ORDER BY', $optionOrderBy );
300 }
301 }
302
303 /**
304 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
305 * but converts $start and $end to database timestamps.
306 * @see addWhereRange
307 * @param string $field
308 * @param string $dir
309 * @param string $start
310 * @param string $end
311 * @param bool $sort
312 */
313 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
314 $db = $this->getDB();
315 $this->addWhereRange( $field, $dir,
316 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
317 }
318
319 /**
320 * Add an option such as LIMIT or USE INDEX. If an option was set
321 * before, the old value will be overwritten
322 * @param string $name Option name
323 * @param string|string[] $value Option value
324 */
325 protected function addOption( $name, $value = null ) {
326 if ( is_null( $value ) ) {
327 $this->options[] = $name;
328 } else {
329 $this->options[$name] = $value;
330 }
331 }
332
333 /**
334 * Execute a SELECT query based on the values in the internal arrays
335 * @param string $method Function the query should be attributed to.
336 * You should usually use __METHOD__ here
337 * @param array $extraQuery Query data to add but not store in the object
338 * Format is [
339 * 'tables' => ...,
340 * 'fields' => ...,
341 * 'where' => ...,
342 * 'options' => ...,
343 * 'join_conds' => ...
344 * ]
345 * @param array|null &$hookData If set, the ApiQueryBaseBeforeQuery and
346 * ApiQueryBaseAfterQuery hooks will be called, and the
347 * ApiQueryBaseProcessRow hook will be expected.
348 * @return ResultWrapper
349 */
350 protected function select( $method, $extraQuery = [], array &$hookData = null ) {
351 $tables = array_merge(
352 $this->tables,
353 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : []
354 );
355 $fields = array_merge(
356 $this->fields,
357 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : []
358 );
359 $where = array_merge(
360 $this->where,
361 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : []
362 );
363 $options = array_merge(
364 $this->options,
365 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : []
366 );
367 $join_conds = array_merge(
368 $this->join_conds,
369 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : []
370 );
371
372 if ( $hookData !== null ) {
373 Hooks::run( 'ApiQueryBaseBeforeQuery',
374 [ $this, &$tables, &$fields, &$where, &$options, &$join_conds, &$hookData ]
375 );
376 }
377
378 $res = $this->getDB()->select( $tables, $fields, $where, $method, $options, $join_conds );
379
380 if ( $hookData !== null ) {
381 Hooks::run( 'ApiQueryBaseAfterQuery', [ $this, $res, &$hookData ] );
382 }
383
384 return $res;
385 }
386
387 /**
388 * Call the ApiQueryBaseProcessRow hook
389 *
390 * Generally, a module that passed $hookData to self::select() will call
391 * this just before calling ApiResult::addValue(), and treat a false return
392 * here in the same way it treats a false return from addValue().
393 *
394 * @since 1.28
395 * @param object $row Database row
396 * @param array &$data Data to be added to the result
397 * @param array &$hookData Hook data from ApiQueryBase::select()
398 * @return bool Return false if row processing should end with continuation
399 */
400 protected function processRow( $row, array &$data, array &$hookData ) {
401 return Hooks::run( 'ApiQueryBaseProcessRow', [ $this, $row, &$data, &$hookData ] );
402 }
403
404 /**
405 * @param string $query
406 * @param string $protocol
407 * @return null|string
408 */
409 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
410 $db = $this->getDB();
411 if ( !is_null( $query ) || $query != '' ) {
412 if ( is_null( $protocol ) ) {
413 $protocol = 'http://';
414 }
415
416 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
417 if ( !$likeQuery ) {
418 $this->dieWithError( 'apierror-badquery' );
419 }
420
421 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
422
423 return 'el_index ' . $db->buildLike( $likeQuery );
424 } elseif ( !is_null( $protocol ) ) {
425 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
426 }
427
428 return null;
429 }
430
431 /**
432 * Filters hidden users (where the user doesn't have the right to view them)
433 * Also adds relevant block information
434 *
435 * @param bool $showBlockInfo
436 * @return void
437 */
438 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
439 $this->addTables( 'ipblocks' );
440 $this->addJoinConds( [
441 'ipblocks' => [ 'LEFT JOIN', 'ipb_user=user_id' ],
442 ] );
443
444 $this->addFields( 'ipb_deleted' );
445
446 if ( $showBlockInfo ) {
447 $this->addFields( [
448 'ipb_id',
449 'ipb_by',
450 'ipb_by_text',
451 'ipb_expiry',
452 'ipb_timestamp'
453 ] );
454 $commentQuery = CommentStore::newKey( 'ipb_reason' )->getJoin();
455 $this->addTables( $commentQuery['tables'] );
456 $this->addFields( $commentQuery['fields'] );
457 $this->addJoinConds( $commentQuery['joins'] );
458 }
459
460 // Don't show hidden names
461 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
462 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
463 }
464 }
465
466 /**@}*/
467
468 /************************************************************************//**
469 * @name Utility methods
470 * @{
471 */
472
473 /**
474 * Add information (title and namespace) about a Title object to a
475 * result array
476 * @param array &$arr Result array à la ApiResult
477 * @param Title $title
478 * @param string $prefix Module prefix
479 */
480 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
481 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
482 $arr[$prefix . 'title'] = $title->getPrefixedText();
483 }
484
485 /**
486 * Add a sub-element under the page element with the given page ID
487 * @param int $pageId Page ID
488 * @param array $data Data array à la ApiResult
489 * @return bool Whether the element fit in the result
490 */
491 protected function addPageSubItems( $pageId, $data ) {
492 $result = $this->getResult();
493 ApiResult::setIndexedTagName( $data, $this->getModulePrefix() );
494
495 return $result->addValue( [ 'query', 'pages', intval( $pageId ) ],
496 $this->getModuleName(),
497 $data );
498 }
499
500 /**
501 * Same as addPageSubItems(), but one element of $data at a time
502 * @param int $pageId Page ID
503 * @param array $item Data array à la ApiResult
504 * @param string $elemname XML element name. If null, getModuleName()
505 * is used
506 * @return bool Whether the element fit in the result
507 */
508 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
509 if ( is_null( $elemname ) ) {
510 $elemname = $this->getModulePrefix();
511 }
512 $result = $this->getResult();
513 $fit = $result->addValue( [ 'query', 'pages', $pageId,
514 $this->getModuleName() ], null, $item );
515 if ( !$fit ) {
516 return false;
517 }
518 $result->addIndexedTagName( [ 'query', 'pages', $pageId,
519 $this->getModuleName() ], $elemname );
520
521 return true;
522 }
523
524 /**
525 * Set a query-continue value
526 * @param string $paramName Parameter name
527 * @param string|array $paramValue Parameter value
528 */
529 protected function setContinueEnumParameter( $paramName, $paramValue ) {
530 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
531 }
532
533 /**
534 * Convert an input title or title prefix into a dbkey.
535 *
536 * $namespace should always be specified in order to handle per-namespace
537 * capitalization settings.
538 *
539 * @param string $titlePart Title part
540 * @param int $namespace Namespace of the title
541 * @return string DBkey (no namespace prefix)
542 */
543 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
544 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
545 if ( !$t || $t->hasFragment() ) {
546 // Invalid title (e.g. bad chars) or contained a '#'.
547 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
548 }
549 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
550 // This can happen in two cases. First, if you call titlePartToKey with a title part
551 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
552 // difficult to handle such a case. Such cases cannot exist and are therefore treated
553 // as invalid user input. The second case is when somebody specifies a title interwiki
554 // prefix.
555 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
556 }
557
558 return substr( $t->getDBkey(), 0, -1 );
559 }
560
561 /**
562 * Convert an input title or title prefix into a namespace constant and dbkey.
563 *
564 * @since 1.26
565 * @param string $titlePart Title part
566 * @param int $defaultNamespace Default namespace if none is given
567 * @return array (int, string) Namespace number and DBkey
568 */
569 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
570 $t = Title::newFromText( $titlePart . 'x', $defaultNamespace );
571 if ( !$t || $t->hasFragment() || $t->isExternal() ) {
572 // Invalid title (e.g. bad chars) or contained a '#'.
573 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $titlePart ) ] );
574 }
575
576 return [ $t->getNamespace(), substr( $t->getDBkey(), 0, -1 ) ];
577 }
578
579 /**
580 * @param string $hash
581 * @return bool
582 */
583 public function validateSha1Hash( $hash ) {
584 return (bool)preg_match( '/^[a-f0-9]{40}$/', $hash );
585 }
586
587 /**
588 * @param string $hash
589 * @return bool
590 */
591 public function validateSha1Base36Hash( $hash ) {
592 return (bool)preg_match( '/^[a-z0-9]{31}$/', $hash );
593 }
594
595 /**
596 * Check whether the current user has permission to view revision-deleted
597 * fields.
598 * @return bool
599 */
600 public function userCanSeeRevDel() {
601 return $this->getUser()->isAllowedAny(
602 'deletedhistory',
603 'deletedtext',
604 'suppressrevision',
605 'viewsuppressed'
606 );
607 }
608
609 /**@}*/
610 }