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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
33 * This is a base class for all Query modules.
34 * It provides some common functionality such as constructing various SQL
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;
47 $this->resetQueryParams();
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.
60 public function getCacheMode( $params ) {
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();
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 );
88 if ( !is_null( $alias ) ) {
89 $this->tables
[$alias] = $tables;
91 $this->tables
[] = $tables;
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 );
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 ) {
132 $this->addFields( $value );
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 );
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 ) {
169 $this->addWhere( $value );
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 ) );
215 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
216 if ( !isset( $this->options
['ORDER BY'] ) ) {
217 $this->addOption( 'ORDER BY', $order );
219 $this->addOption( 'ORDER BY', $this->options
['ORDER BY'] . ', ' . $order );
224 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
225 * but converts $start and $end to database timestamps.
228 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
229 $db = $this->getDb();
230 return $this->addWhereRange( $field, $dir,
231 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
235 * Add an option such as LIMIT or USE INDEX. If an option was set
236 * before, the old value will be overwritten
237 * @param $name string Option name
238 * @param $value string Option value
240 protected function addOption( $name, $value = null ) {
241 if ( is_null( $value ) ) {
242 $this->options
[] = $name;
244 $this->options
[$name] = $value;
249 * Execute a SELECT query based on the values in the internal arrays
250 * @param $method string Function the query should be attributed to.
251 * You should usually use __METHOD__ here
252 * @param $extraQuery array Query data to add but not store in the object
253 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
254 * @return ResultWrapper
256 protected function select( $method, $extraQuery = array() ) {
258 $tables = array_merge( $this->tables
, isset( $extraQuery['tables'] ) ?
(array)$extraQuery['tables'] : array() );
259 $fields = array_merge( $this->fields
, isset( $extraQuery['fields'] ) ?
(array)$extraQuery['fields'] : array() );
260 $where = array_merge( $this->where
, isset( $extraQuery['where'] ) ?
(array)$extraQuery['where'] : array() );
261 $options = array_merge( $this->options
, isset( $extraQuery['options'] ) ?
(array)$extraQuery['options'] : array() );
262 $join_conds = array_merge( $this->join_conds
, isset( $extraQuery['join_conds'] ) ?
(array)$extraQuery['join_conds'] : array() );
264 // getDB has its own profileDBIn/Out calls
265 $db = $this->getDB();
267 $this->profileDBIn();
268 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
269 $this->profileDBOut();
275 * Estimate the row count for the SELECT query that would be run if we
276 * called select() right now, and check if it's acceptable.
277 * @return bool true if acceptable, false otherwise
279 protected function checkRowCount() {
280 $db = $this->getDB();
281 $this->profileDBIn();
282 $rowcount = $db->estimateRowCount( $this->tables
, $this->fields
, $this->where
, __METHOD__
, $this->options
);
283 $this->profileDBOut();
285 global $wgAPIMaxDBRows;
286 if ( $rowcount > $wgAPIMaxDBRows ) {
293 * Add information (title and namespace) about a Title object to a
295 * @param $arr array Result array à la ApiResult
296 * @param $title Title
297 * @param $prefix string Module prefix
299 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
300 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
301 $arr[$prefix . 'title'] = $title->getPrefixedText();
305 * Override this method to request extra fields from the pageSet
306 * using $pageSet->requestField('fieldName')
307 * @param $pageSet ApiPageSet
309 public function requestExtraData( $pageSet ) {
313 * Get the main Query module
316 public function getQuery() {
317 return $this->mQueryModule
;
321 * Add a sub-element under the page element with the given page ID
322 * @param $pageId int Page ID
323 * @param $data array Data array à la ApiResult
324 * @return bool Whether the element fit in the result
326 protected function addPageSubItems( $pageId, $data ) {
327 $result = $this->getResult();
328 $result->setIndexedTagName( $data, $this->getModulePrefix() );
329 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
330 $this->getModuleName(),
335 * Same as addPageSubItems(), but one element of $data at a time
336 * @param $pageId int Page ID
337 * @param $item array Data array à la ApiResult
338 * @param $elemname string XML element name. If null, getModuleName()
340 * @return bool Whether the element fit in the result
342 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
343 if ( is_null( $elemname ) ) {
344 $elemname = $this->getModulePrefix();
346 $result = $this->getResult();
347 $fit = $result->addValue( array( 'query', 'pages', $pageId,
348 $this->getModuleName() ), null, $item );
352 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
353 $this->getModuleName() ), $elemname );
358 * Set a query-continue value
359 * @param $paramName string Parameter name
360 * @param $paramValue string Parameter value
362 protected function setContinueEnumParameter( $paramName, $paramValue ) {
363 $paramName = $this->encodeParamName( $paramName );
364 $msg = array( $paramName => $paramValue );
365 $result = $this->getResult();
366 $result->disableSizeCheck();
367 $result->addValue( 'query-continue', $this->getModuleName(), $msg );
368 $result->enableSizeCheck();
372 * Get the Query database connection (read-only)
373 * @return DatabaseBase
375 protected function getDB() {
376 if ( is_null( $this->mDb
) ) {
377 $apiQuery = $this->getQuery();
378 $this->mDb
= $apiQuery->getDB();
384 * Selects the query database connection with the given name.
385 * See ApiQuery::getNamedDB() for more information
386 * @param $name string Name to assign to the database connection
387 * @param $db int One of the DB_* constants
388 * @param $groups array Query groups
391 public function selectNamedDB( $name, $db, $groups ) {
392 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
396 * Get the PageSet object to work on
399 protected function getPageSet() {
400 return $this->getQuery()->getPageSet();
404 * Convert a title to a DB key
405 * @param $title string Page title with spaces
406 * @return string Page title with underscores
408 public function titleToKey( $title ) {
409 // Don't throw an error if we got an empty string
410 if ( trim( $title ) == '' ) {
413 $t = Title
::newFromText( $title );
415 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
417 return $t->getPrefixedDbKey();
421 * The inverse of titleToKey()
422 * @param $key string Page title with underscores
423 * @return string Page title with spaces
425 public function keyToTitle( $key ) {
426 // Don't throw an error if we got an empty string
427 if ( trim( $key ) == '' ) {
430 $t = Title
::newFromDbKey( $key );
431 // This really shouldn't happen but we gotta check anyway
433 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
435 return $t->getPrefixedText();
439 * An alternative to titleToKey() that doesn't trim trailing spaces
440 * @param $titlePart string Title part with spaces
441 * @return string Title part with underscores
443 public function titlePartToKey( $titlePart ) {
444 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
448 * An alternative to keyToTitle() that doesn't trim trailing spaces
449 * @param $keyPart string Key part with spaces
450 * @return string Key part with underscores
452 public function keyPartToTitle( $keyPart ) {
453 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
457 * Gets the personalised direction parameter description
459 * @param string $p ModulePrefix
460 * @param string $extraDirText Any extra text to be appended on the description
463 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
465 "In which direction to enumerate{$extraDirText}",
466 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
467 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
472 * @param $query String
473 * @param $protocol String
474 * @return null|string
476 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
477 $db = $this->getDb();
478 if ( !is_null( $query ) ||
$query != '' ) {
479 if ( is_null( $protocol ) ) {
480 $protocol = 'http://';
483 $likeQuery = LinkFilter
::makeLikeArray( $query, $protocol );
485 $this->dieUsage( 'Invalid query', 'bad_query' );
488 $likeQuery = LinkFilter
::keepOneWildcard( $likeQuery );
489 return 'el_index ' . $db->buildLike( $likeQuery );
490 } elseif ( !is_null( $protocol ) ) {
491 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
498 * Filters hidden users (where the user doesn't have the right to view them)
499 * Also adds relevant block information
501 * @param bool $showBlockInfo
504 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
505 $userCanViewHiddenUsers = $this->getUser()->isAllowed( 'hideuser' );
507 if ( $showBlockInfo ||
!$userCanViewHiddenUsers ) {
508 $this->addTables( 'ipblocks' );
509 $this->addJoinConds( array(
510 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
513 $this->addFields( 'ipb_deleted' );
515 if ( $showBlockInfo ) {
516 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
519 // Don't show hidden names
520 if ( !$userCanViewHiddenUsers ) {
521 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
527 * @param $hash string
530 public function validateSha1Hash( $hash ) {
531 return preg_match( '/[a-fA-F0-9]{40}/', $hash );
535 * @param $hash string
538 public function validateSha1Base36Hash( $hash ) {
539 return preg_match( '/[a-zA-Z0-9]{31}/', $hash );
545 public function getPossibleErrors() {
546 return array_merge( parent
::getPossibleErrors(), array(
547 array( 'invalidtitle', 'title' ),
548 array( 'invalidtitle', 'key' ),
553 * Get version string for use in the API help output
556 public static function getBaseVersion() {
557 return __CLASS__
. ': $Id$';
564 abstract class ApiQueryGeneratorBase
extends ApiQueryBase
{
566 private $mIsGenerator;
568 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
569 parent
::__construct( $query, $moduleName, $paramPrefix );
570 $this->mIsGenerator
= false;
574 * Switch this module to generator mode. By default, generator mode is
575 * switched off and the module acts like a normal query module.
577 public function setGeneratorMode() {
578 $this->mIsGenerator
= true;
582 * Overrides base class to prepend 'g' to every generator parameter
583 * @param $paramName string Parameter name
584 * @return string Prefixed parameter name
586 public function encodeParamName( $paramName ) {
587 if ( $this->mIsGenerator
) {
588 return 'g' . parent
::encodeParamName( $paramName );
590 return parent
::encodeParamName( $paramName );
595 * Execute this module as a generator
596 * @param $resultPageSet ApiPageSet: All output should be appended to
599 public abstract function executeGenerator( $resultPageSet );