Merge "Implement static public Parser::getExternalLinkRel"
[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 $value array|string 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 $value array|string See addFields()
128 * @param $condition bool If false, do nothing
129 * @return bool $condition
130 */
131 protected function addFieldsIf( $value, $condition ) {
132 if ( $condition ) {
133 $this->addFields( $value );
134 return true;
135 }
136 return false;
137 }
138
139 /**
140 * Add a set of WHERE clauses to the internal array.
141 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
142 * the latter only works if the value is a constant (i.e. not another field)
143 *
144 * If $value is an empty array, this function does nothing.
145 *
146 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
147 * to "foo=bar AND baz='3' AND bla='foo'"
148 * @param $value mixed String or array
149 */
150 protected function addWhere( $value ) {
151 if ( is_array( $value ) ) {
152 // Sanity check: don't insert empty arrays,
153 // Database::makeList() chokes on them
154 if ( count( $value ) ) {
155 $this->where = array_merge( $this->where, $value );
156 }
157 } else {
158 $this->where[] = $value;
159 }
160 }
161
162 /**
163 * Same as addWhere(), but add the WHERE clauses only if a condition is met
164 * @param $value mixed See addWhere()
165 * @param $condition bool If false, do nothing
166 * @return bool $condition
167 */
168 protected function addWhereIf( $value, $condition ) {
169 if ( $condition ) {
170 $this->addWhere( $value );
171 return true;
172 }
173 return false;
174 }
175
176 /**
177 * Equivalent to addWhere(array($field => $value))
178 * @param $field string Field name
179 * @param $value string Value; ignored if null or empty array;
180 */
181 protected function addWhereFld( $field, $value ) {
182 // Use count() to its full documented capabilities to simultaneously
183 // test for null, empty array or empty countable object
184 if ( count( $value ) ) {
185 $this->where[$field] = $value;
186 }
187 }
188
189 /**
190 * Add a WHERE clause corresponding to a range, and an ORDER BY
191 * clause to sort in the right direction
192 * @param $field string Field name
193 * @param $dir string If 'newer', sort in ascending order, otherwise
194 * sort in descending order
195 * @param $start string Value to start the list at. If $dir == 'newer'
196 * this is the lower boundary, otherwise it's the upper boundary
197 * @param $end string Value to end the list at. If $dir == 'newer' this
198 * is the upper boundary, otherwise it's the lower boundary
199 * @param $sort bool If false, don't add an ORDER BY clause
200 */
201 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
202 $isDirNewer = ( $dir === 'newer' );
203 $after = ( $isDirNewer ? '>=' : '<=' );
204 $before = ( $isDirNewer ? '<=' : '>=' );
205 $db = $this->getDB();
206
207 if ( !is_null( $start ) ) {
208 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
209 }
210
211 if ( !is_null( $end ) ) {
212 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
213 }
214
215 if ( $sort ) {
216 $order = $field . ( $isDirNewer ? '' : ' DESC' );
217 // Append ORDER BY
218 $optionOrderBy = isset( $this->options['ORDER BY'] ) ? (array)$this->options['ORDER BY'] : array();
219 $optionOrderBy[] = $order;
220 $this->addOption( 'ORDER BY', $optionOrderBy );
221 }
222 }
223
224 /**
225 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
226 * but converts $start and $end to database timestamps.
227 * @see addWhereRange
228 * @param $field
229 * @param $dir
230 * @param $start
231 * @param $end
232 * @param $sort bool
233 */
234 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
235 $db = $this->getDb();
236 $this->addWhereRange( $field, $dir,
237 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
238 }
239
240 /**
241 * Add an option such as LIMIT or USE INDEX. If an option was set
242 * before, the old value will be overwritten
243 * @param $name string Option name
244 * @param $value string Option value
245 */
246 protected function addOption( $name, $value = null ) {
247 if ( is_null( $value ) ) {
248 $this->options[] = $name;
249 } else {
250 $this->options[$name] = $value;
251 }
252 }
253
254 /**
255 * Execute a SELECT query based on the values in the internal arrays
256 * @param $method string Function the query should be attributed to.
257 * You should usually use __METHOD__ here
258 * @param $extraQuery array Query data to add but not store in the object
259 * Format is array( 'tables' => ..., 'fields' => ..., 'where' => ..., 'options' => ..., 'join_conds' => ... )
260 * @return ResultWrapper
261 */
262 protected function select( $method, $extraQuery = array() ) {
263
264 $tables = array_merge( $this->tables, isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array() );
265 $fields = array_merge( $this->fields, isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array() );
266 $where = array_merge( $this->where, isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array() );
267 $options = array_merge( $this->options, isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array() );
268 $join_conds = array_merge( $this->join_conds, isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array() );
269
270 // getDB has its own profileDBIn/Out calls
271 $db = $this->getDB();
272
273 $this->profileDBIn();
274 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
275 $this->profileDBOut();
276
277 return $res;
278 }
279
280 /**
281 * Estimate the row count for the SELECT query that would be run if we
282 * called select() right now, and check if it's acceptable.
283 * @return bool true if acceptable, false otherwise
284 */
285 protected function checkRowCount() {
286 $db = $this->getDB();
287 $this->profileDBIn();
288 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
289 $this->profileDBOut();
290
291 global $wgAPIMaxDBRows;
292 if ( $rowcount > $wgAPIMaxDBRows ) {
293 return false;
294 }
295 return true;
296 }
297
298 /**
299 * Add information (title and namespace) about a Title object to a
300 * result array
301 * @param $arr array Result array à la ApiResult
302 * @param $title Title
303 * @param $prefix string Module prefix
304 */
305 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
306 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
307 $arr[$prefix . 'title'] = $title->getPrefixedText();
308 }
309
310 /**
311 * Override this method to request extra fields from the pageSet
312 * using $pageSet->requestField('fieldName')
313 * @param $pageSet ApiPageSet
314 */
315 public function requestExtraData( $pageSet ) {
316 }
317
318 /**
319 * Get the main Query module
320 * @return ApiQuery
321 */
322 public function getQuery() {
323 return $this->mQueryModule;
324 }
325
326 /**
327 * Add a sub-element under the page element with the given page ID
328 * @param $pageId int Page ID
329 * @param $data array Data array à la ApiResult
330 * @return bool Whether the element fit in the result
331 */
332 protected function addPageSubItems( $pageId, $data ) {
333 $result = $this->getResult();
334 $result->setIndexedTagName( $data, $this->getModulePrefix() );
335 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
336 $this->getModuleName(),
337 $data );
338 }
339
340 /**
341 * Same as addPageSubItems(), but one element of $data at a time
342 * @param $pageId int Page ID
343 * @param $item array Data array à la ApiResult
344 * @param $elemname string XML element name. If null, getModuleName()
345 * is used
346 * @return bool Whether the element fit in the result
347 */
348 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
349 if ( is_null( $elemname ) ) {
350 $elemname = $this->getModulePrefix();
351 }
352 $result = $this->getResult();
353 $fit = $result->addValue( array( 'query', 'pages', $pageId,
354 $this->getModuleName() ), null, $item );
355 if ( !$fit ) {
356 return false;
357 }
358 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
359 $this->getModuleName() ), $elemname );
360 return true;
361 }
362
363 /**
364 * Set a query-continue value
365 * @param $paramName string Parameter name
366 * @param $paramValue string Parameter value
367 */
368 protected function setContinueEnumParameter( $paramName, $paramValue ) {
369 $paramName = $this->encodeParamName( $paramName );
370 $msg = array( $paramName => $paramValue );
371 $result = $this->getResult();
372 $result->disableSizeCheck();
373 $result->addValue( 'query-continue', $this->getModuleName(), $msg );
374 $result->enableSizeCheck();
375 }
376
377 /**
378 * Get the Query database connection (read-only)
379 * @return DatabaseBase
380 */
381 protected function getDB() {
382 if ( is_null( $this->mDb ) ) {
383 $apiQuery = $this->getQuery();
384 $this->mDb = $apiQuery->getDB();
385 }
386 return $this->mDb;
387 }
388
389 /**
390 * Selects the query database connection with the given name.
391 * See ApiQuery::getNamedDB() for more information
392 * @param $name string Name to assign to the database connection
393 * @param $db int One of the DB_* constants
394 * @param $groups array Query groups
395 * @return DatabaseBase
396 */
397 public function selectNamedDB( $name, $db, $groups ) {
398 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
399 }
400
401 /**
402 * Get the PageSet object to work on
403 * @return ApiPageSet
404 */
405 protected function getPageSet() {
406 return $this->getQuery()->getPageSet();
407 }
408
409 /**
410 * Convert a title to a DB key
411 * @param $title string Page title with spaces
412 * @return string Page title with underscores
413 */
414 public function titleToKey( $title ) {
415 // Don't throw an error if we got an empty string
416 if ( trim( $title ) == '' ) {
417 return '';
418 }
419 $t = Title::newFromText( $title );
420 if ( !$t ) {
421 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
422 }
423 return $t->getPrefixedDbKey();
424 }
425
426 /**
427 * The inverse of titleToKey()
428 * @param $key string Page title with underscores
429 * @return string Page title with spaces
430 */
431 public function keyToTitle( $key ) {
432 // Don't throw an error if we got an empty string
433 if ( trim( $key ) == '' ) {
434 return '';
435 }
436 $t = Title::newFromDbKey( $key );
437 // This really shouldn't happen but we gotta check anyway
438 if ( !$t ) {
439 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
440 }
441 return $t->getPrefixedText();
442 }
443
444 /**
445 * An alternative to titleToKey() that doesn't trim trailing spaces
446 * @param $titlePart string Title part with spaces
447 * @return string Title part with underscores
448 */
449 public function titlePartToKey( $titlePart ) {
450 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
451 }
452
453 /**
454 * An alternative to keyToTitle() that doesn't trim trailing spaces
455 * @param $keyPart string Key part with spaces
456 * @return string Key part with underscores
457 */
458 public function keyPartToTitle( $keyPart ) {
459 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
460 }
461
462 /**
463 * Gets the personalised direction parameter description
464 *
465 * @param string $p ModulePrefix
466 * @param string $extraDirText Any extra text to be appended on the description
467 * @return array
468 */
469 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
470 return array(
471 "In which direction to enumerate{$extraDirText}",
472 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
473 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
474 );
475 }
476
477 /**
478 * @param $query String
479 * @param $protocol String
480 * @return null|string
481 */
482 public function prepareUrlQuerySearchString( $query = null, $protocol = null) {
483 $db = $this->getDb();
484 if ( !is_null( $query ) || $query != '' ) {
485 if ( is_null( $protocol ) ) {
486 $protocol = 'http://';
487 }
488
489 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
490 if ( !$likeQuery ) {
491 $this->dieUsage( 'Invalid query', 'bad_query' );
492 }
493
494 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
495 return 'el_index ' . $db->buildLike( $likeQuery );
496 } elseif ( !is_null( $protocol ) ) {
497 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
498 }
499
500 return null;
501 }
502
503 /**
504 * Filters hidden users (where the user doesn't have the right to view them)
505 * Also adds relevant block information
506 *
507 * @param bool $showBlockInfo
508 * @return void
509 */
510 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
511 $userCanViewHiddenUsers = $this->getUser()->isAllowed( 'hideuser' );
512
513 if ( $showBlockInfo || !$userCanViewHiddenUsers ) {
514 $this->addTables( 'ipblocks' );
515 $this->addJoinConds( array(
516 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
517 ) );
518
519 $this->addFields( 'ipb_deleted' );
520
521 if ( $showBlockInfo ) {
522 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry' ) );
523 }
524
525 // Don't show hidden names
526 if ( !$userCanViewHiddenUsers ) {
527 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
528 }
529 }
530 }
531
532 /**
533 * @param $hash string
534 * @return bool
535 */
536 public function validateSha1Hash( $hash ) {
537 return preg_match( '/^[a-f0-9]{40}$/', $hash );
538 }
539
540 /**
541 * @param $hash string
542 * @return bool
543 */
544 public function validateSha1Base36Hash( $hash ) {
545 return preg_match( '/^[a-z0-9]{31}$/', $hash );
546 }
547
548 /**
549 * @return array
550 */
551 public function getPossibleErrors() {
552 return array_merge( parent::getPossibleErrors(), array(
553 array( 'invalidtitle', 'title' ),
554 array( 'invalidtitle', 'key' ),
555 ) );
556 }
557
558 /**
559 * Get version string for use in the API help output
560 * @return string
561 */
562 public static function getBaseVersion() {
563 return __CLASS__ . ': $Id$';
564 }
565 }
566
567 /**
568 * @ingroup API
569 */
570 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
571
572 private $mIsGenerator;
573
574 /**
575 * @param $query ApiBase
576 * @param $moduleName string
577 * @param $paramPrefix string
578 */
579 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
580 parent::__construct( $query, $moduleName, $paramPrefix );
581 $this->mIsGenerator = false;
582 }
583
584 /**
585 * Switch this module to generator mode. By default, generator mode is
586 * switched off and the module acts like a normal query module.
587 */
588 public function setGeneratorMode() {
589 $this->mIsGenerator = true;
590 }
591
592 /**
593 * Overrides base class to prepend 'g' to every generator parameter
594 * @param $paramName string Parameter name
595 * @return string Prefixed parameter name
596 */
597 public function encodeParamName( $paramName ) {
598 if ( $this->mIsGenerator ) {
599 return 'g' . parent::encodeParamName( $paramName );
600 } else {
601 return parent::encodeParamName( $paramName );
602 }
603 }
604
605 /**
606 * Execute this module as a generator
607 * @param $resultPageSet ApiPageSet: All output should be appended to
608 * this object
609 */
610 public abstract function executeGenerator( $resultPageSet );
611 }