Followup r86622: add initial QUnit test cases for jquery.textSelection module.
[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 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
30 }
31
32 /**
33 * This is a base class for all Query modules.
34 * It provides some common functionality such as constructing various SQL
35 * queries.
36 *
37 * @ingroup API
38 */
39 abstract class ApiQueryBase extends ApiBase {
40
41 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
42
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();
48 }
49
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()
54 *
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.
57 *
58 * @return string
59 */
60 public function getCacheMode( $params ) {
61 return 'private';
62 }
63
64 /**
65 * Blank the internal arrays with query parameters
66 */
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();
73 }
74
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
80 */
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' );
85 }
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;
92 }
93 }
94 }
95
96 /**
97 * Add a set of JOIN conditions to the internal array
98 *
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
104 */
105 protected function addJoinConds( $join_conds ) {
106 if ( !is_array( $join_conds ) ) {
107 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
108 }
109 $this->join_conds = array_merge( $this->join_conds, $join_conds );
110 }
111
112 /**
113 * Add a set of fields to select to the internal array
114 * @param $value array|string Field name or array of field names
115 */
116 protected function addFields( $value ) {
117 if ( is_array( $value ) ) {
118 $this->fields = array_merge( $this->fields, $value );
119 } else {
120 $this->fields[] = $value;
121 }
122 }
123
124 /**
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
129 */
130 protected function addFieldsIf( $value, $condition ) {
131 if ( $condition ) {
132 $this->addFields( $value );
133 return true;
134 }
135 return false;
136 }
137
138 /**
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)
142 *
143 * If $value is an empty array, this function does nothing.
144 *
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
148 */
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 );
155 }
156 } else {
157 $this->where[] = $value;
158 }
159 }
160
161 /**
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
166 */
167 protected function addWhereIf( $value, $condition ) {
168 if ( $condition ) {
169 $this->addWhere( $value );
170 return true;
171 }
172 return false;
173 }
174
175 /**
176 * Equivalent to addWhere(array($field => $value))
177 * @param $field string Field name
178 * @param $value string Value; ignored if null or empty array;
179 */
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;
185 }
186 }
187
188 /**
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
199 */
200 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
201 $isDirNewer = ( $dir === 'newer' );
202 $after = ( $isDirNewer ? '>=' : '<=' );
203 $before = ( $isDirNewer ? '<=' : '>=' );
204 $db = $this->getDB();
205
206 if ( !is_null( $start ) ) {
207 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
208 }
209
210 if ( !is_null( $end ) ) {
211 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
212 }
213
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 );
220 }
221 }
222 }
223
224 /**
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
229 */
230 protected function addOption( $name, $value = null ) {
231 if ( is_null( $value ) ) {
232 $this->options[] = $name;
233 } else {
234 $this->options[$name] = $value;
235 }
236 }
237
238 /**
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
245 */
246 protected function select( $method, $extraQuery = array() ) {
247
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() );
253
254 // getDB has its own profileDBIn/Out calls
255 $db = $this->getDB();
256
257 $this->profileDBIn();
258 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
259 $this->profileDBOut();
260
261 return $res;
262 }
263
264 /**
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
268 */
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();
274
275 global $wgAPIMaxDBRows;
276 if ( $rowcount > $wgAPIMaxDBRows ) {
277 return false;
278 }
279 return true;
280 }
281
282 /**
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
288 */
289 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
290 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
291 $arr[$prefix . 'title'] = $title->getPrefixedText();
292 }
293
294 /**
295 * Override this method to request extra fields from the pageSet
296 * using $pageSet->requestField('fieldName')
297 * @param $pageSet ApiPageSet
298 */
299 public function requestExtraData( $pageSet ) {
300 }
301
302 /**
303 * Get the main Query module
304 * @return ApiQuery
305 */
306 public function getQuery() {
307 return $this->mQueryModule;
308 }
309
310 /**
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
315 */
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 );
322 }
323
324 /**
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
331 */
332 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
333 if ( is_null( $elemname ) ) {
334 $elemname = $this->getModulePrefix();
335 }
336 $result = $this->getResult();
337 $fit = $result->addValue( array( 'query', 'pages', $pageId,
338 $this->getModuleName() ), null, $item );
339 if ( !$fit ) {
340 return false;
341 }
342 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
343 $this->getModuleName() ), $elemname );
344 return true;
345 }
346
347 /**
348 * Set a query-continue value
349 * @param $paramName string Parameter name
350 * @param $paramValue string Parameter value
351 */
352 protected function setContinueEnumParameter( $paramName, $paramValue ) {
353 $paramName = $this->encodeParamName( $paramName );
354 $msg = array( $paramName => $paramValue );
355 $result = $this->getResult();
356 $result->disableSizeCheck();
357 $result->addValue( 'query-continue', $this->getModuleName(), $msg );
358 $result->enableSizeCheck();
359 }
360
361 /**
362 * Get the Query database connection (read-only)
363 * @return DatabaseBase
364 */
365 protected function getDB() {
366 if ( is_null( $this->mDb ) ) {
367 $apiQuery = $this->getQuery();
368 $this->mDb = $apiQuery->getDB();
369 }
370 return $this->mDb;
371 }
372
373 /**
374 * Selects the query database connection with the given name.
375 * See ApiQuery::getNamedDB() for more information
376 * @param $name string Name to assign to the database connection
377 * @param $db int One of the DB_* constants
378 * @param $groups array Query groups
379 * @return Database
380 */
381 public function selectNamedDB( $name, $db, $groups ) {
382 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
383 }
384
385 /**
386 * Get the PageSet object to work on
387 * @return ApiPageSet
388 */
389 protected function getPageSet() {
390 return $this->getQuery()->getPageSet();
391 }
392
393 /**
394 * Convert a title to a DB key
395 * @param $title string Page title with spaces
396 * @return string Page title with underscores
397 */
398 public function titleToKey( $title ) {
399 // Don't throw an error if we got an empty string
400 if ( trim( $title ) == '' ) {
401 return '';
402 }
403 $t = Title::newFromText( $title );
404 if ( !$t ) {
405 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
406 }
407 return $t->getPrefixedDbKey();
408 }
409
410 /**
411 * The inverse of titleToKey()
412 * @param $key string Page title with underscores
413 * @return string Page title with spaces
414 */
415 public function keyToTitle( $key ) {
416 // Don't throw an error if we got an empty string
417 if ( trim( $key ) == '' ) {
418 return '';
419 }
420 $t = Title::newFromDbKey( $key );
421 // This really shouldn't happen but we gotta check anyway
422 if ( !$t ) {
423 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
424 }
425 return $t->getPrefixedText();
426 }
427
428 /**
429 * An alternative to titleToKey() that doesn't trim trailing spaces
430 * @param $titlePart string Title part with spaces
431 * @return string Title part with underscores
432 */
433 public function titlePartToKey( $titlePart ) {
434 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
435 }
436
437 /**
438 * An alternative to keyToTitle() that doesn't trim trailing spaces
439 * @param $keyPart string Key part with spaces
440 * @return string Key part with underscores
441 */
442 public function keyPartToTitle( $keyPart ) {
443 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
444 }
445
446 /**
447 * Gets the personalised direction parameter description
448 *
449 * @param string $p ModulePrefix
450 * @param string $extraDirText Any extra text to be appended on the description
451 * @return array
452 */
453 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
454 return array(
455 "In which direction to enumerate{$extraDirText}",
456 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
457 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
458 );
459 }
460
461 /**
462 * @param $query String
463 * @param $protocol String
464 * @return null|string
465 */
466 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
467 $db = $this->getDb();
468 if ( !is_null( $query ) || $query != '' ) {
469 if ( is_null( $protocol ) ) {
470 $protocol = 'http://';
471 }
472
473 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
474 if ( !$likeQuery ) {
475 $this->dieUsage( 'Invalid query', 'bad_query' );
476 }
477
478 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
479 return 'el_index ' . $db->buildLike( $likeQuery );
480 } elseif ( !is_null( $protocol ) ) {
481 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
482 }
483
484 return null;
485 }
486
487 /**
488 * Filters hidden users (where the user doesn't have the right to view them)
489 * Also adds relevant block information
490 *
491 * @param bool $showBlockInfo
492 * @return void
493 */
494 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
495 global $wgUser;
496 $userCanViewHiddenUsers = $wgUser->isAllowed( 'hideuser' );
497
498 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
499 $this->addTables( 'ipblocks' );
500 $this->addJoinConds( array(
501 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
502 ) );
503
504 $this->addFields( 'ipb_deleted' );
505
506 if ( $showBlockInfo ) {
507 $this->addFields( array( 'ipb_reason', 'ipb_by_text', 'ipb_expiry' ) );
508 }
509
510 // Don't show hidden names
511 if ( !$userCanViewHiddenUsers ) {
512 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
513 }
514 }
515 }
516
517 /**
518 * @param $hash string
519 * @return bool
520 */
521 public function validateSha1Hash( $hash ) {
522 return preg_match( '/[a-fA-F0-9]{40}/', $hash );
523 }
524
525 /**
526 * @param $hash string
527 * @return bool
528 */
529 public function validateSha1Base36Hash( $hash ) {
530 return preg_match( '/[a-zA-Z0-9]{31}/', $hash );
531 }
532
533 /**
534 * @return array
535 */
536 public function getPossibleErrors() {
537 return array_merge( parent::getPossibleErrors(), array(
538 array( 'invalidtitle', 'title' ),
539 array( 'invalidtitle', 'key' ),
540 ) );
541 }
542
543 /**
544 * Get version string for use in the API help output
545 * @return string
546 */
547 public static function getBaseVersion() {
548 return __CLASS__ . ': $Id$';
549 }
550 }
551
552 /**
553 * @ingroup API
554 */
555 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
556
557 private $mIsGenerator;
558
559 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
560 parent::__construct( $query, $moduleName, $paramPrefix );
561 $this->mIsGenerator = false;
562 }
563
564 /**
565 * Switch this module to generator mode. By default, generator mode is
566 * switched off and the module acts like a normal query module.
567 */
568 public function setGeneratorMode() {
569 $this->mIsGenerator = true;
570 }
571
572 /**
573 * Overrides base class to prepend 'g' to every generator parameter
574 * @param $paramName string Parameter name
575 * @return string Prefixed parameter name
576 */
577 public function encodeParamName( $paramName ) {
578 if ( $this->mIsGenerator ) {
579 return 'g' . parent::encodeParamName( $paramName );
580 } else {
581 return parent::encodeParamName( $paramName );
582 }
583 }
584
585 /**
586 * Execute this module as a generator
587 * @param $resultPageSet ApiPageSet: All output should be appended to
588 * this object
589 */
590 public abstract function executeGenerator( $resultPageSet );
591 }