Merge "Remove unused 'XMPGetInfo' and 'XMPGetResults' hooks"
[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 ApiQuery $queryModule
40 * @param string $moduleName
41 * @param string $paramPrefix
42 */
43 public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
44 parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule = $queryModule;
46 $this->mDb = null;
47 $this->resetQueryParams();
48 }
49
50 /************************************************************************//**
51 * @name Methods to implement
52 * @{
53 */
54
55 /**
56 * Get the cache mode for the data generated by this module. Override
57 * this in the module subclass. For possible return values and other
58 * details about cache modes, see ApiMain::setCacheMode()
59 *
60 * Public caching will only be allowed if *all* the modules that supply
61 * data for a given request return a cache mode of public.
62 *
63 * @param array $params
64 * @return string
65 */
66 public function getCacheMode( $params ) {
67 return 'private';
68 }
69
70 /**
71 * Override this method to request extra fields from the pageSet
72 * using $pageSet->requestField('fieldName')
73 *
74 * Note this only makes sense for 'prop' modules, as 'list' and 'meta'
75 * modules should not be using the pageset.
76 *
77 * @param ApiPageSet $pageSet
78 */
79 public function requestExtraData( $pageSet ) {
80 }
81
82 /**@}*/
83
84 /************************************************************************//**
85 * @name Data access
86 * @{
87 */
88
89 /**
90 * Get the main Query module
91 * @return ApiQuery
92 */
93 public function getQuery() {
94 return $this->mQueryModule;
95 }
96
97 /**
98 * @see ApiBase::getParent()
99 */
100 public function getParent() {
101 return $this->getQuery();
102 }
103
104 /**
105 * Get the Query database connection (read-only)
106 * @return DatabaseBase
107 */
108 protected function getDB() {
109 if ( is_null( $this->mDb ) ) {
110 $this->mDb = $this->getQuery()->getDB();
111 }
112
113 return $this->mDb;
114 }
115
116 /**
117 * Selects the query database connection with the given name.
118 * See ApiQuery::getNamedDB() for more information
119 * @param string $name Name to assign to the database connection
120 * @param int $db One of the DB_* constants
121 * @param array $groups Query groups
122 * @return DatabaseBase
123 */
124 public function selectNamedDB( $name, $db, $groups ) {
125 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
126 return $this->mDb;
127 }
128
129 /**
130 * Get the PageSet object to work on
131 * @return ApiPageSet
132 */
133 protected function getPageSet() {
134 return $this->getQuery()->getPageSet();
135 }
136
137 /**@}*/
138
139 /************************************************************************//**
140 * @name Querying
141 * @{
142 */
143
144 /**
145 * Blank the internal arrays with query parameters
146 */
147 protected function resetQueryParams() {
148 $this->tables = array();
149 $this->where = array();
150 $this->fields = array();
151 $this->options = array();
152 $this->join_conds = array();
153 }
154
155 /**
156 * Add a set of tables to the internal array
157 * @param string|string[] $tables Table name or array of table names
158 * @param string|null $alias Table alias, or null for no alias. Cannot be
159 * used with multiple tables
160 */
161 protected function addTables( $tables, $alias = null ) {
162 if ( is_array( $tables ) ) {
163 if ( !is_null( $alias ) ) {
164 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
165 }
166 $this->tables = array_merge( $this->tables, $tables );
167 } else {
168 if ( !is_null( $alias ) ) {
169 $this->tables[$alias] = $tables;
170 } else {
171 $this->tables[] = $tables;
172 }
173 }
174 }
175
176 /**
177 * Add a set of JOIN conditions to the internal array
178 *
179 * JOIN conditions are formatted as array( tablename => array(jointype,
180 * conditions) e.g. array('page' => array('LEFT JOIN',
181 * 'page_id=rev_page')) . conditions may be a string or an
182 * addWhere()-style array
183 * @param array $join_conds JOIN conditions
184 */
185 protected function addJoinConds( $join_conds ) {
186 if ( !is_array( $join_conds ) ) {
187 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
188 }
189 $this->join_conds = array_merge( $this->join_conds, $join_conds );
190 }
191
192 /**
193 * Add a set of fields to select to the internal array
194 * @param array|string $value Field name or array of field names
195 */
196 protected function addFields( $value ) {
197 if ( is_array( $value ) ) {
198 $this->fields = array_merge( $this->fields, $value );
199 } else {
200 $this->fields[] = $value;
201 }
202 }
203
204 /**
205 * Same as addFields(), but add the fields only if a condition is met
206 * @param array|string $value See addFields()
207 * @param bool $condition If false, do nothing
208 * @return bool $condition
209 */
210 protected function addFieldsIf( $value, $condition ) {
211 if ( $condition ) {
212 $this->addFields( $value );
213
214 return true;
215 }
216
217 return false;
218 }
219
220 /**
221 * Add a set of WHERE clauses to the internal array.
222 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
223 * the latter only works if the value is a constant (i.e. not another field)
224 *
225 * If $value is an empty array, this function does nothing.
226 *
227 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
228 * to "foo=bar AND baz='3' AND bla='foo'"
229 * @param string|array $value
230 */
231 protected function addWhere( $value ) {
232 if ( is_array( $value ) ) {
233 // Sanity check: don't insert empty arrays,
234 // Database::makeList() chokes on them
235 if ( count( $value ) ) {
236 $this->where = array_merge( $this->where, $value );
237 }
238 } else {
239 $this->where[] = $value;
240 }
241 }
242
243 /**
244 * Same as addWhere(), but add the WHERE clauses only if a condition is met
245 * @param string|array $value
246 * @param bool $condition If false, do nothing
247 * @return bool $condition
248 */
249 protected function addWhereIf( $value, $condition ) {
250 if ( $condition ) {
251 $this->addWhere( $value );
252
253 return true;
254 }
255
256 return false;
257 }
258
259 /**
260 * Equivalent to addWhere(array($field => $value))
261 * @param string $field Field name
262 * @param string $value Value; ignored if null or empty array;
263 */
264 protected function addWhereFld( $field, $value ) {
265 // Use count() to its full documented capabilities to simultaneously
266 // test for null, empty array or empty countable object
267 if ( count( $value ) ) {
268 $this->where[$field] = $value;
269 }
270 }
271
272 /**
273 * Add a WHERE clause corresponding to a range, and an ORDER BY
274 * clause to sort in the right direction
275 * @param string $field Field name
276 * @param string $dir If 'newer', sort in ascending order, otherwise
277 * sort in descending order
278 * @param string $start Value to start the list at. If $dir == 'newer'
279 * this is the lower boundary, otherwise it's the upper boundary
280 * @param string $end Value to end the list at. If $dir == 'newer' this
281 * is the upper boundary, otherwise it's the lower boundary
282 * @param bool $sort If false, don't add an ORDER BY clause
283 */
284 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
285 $isDirNewer = ( $dir === 'newer' );
286 $after = ( $isDirNewer ? '>=' : '<=' );
287 $before = ( $isDirNewer ? '<=' : '>=' );
288 $db = $this->getDB();
289
290 if ( !is_null( $start ) ) {
291 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
292 }
293
294 if ( !is_null( $end ) ) {
295 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
296 }
297
298 if ( $sort ) {
299 $order = $field . ( $isDirNewer ? '' : ' DESC' );
300 // Append ORDER BY
301 $optionOrderBy = isset( $this->options['ORDER BY'] )
302 ? (array)$this->options['ORDER BY']
303 : array();
304 $optionOrderBy[] = $order;
305 $this->addOption( 'ORDER BY', $optionOrderBy );
306 }
307 }
308
309 /**
310 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
311 * but converts $start and $end to database timestamps.
312 * @see addWhereRange
313 * @param string $field
314 * @param string $dir
315 * @param string $start
316 * @param string $end
317 * @param bool $sort
318 */
319 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
320 $db = $this->getDb();
321 $this->addWhereRange( $field, $dir,
322 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
323 }
324
325 /**
326 * Add an option such as LIMIT or USE INDEX. If an option was set
327 * before, the old value will be overwritten
328 * @param string $name Option name
329 * @param string $value Option value
330 */
331 protected function addOption( $name, $value = null ) {
332 if ( is_null( $value ) ) {
333 $this->options[] = $name;
334 } else {
335 $this->options[$name] = $value;
336 }
337 }
338
339 /**
340 * Execute a SELECT query based on the values in the internal arrays
341 * @param string $method Function the query should be attributed to.
342 * You should usually use __METHOD__ here
343 * @param array $extraQuery Query data to add but not store in the object
344 * Format is array(
345 * 'tables' => ...,
346 * 'fields' => ...,
347 * 'where' => ...,
348 * 'options' => ...,
349 * 'join_conds' => ...
350 * )
351 * @return ResultWrapper
352 */
353 protected function select( $method, $extraQuery = array() ) {
354
355 $tables = array_merge(
356 $this->tables,
357 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array()
358 );
359 $fields = array_merge(
360 $this->fields,
361 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array()
362 );
363 $where = array_merge(
364 $this->where,
365 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array()
366 );
367 $options = array_merge(
368 $this->options,
369 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array()
370 );
371 $join_conds = array_merge(
372 $this->join_conds,
373 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array()
374 );
375
376 $res = $this->getDB()->select( $tables, $fields, $where, $method, $options, $join_conds );
377
378 return $res;
379 }
380
381 /**
382 * @param string $query
383 * @param string $protocol
384 * @return null|string
385 */
386 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
387 $db = $this->getDb();
388 if ( !is_null( $query ) || $query != '' ) {
389 if ( is_null( $protocol ) ) {
390 $protocol = 'http://';
391 }
392
393 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
394 if ( !$likeQuery ) {
395 $this->dieUsage( 'Invalid query', 'bad_query' );
396 }
397
398 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
399
400 return 'el_index ' . $db->buildLike( $likeQuery );
401 } elseif ( !is_null( $protocol ) ) {
402 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
403 }
404
405 return null;
406 }
407
408 /**
409 * Filters hidden users (where the user doesn't have the right to view them)
410 * Also adds relevant block information
411 *
412 * @param bool $showBlockInfo
413 * @return void
414 */
415 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
416 $this->addTables( 'ipblocks' );
417 $this->addJoinConds( array(
418 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
419 ) );
420
421 $this->addFields( 'ipb_deleted' );
422
423 if ( $showBlockInfo ) {
424 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry', 'ipb_timestamp' ) );
425 }
426
427 // Don't show hidden names
428 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
429 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
430 }
431 }
432
433 /**@}*/
434
435 /************************************************************************//**
436 * @name Utility methods
437 * @{
438 */
439
440 /**
441 * Add information (title and namespace) about a Title object to a
442 * result array
443 * @param array $arr Result array à la ApiResult
444 * @param Title $title
445 * @param string $prefix Module prefix
446 */
447 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
448 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
449 $arr[$prefix . 'title'] = $title->getPrefixedText();
450 }
451
452 /**
453 * Add a sub-element under the page element with the given page ID
454 * @param int $pageId Page ID
455 * @param array $data Data array à la ApiResult
456 * @return bool Whether the element fit in the result
457 */
458 protected function addPageSubItems( $pageId, $data ) {
459 $result = $this->getResult();
460 ApiResult::setIndexedTagName( $data, $this->getModulePrefix() );
461
462 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
463 $this->getModuleName(),
464 $data );
465 }
466
467 /**
468 * Same as addPageSubItems(), but one element of $data at a time
469 * @param int $pageId Page ID
470 * @param array $item Data array à la ApiResult
471 * @param string $elemname XML element name. If null, getModuleName()
472 * is used
473 * @return bool Whether the element fit in the result
474 */
475 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
476 if ( is_null( $elemname ) ) {
477 $elemname = $this->getModulePrefix();
478 }
479 $result = $this->getResult();
480 $fit = $result->addValue( array( 'query', 'pages', $pageId,
481 $this->getModuleName() ), null, $item );
482 if ( !$fit ) {
483 return false;
484 }
485 $result->addIndexedTagName( array( 'query', 'pages', $pageId,
486 $this->getModuleName() ), $elemname );
487
488 return true;
489 }
490
491 /**
492 * Set a query-continue value
493 * @param string $paramName Parameter name
494 * @param string|array $paramValue Parameter value
495 */
496 protected function setContinueEnumParameter( $paramName, $paramValue ) {
497 $this->getContinuationManager()->addContinueParam( $this, $paramName, $paramValue );
498 }
499
500 /**
501 * Convert an input title or title prefix into a dbkey.
502 *
503 * $namespace should always be specified in order to handle per-namespace
504 * capitalization settings.
505 *
506 * @param string $titlePart Title part
507 * @param int $namespace Namespace of the title
508 * @return string DBkey (no namespace prefix)
509 */
510 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
511 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
512 if ( !$t || $t->hasFragment() ) {
513 // Invalid title (e.g. bad chars) or contained a '#'.
514 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
515 }
516 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
517 // This can happen in two cases. First, if you call titlePartToKey with a title part
518 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
519 // difficult to handle such a case. Such cases cannot exist and are therefore treated
520 // as invalid user input. The second case is when somebody specifies a title interwiki
521 // prefix.
522 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
523 }
524
525 return substr( $t->getDbKey(), 0, -1 );
526 }
527
528 /**
529 * Convert an input title or title prefix into a namespace constant and dbkey.
530 *
531 * @since 1.26
532 * @param string $titlePart Title part
533 * @param int $defaultNamespace Default namespace if none is given
534 * @return array (int, string) Namespace number and DBkey
535 */
536 public function prefixedTitlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
537 $t = Title::newFromText( $titlePart . 'x', $defaultNamespace );
538 if ( !$t || $t->hasFragment() || $t->isExternal() ) {
539 // Invalid title (e.g. bad chars) or contained a '#'.
540 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
541 }
542
543 return array( $t->getNamespace(), substr( $t->getDbKey(), 0, -1 ) );
544 }
545
546 /**
547 * Gets the personalised direction parameter description
548 *
549 * @param string $p ModulePrefix
550 * @param string $extraDirText Any extra text to be appended on the description
551 * @return array
552 */
553 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
554 return array(
555 "In which direction to enumerate{$extraDirText}",
556 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
557 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
558 );
559 }
560
561 /**
562 * @param string $hash
563 * @return bool
564 */
565 public function validateSha1Hash( $hash ) {
566 return preg_match( '/^[a-f0-9]{40}$/', $hash );
567 }
568
569 /**
570 * @param string $hash
571 * @return bool
572 */
573 public function validateSha1Base36Hash( $hash ) {
574 return preg_match( '/^[a-z0-9]{31}$/', $hash );
575 }
576
577 /**
578 * Check whether the current user has permission to view revision-deleted
579 * fields.
580 * @return bool
581 */
582 public function userCanSeeRevDel() {
583 return $this->getUser()->isAllowedAny(
584 'deletedhistory',
585 'deletedtext',
586 'suppressrevision',
587 'viewsuppressed'
588 );
589 }
590
591 /**@}*/
592
593 /************************************************************************//**
594 * @name Deprecated
595 * @{
596 */
597
598 /**
599 * Estimate the row count for the SELECT query that would be run if we
600 * called select() right now, and check if it's acceptable.
601 * @deprecated since 1.24
602 * @return bool True if acceptable, false otherwise
603 */
604 protected function checkRowCount() {
605 wfDeprecated( __METHOD__, '1.24' );
606 $db = $this->getDB();
607 $rowcount = $db->estimateRowCount(
608 $this->tables,
609 $this->fields,
610 $this->where,
611 __METHOD__,
612 $this->options
613 );
614
615 if ( $rowcount > $this->getConfig()->get( 'APIMaxDBRows' ) ) {
616 return false;
617 }
618
619 return true;
620 }
621
622 /**
623 * Convert a title to a DB key
624 * @deprecated since 1.24, past uses of this were always incorrect and should
625 * have used self::titlePartToKey() instead
626 * @param string $title Page title with spaces
627 * @return string Page title with underscores
628 */
629 public function titleToKey( $title ) {
630 wfDeprecated( __METHOD__, '1.24' );
631 // Don't throw an error if we got an empty string
632 if ( trim( $title ) == '' ) {
633 return '';
634 }
635 $t = Title::newFromText( $title );
636 if ( !$t ) {
637 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
638 }
639
640 return $t->getPrefixedDBkey();
641 }
642
643 /**
644 * The inverse of titleToKey()
645 * @deprecated since 1.24, unused and probably never needed
646 * @param string $key Page title with underscores
647 * @return string Page title with spaces
648 */
649 public function keyToTitle( $key ) {
650 wfDeprecated( __METHOD__, '1.24' );
651 // Don't throw an error if we got an empty string
652 if ( trim( $key ) == '' ) {
653 return '';
654 }
655 $t = Title::newFromDBkey( $key );
656 // This really shouldn't happen but we gotta check anyway
657 if ( !$t ) {
658 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
659 }
660
661 return $t->getPrefixedText();
662 }
663
664 /**
665 * Inverse of titlePartToKey()
666 * @deprecated since 1.24, unused and probably never needed
667 * @param string $keyPart DBkey, with prefix
668 * @return string Key part with underscores
669 */
670 public function keyPartToTitle( $keyPart ) {
671 wfDeprecated( __METHOD__, '1.24' );
672 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 );
673 }
674
675 /**@}*/
676 }
677
678 /**
679 * @ingroup API
680 */
681 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
682
683 private $mGeneratorPageSet = null;
684
685 /**
686 * Switch this module to generator mode. By default, generator mode is
687 * switched off and the module acts like a normal query module.
688 * @since 1.21 requires pageset parameter
689 * @param ApiPageSet $generatorPageSet ApiPageSet object that the module will get
690 * by calling getPageSet() when in generator mode.
691 */
692 public function setGeneratorMode( ApiPageSet $generatorPageSet ) {
693 if ( $generatorPageSet === null ) {
694 ApiBase::dieDebug( __METHOD__, 'Required parameter missing - $generatorPageSet' );
695 }
696 $this->mGeneratorPageSet = $generatorPageSet;
697 }
698
699 /**
700 * Get the PageSet object to work on.
701 * If this module is generator, the pageSet object is different from other module's
702 * @return ApiPageSet
703 */
704 protected function getPageSet() {
705 if ( $this->mGeneratorPageSet !== null ) {
706 return $this->mGeneratorPageSet;
707 }
708
709 return parent::getPageSet();
710 }
711
712 /**
713 * Overrides ApiBase to prepend 'g' to every generator parameter
714 * @param string $paramName Parameter name
715 * @return string Prefixed parameter name
716 */
717 public function encodeParamName( $paramName ) {
718 if ( $this->mGeneratorPageSet !== null ) {
719 return 'g' . parent::encodeParamName( $paramName );
720 } else {
721 return parent::encodeParamName( $paramName );
722 }
723 }
724
725 /**
726 * Overridden to set the generator param if in generator mode
727 * @param string $paramName Parameter name
728 * @param string|array $paramValue Parameter value
729 */
730 protected function setContinueEnumParameter( $paramName, $paramValue ) {
731 if ( $this->mGeneratorPageSet !== null ) {
732 $this->getContinuationManager()->addGeneratorContinueParam( $this, $paramName, $paramValue );
733 } else {
734 parent::setContinueEnumParameter( $paramName, $paramValue );
735 }
736 }
737
738 /**
739 * @see ApiBase::getHelpFlags()
740 *
741 * Corresponding messages: api-help-flag-generator
742 */
743 protected function getHelpFlags() {
744 $flags = parent::getHelpFlags();
745 $flags[] = 'generator';
746 return $flags;
747 }
748
749 /**
750 * Execute this module as a generator
751 * @param ApiPageSet $resultPageSet All output should be appended to this object
752 */
753 abstract public function executeGenerator( $resultPageSet );
754 }