Removed raw Article->field accessing
[mediawiki.git] / includes / api / ApiQueryBase.php
blob628611d4459854a7691ceca37ca77098d1ad8ee6
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 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
32 /**
33 * This is a base class for all Query modules.
34 * It provides some common functionality such as constructing various SQL
35 * queries.
37 * @ingroup API
39 abstract class ApiQueryBase extends ApiBase {
41 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
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 * @return string
60 public function getCacheMode( $params ) {
61 return 'private';
64 /**
65 * Blank the internal arrays with query parameters
67 protected function resetQueryParams() {
68 $this->tables = array();
69 $this->where = array();
70 $this->fields = array();
71 $this->options = array();
72 $this->join_conds = array();
75 /**
76 * Add a set of tables to the internal array
77 * @param $tables mixed Table name or array of table names
78 * @param $alias mixed Table alias, or null for no alias. Cannot be
79 * used with multiple tables
81 protected function addTables( $tables, $alias = null ) {
82 if ( is_array( $tables ) ) {
83 if ( !is_null( $alias ) ) {
84 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
86 $this->tables = array_merge( $this->tables, $tables );
87 } else {
88 if ( !is_null( $alias ) ) {
89 $this->tables[$alias] = $tables;
90 } else {
91 $this->tables[] = $tables;
96 /**
97 * Add a set of JOIN conditions to the internal array
99 * JOIN conditions are formatted as array( tablename => array(jointype,
100 * conditions) e.g. array('page' => array('LEFT JOIN',
101 * 'page_id=rev_page')) . conditions may be a string or an
102 * addWhere()-style array
103 * @param $join_conds array JOIN conditions
105 protected function addJoinConds( $join_conds ) {
106 if ( !is_array( $join_conds ) ) {
107 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
109 $this->join_conds = array_merge( $this->join_conds, $join_conds );
113 * Add a set of fields to select to the internal array
114 * @param $value array|string Field name or array of field names
116 protected function addFields( $value ) {
117 if ( is_array( $value ) ) {
118 $this->fields = array_merge( $this->fields, $value );
119 } else {
120 $this->fields[] = $value;
125 * Same as addFields(), but add the fields only if a condition is met
126 * @param $value array|string See addFields()
127 * @param $condition bool If false, do nothing
128 * @return bool $condition
130 protected function addFieldsIf( $value, $condition ) {
131 if ( $condition ) {
132 $this->addFields( $value );
133 return true;
135 return false;
139 * Add a set of WHERE clauses to the internal array.
140 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
141 * the latter only works if the value is a constant (i.e. not another field)
143 * If $value is an empty array, this function does nothing.
145 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
146 * to "foo=bar AND baz='3' AND bla='foo'"
147 * @param $value mixed String or array
149 protected function addWhere( $value ) {
150 if ( is_array( $value ) ) {
151 // Sanity check: don't insert empty arrays,
152 // Database::makeList() chokes on them
153 if ( count( $value ) ) {
154 $this->where = array_merge( $this->where, $value );
156 } else {
157 $this->where[] = $value;
162 * Same as addWhere(), but add the WHERE clauses only if a condition is met
163 * @param $value mixed See addWhere()
164 * @param $condition bool If false, do nothing
165 * @return bool $condition
167 protected function addWhereIf( $value, $condition ) {
168 if ( $condition ) {
169 $this->addWhere( $value );
170 return true;
172 return false;
176 * Equivalent to addWhere(array($field => $value))
177 * @param $field string Field name
178 * @param $value string Value; ignored if null or empty array;
180 protected function addWhereFld( $field, $value ) {
181 // Use count() to its full documented capabilities to simultaneously
182 // test for null, empty array or empty countable object
183 if ( count( $value ) ) {
184 $this->where[$field] = $value;
189 * Add a WHERE clause corresponding to a range, and an ORDER BY
190 * clause to sort in the right direction
191 * @param $field string Field name
192 * @param $dir string If 'newer', sort in ascending order, otherwise
193 * sort in descending order
194 * @param $start string Value to start the list at. If $dir == 'newer'
195 * this is the lower boundary, otherwise it's the upper boundary
196 * @param $end string Value to end the list at. If $dir == 'newer' this
197 * is the upper boundary, otherwise it's the lower boundary
198 * @param $sort bool If false, don't add an ORDER BY clause
200 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
201 $isDirNewer = ( $dir === 'newer' );
202 $after = ( $isDirNewer ? '>=' : '<=' );
203 $before = ( $isDirNewer ? '<=' : '>=' );
204 $db = $this->getDB();
206 if ( !is_null( $start ) ) {
207 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
210 if ( !is_null( $end ) ) {
211 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
214 if ( $sort ) {
215 $order = $field . ( $isDirNewer ? '' : ' DESC' );
216 if ( !isset( $this->options['ORDER BY'] ) ) {
217 $this->addOption( 'ORDER BY', $order );
218 } else {
219 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
225 * Add an option such as LIMIT or USE INDEX. If an option was set
226 * before, the old value will be overwritten
227 * @param $name string Option name
228 * @param $value string Option value
230 protected function addOption( $name, $value = null ) {
231 if ( is_null( $value ) ) {
232 $this->options[] = $name;
233 } else {
234 $this->options[$name] = $value;
239 * Execute a SELECT query based on the values in the internal arrays
240 * @param $method string Function the query should be attributed to.
241 * You should usually use __METHOD__ here
242 * @param $extraQuery array Query data to add but not store in the object
243 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
244 * @return ResultWrapper
246 protected function select( $method, $extraQuery = array() ) {
248 $tables = array_merge( $this->tables, isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array() );
249 $fields = array_merge( $this->fields, isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array() );
250 $where = array_merge( $this->where, isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array() );
251 $options = array_merge( $this->options, isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array() );
252 $join_conds = array_merge( $this->join_conds, isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array() );
254 // getDB has its own profileDBIn/Out calls
255 $db = $this->getDB();
257 $this->profileDBIn();
258 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
259 $this->profileDBOut();
261 return $res;
265 * Estimate the row count for the SELECT query that would be run if we
266 * called select() right now, and check if it's acceptable.
267 * @return bool true if acceptable, false otherwise
269 protected function checkRowCount() {
270 $db = $this->getDB();
271 $this->profileDBIn();
272 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
273 $this->profileDBOut();
275 global $wgAPIMaxDBRows;
276 if ( $rowcount > $wgAPIMaxDBRows ) {
277 return false;
279 return true;
283 * Add information (title and namespace) about a Title object to a
284 * result array
285 * @param $arr array Result array à la ApiResult
286 * @param $title Title
287 * @param $prefix string Module prefix
289 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
290 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
291 $arr[$prefix . 'title'] = $title->getPrefixedText();
295 * Override this method to request extra fields from the pageSet
296 * using $pageSet->requestField('fieldName')
297 * @param $pageSet ApiPageSet
299 public function requestExtraData( $pageSet ) {
303 * Get the main Query module
304 * @return ApiQuery
306 public function getQuery() {
307 return $this->mQueryModule;
311 * Add a sub-element under the page element with the given page ID
312 * @param $pageId int Page ID
313 * @param $data array Data array à la ApiResult
314 * @return bool Whether the element fit in the result
316 protected function addPageSubItems( $pageId, $data ) {
317 $result = $this->getResult();
318 $result->setIndexedTagName( $data, $this->getModulePrefix() );
319 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
320 $this->getModuleName(),
321 $data );
325 * Same as addPageSubItems(), but one element of $data at a time
326 * @param $pageId int Page ID
327 * @param $item array Data array à la ApiResult
328 * @param $elemname string XML element name. If null, getModuleName()
329 * is used
330 * @return bool Whether the element fit in the result
332 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
333 if ( is_null( $elemname ) ) {
334 $elemname = $this->getModulePrefix();
336 $result = $this->getResult();
337 $fit = $result->addValue( array( 'query', 'pages', $pageId,
338 $this->getModuleName() ), null, $item );
339 if ( !$fit ) {
340 return false;
342 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
343 $this->getModuleName() ), $elemname );
344 return true;
348 * Set a query-continue value
349 * @param $paramName string Parameter name
350 * @param $paramValue string Parameter value
352 protected function setContinueEnumParameter( $paramName, $paramValue ) {
353 $paramName = $this->encodeParamName( $paramName );
354 $msg = array( $paramName => $paramValue );
355 $this->getResult()->disableSizeCheck();
356 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
357 $this->getResult()->enableSizeCheck();
361 * Get the Query database connection (read-only)
362 * @return DatabaseBase
364 protected function getDB() {
365 if ( is_null( $this->mDb ) ) {
366 $apiQuery = $this->getQuery();
367 $this->mDb = $apiQuery->getDB();
369 return $this->mDb;
373 * Selects the query database connection with the given name.
374 * See ApiQuery::getNamedDB() for more information
375 * @param $name string Name to assign to the database connection
376 * @param $db int One of the DB_* constants
377 * @param $groups array Query groups
378 * @return Database
380 public function selectNamedDB( $name, $db, $groups ) {
381 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
385 * Get the PageSet object to work on
386 * @return ApiPageSet
388 protected function getPageSet() {
389 return $this->getQuery()->getPageSet();
393 * Convert a title to a DB key
394 * @param $title string Page title with spaces
395 * @return string Page title with underscores
397 public function titleToKey( $title ) {
398 // Don't throw an error if we got an empty string
399 if ( trim( $title ) == '' ) {
400 return '';
402 $t = Title::newFromText( $title );
403 if ( !$t ) {
404 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
406 return $t->getPrefixedDbKey();
410 * The inverse of titleToKey()
411 * @param $key string Page title with underscores
412 * @return string Page title with spaces
414 public function keyToTitle( $key ) {
415 // Don't throw an error if we got an empty string
416 if ( trim( $key ) == '' ) {
417 return '';
419 $t = Title::newFromDbKey( $key );
420 // This really shouldn't happen but we gotta check anyway
421 if ( !$t ) {
422 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
424 return $t->getPrefixedText();
428 * An alternative to titleToKey() that doesn't trim trailing spaces
429 * @param $titlePart string Title part with spaces
430 * @return string Title part with underscores
432 public function titlePartToKey( $titlePart ) {
433 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
437 * An alternative to keyToTitle() that doesn't trim trailing spaces
438 * @param $keyPart string Key part with spaces
439 * @return string Key part with underscores
441 public function keyPartToTitle( $keyPart ) {
442 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
446 * Gets the personalised direction parameter description
448 * @param string $p ModulePrefix
449 * @param string $extraDirText Any extra text to be appended on the description
450 * @return array
452 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
453 return array(
454 "In which direction to enumerate{$extraDirText}",
455 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
456 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
461 * @param $query String
462 * @param $protocol String
463 * @return null|string
465 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
466 $db = $this->getDb();
467 if ( !is_null( $query ) || $query != '' ) {
468 if ( is_null( $protocol ) ) {
469 $protocol = 'http://';
472 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
473 if ( !$likeQuery ) {
474 $this->dieUsage( 'Invalid query', 'bad_query' );
477 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
478 return 'el_index ' . $db->buildLike( $likeQuery );
479 } elseif ( !is_null( $protocol ) ) {
480 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
483 return null;
487 * Filters hidden users (where the user doesn't have the right to view them)
488 * Also adds relevant block information
490 * @param bool $showBlockInfo
491 * @return void
493 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
494 global $wgUser;
495 $userCanViewHiddenUsers = $wgUser->isAllowed( 'hideuser' );
497 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
498 $this->addTables( 'ipblocks' );
499 $this->addJoinConds( array(
500 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
501 ) );
503 $this->addFields( 'ipb_deleted' );
505 if ( $showBlockInfo ) {
506 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
509 // Don't show hidden names
510 if ( !$userCanViewHiddenUsers ) {
511 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
517 * @param $hash string
518 * @return bool
520 public function validateSha1Hash( $hash ) {
521 return preg_match( '/[a-fA-F0-9]{40}/', $hash );
525 * @param $hash string
526 * @return bool
528 public function validateSha1Base36Hash( $hash ) {
529 return preg_match( '/[a-zA-Z0-9]{31}/', $hash );
533 * @return array
535 public function getPossibleErrors() {
536 return array_merge( parent::getPossibleErrors(), array(
537 array( 'invalidtitle', 'title' ),
538 array( 'invalidtitle', 'key' ),
539 ) );
543 * Get version string for use in the API help output
544 * @return string
546 public static function getBaseVersion() {
547 return __CLASS__ . ': $Id$';
552 * @ingroup API
554 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
556 private $mIsGenerator;
558 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
559 parent::__construct( $query, $moduleName, $paramPrefix );
560 $this->mIsGenerator = false;
564 * Switch this module to generator mode. By default, generator mode is
565 * switched off and the module acts like a normal query module.
567 public function setGeneratorMode() {
568 $this->mIsGenerator = true;
572 * Overrides base class to prepend 'g' to every generator parameter
573 * @param $paramName string Parameter name
574 * @return string Prefixed parameter name
576 public function encodeParamName( $paramName ) {
577 if ( $this->mIsGenerator ) {
578 return 'g' . parent::encodeParamName( $paramName );
579 } else {
580 return parent::encodeParamName( $paramName );
585 * Execute this module as a generator
586 * @param $resultPageSet ApiPageSet: All output should be appended to
587 * this object
589 public abstract function executeGenerator( $resultPageSet );