Merge "Fixed stream wrapper in PhpHttpRequest"
[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 /**
28 * This is a base class for all Query modules.
29 * It provides some common functionality such as constructing various SQL
30 * queries.
31 *
32 * @ingroup API
33 */
34 abstract class ApiQueryBase extends ApiBase {
35
36 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
37
38 /**
39 * @param $query ApiBase
40 * @param $moduleName string
41 * @param $paramPrefix string
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 * @param $params
59 * @return string
60 */
61 public function getCacheMode( $params ) {
62 return 'private';
63 }
64
65 /**
66 * Blank the internal arrays with query parameters
67 */
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();
74 }
75
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
81 */
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' );
86 }
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;
93 }
94 }
95 }
96
97 /**
98 * Add a set of JOIN conditions to the internal array
99 *
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
105 */
106 protected function addJoinConds( $join_conds ) {
107 if ( !is_array( $join_conds ) ) {
108 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
109 }
110 $this->join_conds = array_merge( $this->join_conds, $join_conds );
111 }
112
113 /**
114 * Add a set of fields to select to the internal array
115 * @param array|string $value Field name or array of field names
116 */
117 protected function addFields( $value ) {
118 if ( is_array( $value ) ) {
119 $this->fields = array_merge( $this->fields, $value );
120 } else {
121 $this->fields[] = $value;
122 }
123 }
124
125 /**
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
130 */
131 protected function addFieldsIf( $value, $condition ) {
132 if ( $condition ) {
133 $this->addFields( $value );
134
135 return true;
136 }
137
138 return false;
139 }
140
141 /**
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)
145 *
146 * If $value is an empty array, this function does nothing.
147 *
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
151 */
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 );
158 }
159 } else {
160 $this->where[] = $value;
161 }
162 }
163
164 /**
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
169 */
170 protected function addWhereIf( $value, $condition ) {
171 if ( $condition ) {
172 $this->addWhere( $value );
173
174 return true;
175 }
176
177 return false;
178 }
179
180 /**
181 * Equivalent to addWhere(array($field => $value))
182 * @param string $field Field name
183 * @param string $value Value; ignored if null or empty array;
184 */
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;
190 }
191 }
192
193 /**
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
204 */
205 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
206 $isDirNewer = ( $dir === 'newer' );
207 $after = ( $isDirNewer ? '>=' : '<=' );
208 $before = ( $isDirNewer ? '<=' : '>=' );
209 $db = $this->getDB();
210
211 if ( !is_null( $start ) ) {
212 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
213 }
214
215 if ( !is_null( $end ) ) {
216 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
217 }
218
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 );
227 }
228 }
229
230 /**
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
239 */
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 );
244 }
245
246 /**
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
251 */
252 protected function addOption( $name, $value = null ) {
253 if ( is_null( $value ) ) {
254 $this->options[] = $name;
255 } else {
256 $this->options[$name] = $value;
257 }
258 }
259
260 /**
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' => ...
271 * )
272 * @return ResultWrapper
273 */
274 protected function select( $method, $extraQuery = array() ) {
275
276 $tables = array_merge(
277 $this->tables,
278 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array()
279 );
280 $fields = array_merge(
281 $this->fields,
282 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array()
283 );
284 $where = array_merge(
285 $this->where,
286 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array()
287 );
288 $options = array_merge(
289 $this->options,
290 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array()
291 );
292 $join_conds = array_merge(
293 $this->join_conds,
294 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array()
295 );
296
297 // getDB has its own profileDBIn/Out calls
298 $db = $this->getDB();
299
300 $this->profileDBIn();
301 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
302 $this->profileDBOut();
303
304 return $res;
305 }
306
307 /**
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
311 */
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
321 );
322 $this->profileDBOut();
323
324 global $wgAPIMaxDBRows;
325 if ( $rowcount > $wgAPIMaxDBRows ) {
326 return false;
327 }
328
329 return true;
330 }
331
332 /**
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
338 */
339 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
340 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
341 $arr[$prefix . 'title'] = $title->getPrefixedText();
342 }
343
344 /**
345 * Override this method to request extra fields from the pageSet
346 * using $pageSet->requestField('fieldName')
347 * @param $pageSet ApiPageSet
348 */
349 public function requestExtraData( $pageSet ) {
350 }
351
352 /**
353 * Get the main Query module
354 * @return ApiQuery
355 */
356 public function getQuery() {
357 return $this->mQueryModule;
358 }
359
360 /**
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
365 */
366 protected function addPageSubItems( $pageId, $data ) {
367 $result = $this->getResult();
368 $result->setIndexedTagName( $data, $this->getModulePrefix() );
369
370 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
371 $this->getModuleName(),
372 $data );
373 }
374
375 /**
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
382 */
383 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
384 if ( is_null( $elemname ) ) {
385 $elemname = $this->getModulePrefix();
386 }
387 $result = $this->getResult();
388 $fit = $result->addValue( array( 'query', 'pages', $pageId,
389 $this->getModuleName() ), null, $item );
390 if ( !$fit ) {
391 return false;
392 }
393 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
394 $this->getModuleName() ), $elemname );
395
396 return true;
397 }
398
399 /**
400 * Set a query-continue value
401 * @param string $paramName Parameter name
402 * @param string $paramValue Parameter value
403 */
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();
411 }
412
413 /**
414 * Get the Query database connection (read-only)
415 * @return DatabaseBase
416 */
417 protected function getDB() {
418 if ( is_null( $this->mDb ) ) {
419 $this->mDb = $this->getQuery()->getDB();
420 }
421
422 return $this->mDb;
423 }
424
425 /**
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
432 */
433 public function selectNamedDB( $name, $db, $groups ) {
434 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
435 }
436
437 /**
438 * Get the PageSet object to work on
439 * @return ApiPageSet
440 */
441 protected function getPageSet() {
442 return $this->getQuery()->getPageSet();
443 }
444
445 /**
446 * Convert a title to a DB key
447 * @param string $title Page title with spaces
448 * @return string Page title with underscores
449 */
450 public function titleToKey( $title ) {
451 // Don't throw an error if we got an empty string
452 if ( trim( $title ) == '' ) {
453 return '';
454 }
455 $t = Title::newFromText( $title );
456 if ( !$t ) {
457 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
458 }
459
460 return $t->getPrefixedDBkey();
461 }
462
463 /**
464 * The inverse of titleToKey()
465 * @param string $key Page title with underscores
466 * @return string Page title with spaces
467 */
468 public function keyToTitle( $key ) {
469 // Don't throw an error if we got an empty string
470 if ( trim( $key ) == '' ) {
471 return '';
472 }
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 ) );
477 }
478
479 return $t->getPrefixedText();
480 }
481
482 /**
483 * An alternative to titleToKey() that doesn't trim trailing spaces, and
484 * does not mangle the input if starts with something that looks like a
485 * namespace. It is advisable to pass the namespace parameter in order to
486 * handle per-namespace capitalization settings.
487 * @param string $titlePart Title part with spaces
488 * @param $defaultNamespace int Namespace to assume
489 * @return string Title part with underscores
490 */
491 public function titlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
492 $t = Title::makeTitleSafe( $defaultNamespace, $titlePart . 'x' );
493 if ( !$t ) {
494 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
495 }
496 if ( $defaultNamespace != $t->getNamespace() || $t->isExternal() ) {
497 // This can happen in two cases. First, if you call titlePartToKey with a title part
498 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
499 // difficult to handle such a case. Such cases cannot exist and are therefore treated
500 // as invalid user input. The second case is when somebody specifies a title interwiki
501 // prefix.
502 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
503 }
504 return substr( $t->getDbKey(), 0, -1 );
505 }
506
507 /**
508 * An alternative to keyToTitle() that doesn't trim trailing spaces
509 * @param string $keyPart Key part with spaces
510 * @return string Key part with underscores
511 */
512 public function keyPartToTitle( $keyPart ) {
513 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 );
514 }
515
516 /**
517 * Gets the personalised direction parameter description
518 *
519 * @param string $p ModulePrefix
520 * @param string $extraDirText Any extra text to be appended on the description
521 * @return array
522 */
523 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
524 return array(
525 "In which direction to enumerate{$extraDirText}",
526 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
527 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
528 );
529 }
530
531 /**
532 * @param $query String
533 * @param $protocol String
534 * @return null|string
535 */
536 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
537 $db = $this->getDb();
538 if ( !is_null( $query ) || $query != '' ) {
539 if ( is_null( $protocol ) ) {
540 $protocol = 'http://';
541 }
542
543 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
544 if ( !$likeQuery ) {
545 $this->dieUsage( 'Invalid query', 'bad_query' );
546 }
547
548 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
549
550 return 'el_index ' . $db->buildLike( $likeQuery );
551 } elseif ( !is_null( $protocol ) ) {
552 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
553 }
554
555 return null;
556 }
557
558 /**
559 * Filters hidden users (where the user doesn't have the right to view them)
560 * Also adds relevant block information
561 *
562 * @param bool $showBlockInfo
563 * @return void
564 */
565 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
566 $this->addTables( 'ipblocks' );
567 $this->addJoinConds( array(
568 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
569 ) );
570
571 $this->addFields( 'ipb_deleted' );
572
573 if ( $showBlockInfo ) {
574 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry' ) );
575 }
576
577 // Don't show hidden names
578 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
579 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
580 }
581 }
582
583 /**
584 * @param $hash string
585 * @return bool
586 */
587 public function validateSha1Hash( $hash ) {
588 return preg_match( '/^[a-f0-9]{40}$/', $hash );
589 }
590
591 /**
592 * @param $hash string
593 * @return bool
594 */
595 public function validateSha1Base36Hash( $hash ) {
596 return preg_match( '/^[a-z0-9]{31}$/', $hash );
597 }
598
599 /**
600 * @return array
601 */
602 public function getPossibleErrors() {
603 $errors = parent::getPossibleErrors();
604 $errors = array_merge( $errors, array(
605 array( 'invalidtitle', 'title' ),
606 array( 'invalidtitle', 'key' ),
607 ) );
608
609 return $errors;
610 }
611
612 /**
613 * Check whether the current user has permission to view revision-deleted
614 * fields.
615 * @return bool
616 */
617 public function userCanSeeRevDel() {
618 return $this->getUser()->isAllowedAny( 'deletedhistory', 'deletedtext', 'suppressrevision' );
619 }
620 }
621
622 /**
623 * @ingroup API
624 */
625 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
626
627 private $mGeneratorPageSet = null;
628
629 /**
630 * Switch this module to generator mode. By default, generator mode is
631 * switched off and the module acts like a normal query module.
632 * @since 1.21 requires pageset parameter
633 * @param $generatorPageSet ApiPageSet object that the module will get
634 * by calling getPageSet() when in generator mode.
635 */
636 public function setGeneratorMode( ApiPageSet $generatorPageSet ) {
637 if ( $generatorPageSet === null ) {
638 ApiBase::dieDebug( __METHOD__, 'Required parameter missing - $generatorPageSet' );
639 }
640 $this->mGeneratorPageSet = $generatorPageSet;
641 }
642
643 /**
644 * Get the PageSet object to work on.
645 * If this module is generator, the pageSet object is different from other module's
646 * @return ApiPageSet
647 */
648 protected function getPageSet() {
649 if ( $this->mGeneratorPageSet !== null ) {
650 return $this->mGeneratorPageSet;
651 }
652
653 return parent::getPageSet();
654 }
655
656 /**
657 * Overrides base class to prepend 'g' to every generator parameter
658 * @param string $paramName Parameter name
659 * @return string Prefixed parameter name
660 */
661 public function encodeParamName( $paramName ) {
662 if ( $this->mGeneratorPageSet !== null ) {
663 return 'g' . parent::encodeParamName( $paramName );
664 } else {
665 return parent::encodeParamName( $paramName );
666 }
667 }
668
669 /**
670 * Overrides base in case of generator & smart continue to
671 * notify ApiQueryMain instead of adding them to the result right away.
672 * @param string $paramName Parameter name
673 * @param string $paramValue Parameter value
674 */
675 protected function setContinueEnumParameter( $paramName, $paramValue ) {
676 // If this is a generator and query->setGeneratorContinue() returns false, treat as before
677 if ( $this->mGeneratorPageSet === null
678 || !$this->getQuery()->setGeneratorContinue( $this, $paramName, $paramValue )
679 ) {
680 parent::setContinueEnumParameter( $paramName, $paramValue );
681 }
682 }
683
684 /**
685 * Execute this module as a generator
686 * @param $resultPageSet ApiPageSet: All output should be appended to
687 * this object
688 */
689 abstract public function executeGenerator( $resultPageSet );
690 }