Merge "Add additional information to FileRepo::getInfo"
[mediawiki.git] / includes / api / ApiQueryBase.php
blobcfc224470327f40e8a565a26ac98349b1799fc83
1 <?php
2 /**
5 * Created on Sep 7, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
24 * @file
27 /**
28 * This is a base class for all Query modules.
29 * It provides some common functionality such as constructing various SQL
30 * queries.
32 * @ingroup API
34 abstract class ApiQueryBase extends ApiBase {
36 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
38 /**
39 * @param $query ApiBase
40 * @param $moduleName string
41 * @param $paramPrefix string
43 public function __construct( ApiBase $query, $moduleName, $paramPrefix = '' ) {
44 parent::__construct( $query->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule = $query;
46 $this->mDb = null;
47 $this->resetQueryParams();
50 /**
51 * Get the cache mode for the data generated by this module. Override
52 * this in the module subclass. For possible return values and other
53 * details about cache modes, see ApiMain::setCacheMode()
55 * Public caching will only be allowed if *all* the modules that supply
56 * data for a given request return a cache mode of public.
58 * @param $params
59 * @return string
61 public function getCacheMode( $params ) {
62 return 'private';
65 /**
66 * Blank the internal arrays with query parameters
68 protected function resetQueryParams() {
69 $this->tables = array();
70 $this->where = array();
71 $this->fields = array();
72 $this->options = array();
73 $this->join_conds = array();
76 /**
77 * Add a set of tables to the internal array
78 * @param $tables mixed Table name or array of table names
79 * @param $alias mixed Table alias, or null for no alias. Cannot be
80 * used with multiple tables
82 protected function addTables( $tables, $alias = null ) {
83 if ( is_array( $tables ) ) {
84 if ( !is_null( $alias ) ) {
85 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
87 $this->tables = array_merge( $this->tables, $tables );
88 } else {
89 if ( !is_null( $alias ) ) {
90 $this->tables[$alias] = $tables;
91 } else {
92 $this->tables[] = $tables;
97 /**
98 * Add a set of JOIN conditions to the internal array
100 * JOIN conditions are formatted as array( tablename => array(jointype,
101 * conditions) e.g. array('page' => array('LEFT JOIN',
102 * 'page_id=rev_page')) . conditions may be a string or an
103 * addWhere()-style array
104 * @param $join_conds array JOIN conditions
106 protected function addJoinConds( $join_conds ) {
107 if ( !is_array( $join_conds ) ) {
108 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
110 $this->join_conds = array_merge( $this->join_conds, $join_conds );
114 * Add a set of fields to select to the internal array
115 * @param array|string $value Field name or array of field names
117 protected function addFields( $value ) {
118 if ( is_array( $value ) ) {
119 $this->fields = array_merge( $this->fields, $value );
120 } else {
121 $this->fields[] = $value;
126 * Same as addFields(), but add the fields only if a condition is met
127 * @param array|string $value See addFields()
128 * @param bool $condition If false, do nothing
129 * @return bool $condition
131 protected function addFieldsIf( $value, $condition ) {
132 if ( $condition ) {
133 $this->addFields( $value );
135 return true;
138 return false;
142 * Add a set of WHERE clauses to the internal array.
143 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
144 * the latter only works if the value is a constant (i.e. not another field)
146 * If $value is an empty array, this function does nothing.
148 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
149 * to "foo=bar AND baz='3' AND bla='foo'"
150 * @param $value mixed String or array
152 protected function addWhere( $value ) {
153 if ( is_array( $value ) ) {
154 // Sanity check: don't insert empty arrays,
155 // Database::makeList() chokes on them
156 if ( count( $value ) ) {
157 $this->where = array_merge( $this->where, $value );
159 } else {
160 $this->where[] = $value;
165 * Same as addWhere(), but add the WHERE clauses only if a condition is met
166 * @param $value mixed See addWhere()
167 * @param bool $condition If false, do nothing
168 * @return bool $condition
170 protected function addWhereIf( $value, $condition ) {
171 if ( $condition ) {
172 $this->addWhere( $value );
174 return true;
177 return false;
181 * Equivalent to addWhere(array($field => $value))
182 * @param string $field Field name
183 * @param string $value Value; ignored if null or empty array;
185 protected function addWhereFld( $field, $value ) {
186 // Use count() to its full documented capabilities to simultaneously
187 // test for null, empty array or empty countable object
188 if ( count( $value ) ) {
189 $this->where[$field] = $value;
194 * Add a WHERE clause corresponding to a range, and an ORDER BY
195 * clause to sort in the right direction
196 * @param string $field Field name
197 * @param string $dir If 'newer', sort in ascending order, otherwise
198 * sort in descending order
199 * @param string $start Value to start the list at. If $dir == 'newer'
200 * this is the lower boundary, otherwise it's the upper boundary
201 * @param string $end Value to end the list at. If $dir == 'newer' this
202 * is the upper boundary, otherwise it's the lower boundary
203 * @param bool $sort If false, don't add an ORDER BY clause
205 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
206 $isDirNewer = ( $dir === 'newer' );
207 $after = ( $isDirNewer ? '>=' : '<=' );
208 $before = ( $isDirNewer ? '<=' : '>=' );
209 $db = $this->getDB();
211 if ( !is_null( $start ) ) {
212 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
215 if ( !is_null( $end ) ) {
216 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
219 if ( $sort ) {
220 $order = $field . ( $isDirNewer ? '' : ' DESC' );
221 // Append ORDER BY
222 $optionOrderBy = isset( $this->options['ORDER BY'] )
223 ? (array)$this->options['ORDER BY']
224 : array();
225 $optionOrderBy[] = $order;
226 $this->addOption( 'ORDER BY', $optionOrderBy );
231 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
232 * but converts $start and $end to database timestamps.
233 * @see addWhereRange
234 * @param $field
235 * @param $dir
236 * @param $start
237 * @param $end
238 * @param $sort bool
240 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
241 $db = $this->getDb();
242 $this->addWhereRange( $field, $dir,
243 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
247 * Add an option such as LIMIT or USE INDEX. If an option was set
248 * before, the old value will be overwritten
249 * @param string $name Option name
250 * @param string $value Option value
252 protected function addOption( $name, $value = null ) {
253 if ( is_null( $value ) ) {
254 $this->options[] = $name;
255 } else {
256 $this->options[$name] = $value;
261 * Execute a SELECT query based on the values in the internal arrays
262 * @param string $method Function the query should be attributed to.
263 * You should usually use __METHOD__ here
264 * @param array $extraQuery Query data to add but not store in the object
265 * Format is array(
266 * 'tables' => ...,
267 * 'fields' => ...,
268 * 'where' => ...,
269 * 'options' => ...,
270 * 'join_conds' => ...
272 * @return ResultWrapper
274 protected function select( $method, $extraQuery = array() ) {
276 $tables = array_merge(
277 $this->tables,
278 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array()
280 $fields = array_merge(
281 $this->fields,
282 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array()
284 $where = array_merge(
285 $this->where,
286 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array()
288 $options = array_merge(
289 $this->options,
290 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array()
292 $join_conds = array_merge(
293 $this->join_conds,
294 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array()
297 // getDB has its own profileDBIn/Out calls
298 $db = $this->getDB();
300 $this->profileDBIn();
301 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
302 $this->profileDBOut();
304 return $res;
308 * Estimate the row count for the SELECT query that would be run if we
309 * called select() right now, and check if it's acceptable.
310 * @return bool true if acceptable, false otherwise
312 protected function checkRowCount() {
313 $db = $this->getDB();
314 $this->profileDBIn();
315 $rowcount = $db->estimateRowCount(
316 $this->tables,
317 $this->fields,
318 $this->where,
319 __METHOD__,
320 $this->options
322 $this->profileDBOut();
324 global $wgAPIMaxDBRows;
325 if ( $rowcount > $wgAPIMaxDBRows ) {
326 return false;
329 return true;
333 * Add information (title and namespace) about a Title object to a
334 * result array
335 * @param array $arr Result array à la ApiResult
336 * @param $title Title
337 * @param string $prefix Module prefix
339 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
340 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
341 $arr[$prefix . 'title'] = $title->getPrefixedText();
345 * Override this method to request extra fields from the pageSet
346 * using $pageSet->requestField('fieldName')
347 * @param $pageSet ApiPageSet
349 public function requestExtraData( $pageSet ) {
353 * Get the main Query module
354 * @return ApiQuery
356 public function getQuery() {
357 return $this->mQueryModule;
361 * Add a sub-element under the page element with the given page ID
362 * @param int $pageId Page ID
363 * @param array $data Data array à la ApiResult
364 * @return bool Whether the element fit in the result
366 protected function addPageSubItems( $pageId, $data ) {
367 $result = $this->getResult();
368 $result->setIndexedTagName( $data, $this->getModulePrefix() );
370 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
371 $this->getModuleName(),
372 $data );
376 * Same as addPageSubItems(), but one element of $data at a time
377 * @param int $pageId Page ID
378 * @param array $item Data array à la ApiResult
379 * @param string $elemname XML element name. If null, getModuleName()
380 * is used
381 * @return bool Whether the element fit in the result
383 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
384 if ( is_null( $elemname ) ) {
385 $elemname = $this->getModulePrefix();
387 $result = $this->getResult();
388 $fit = $result->addValue( array( 'query', 'pages', $pageId,
389 $this->getModuleName() ), null, $item );
390 if ( !$fit ) {
391 return false;
393 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
394 $this->getModuleName() ), $elemname );
396 return true;
400 * Set a query-continue value
401 * @param string $paramName Parameter name
402 * @param string $paramValue Parameter value
404 protected function setContinueEnumParameter( $paramName, $paramValue ) {
405 $paramName = $this->encodeParamName( $paramName );
406 $msg = array( $paramName => $paramValue );
407 $result = $this->getResult();
408 $result->disableSizeCheck();
409 $result->addValue( 'query-continue', $this->getModuleName(), $msg, ApiResult::ADD_ON_TOP );
410 $result->enableSizeCheck();
414 * Get the Query database connection (read-only)
415 * @return DatabaseBase
417 protected function getDB() {
418 if ( is_null( $this->mDb ) ) {
419 $this->mDb = $this->getQuery()->getDB();
422 return $this->mDb;
426 * Selects the query database connection with the given name.
427 * See ApiQuery::getNamedDB() for more information
428 * @param string $name Name to assign to the database connection
429 * @param int $db One of the DB_* constants
430 * @param array $groups Query groups
431 * @return DatabaseBase
433 public function selectNamedDB( $name, $db, $groups ) {
434 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
438 * Get the PageSet object to work on
439 * @return ApiPageSet
441 protected function getPageSet() {
442 return $this->getQuery()->getPageSet();
446 * Convert a title to a DB key
447 * @param string $title Page title with spaces
448 * @return string Page title with underscores
450 public function titleToKey( $title ) {
451 // Don't throw an error if we got an empty string
452 if ( trim( $title ) == '' ) {
453 return '';
455 $t = Title::newFromText( $title );
456 if ( !$t ) {
457 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
460 return $t->getPrefixedDBkey();
464 * The inverse of titleToKey()
465 * @param string $key Page title with underscores
466 * @return string Page title with spaces
468 public function keyToTitle( $key ) {
469 // Don't throw an error if we got an empty string
470 if ( trim( $key ) == '' ) {
471 return '';
473 $t = Title::newFromDBkey( $key );
474 // This really shouldn't happen but we gotta check anyway
475 if ( !$t ) {
476 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
479 return $t->getPrefixedText();
483 * An alternative to titleToKey() that doesn't trim trailing spaces
484 * @param string $titlePart Title part with spaces
485 * @return string Title part with underscores
487 public function titlePartToKey( $titlePart ) {
488 return substr( $this->titleToKey( $titlePart . 'x' ), 0, -1 );
492 * An alternative to keyToTitle() that doesn't trim trailing spaces
493 * @param string $keyPart Key part with spaces
494 * @return string Key part with underscores
496 public function keyPartToTitle( $keyPart ) {
497 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 );
501 * Gets the personalised direction parameter description
503 * @param string $p ModulePrefix
504 * @param string $extraDirText Any extra text to be appended on the description
505 * @return array
507 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
508 return array(
509 "In which direction to enumerate{$extraDirText}",
510 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
511 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
516 * @param $query String
517 * @param $protocol String
518 * @return null|string
520 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
521 $db = $this->getDb();
522 if ( !is_null( $query ) || $query != '' ) {
523 if ( is_null( $protocol ) ) {
524 $protocol = 'http://';
527 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
528 if ( !$likeQuery ) {
529 $this->dieUsage( 'Invalid query', 'bad_query' );
532 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
534 return 'el_index ' . $db->buildLike( $likeQuery );
535 } elseif ( !is_null( $protocol ) ) {
536 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
539 return null;
543 * Filters hidden users (where the user doesn't have the right to view them)
544 * Also adds relevant block information
546 * @param bool $showBlockInfo
547 * @return void
549 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
550 $userCanViewHiddenUsers = $this->getUser()->isAllowed( 'hideuser' );
552 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
553 $this->addTables( 'ipblocks' );
554 $this->addJoinConds( array(
555 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
556 ) );
558 $this->addFields( 'ipb_deleted' );
560 if ( $showBlockInfo ) {
561 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry' ) );
564 // Don't show hidden names
565 if ( !$userCanViewHiddenUsers ) {
566 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
572 * @param $hash string
573 * @return bool
575 public function validateSha1Hash( $hash ) {
576 return preg_match( '/^[a-f0-9]{40}$/', $hash );
580 * @param $hash string
581 * @return bool
583 public function validateSha1Base36Hash( $hash ) {
584 return preg_match( '/^[a-z0-9]{31}$/', $hash );
588 * @return array
590 public function getPossibleErrors() {
591 $errors = parent::getPossibleErrors();
592 $errors = array_merge( $errors, array(
593 array( 'invalidtitle', 'title' ),
594 array( 'invalidtitle', 'key' ),
595 ) );
597 return $errors;
602 * @ingroup API
604 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
606 private $mGeneratorPageSet = null;
609 * Switch this module to generator mode. By default, generator mode is
610 * switched off and the module acts like a normal query module.
611 * @since 1.21 requires pageset parameter
612 * @param $generatorPageSet ApiPageSet object that the module will get
613 * by calling getPageSet() when in generator mode.
615 public function setGeneratorMode( ApiPageSet $generatorPageSet ) {
616 if ( $generatorPageSet === null ) {
617 ApiBase::dieDebug( __METHOD__, 'Required parameter missing - $generatorPageSet' );
619 $this->mGeneratorPageSet = $generatorPageSet;
623 * Get the PageSet object to work on.
624 * If this module is generator, the pageSet object is different from other module's
625 * @return ApiPageSet
627 protected function getPageSet() {
628 if ( $this->mGeneratorPageSet !== null ) {
629 return $this->mGeneratorPageSet;
632 return parent::getPageSet();
636 * Overrides base class to prepend 'g' to every generator parameter
637 * @param string $paramName Parameter name
638 * @return string Prefixed parameter name
640 public function encodeParamName( $paramName ) {
641 if ( $this->mGeneratorPageSet !== null ) {
642 return 'g' . parent::encodeParamName( $paramName );
643 } else {
644 return parent::encodeParamName( $paramName );
649 * Overrides base in case of generator & smart continue to
650 * notify ApiQueryMain instead of adding them to the result right away.
651 * @param string $paramName Parameter name
652 * @param string $paramValue Parameter value
654 protected function setContinueEnumParameter( $paramName, $paramValue ) {
655 // If this is a generator and query->setGeneratorContinue() returns false, treat as before
656 if ( $this->mGeneratorPageSet === null
657 || !$this->getQuery()->setGeneratorContinue( $this, $paramName, $paramValue )
659 parent::setContinueEnumParameter( $paramName, $paramValue );
664 * Execute this module as a generator
665 * @param $resultPageSet ApiPageSet: All output should be appended to
666 * this object
668 abstract public function executeGenerator( $resultPageSet );