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