]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/api/ApiQueryBase.php
MediaWiki 1.15.5
[autoinstallsdev/mediawiki.git] / includes / api / ApiQueryBase.php
1 <?php
2
3 /*
4  * Created on Sep 7, 2006
5  *
6  * API for MediaWiki 1.8+
7  *
8  * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  * http://www.gnu.org/copyleft/gpl.html
24  */
25
26 if (!defined('MEDIAWIKI')) {
27         // Eclipse helper - will be ignored in production
28         require_once ('ApiBase.php');
29 }
30
31 /**
32  * This is a base class for all Query modules.
33  * It provides some common functionality such as constructing various SQL
34  * queries.
35  *
36  * @ingroup API
37  */
38 abstract class ApiQueryBase extends ApiBase {
39
40         private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
41
42         public function __construct($query, $moduleName, $paramPrefix = '') {
43                 parent :: __construct($query->getMain(), $moduleName, $paramPrefix);
44                 $this->mQueryModule = $query;
45                 $this->mDb = null;
46                 $this->resetQueryParams();
47         }
48
49         /**
50          * Get the cache mode for the data generated by this module. Override this 
51          * in the module subclass.
52          *
53          * Public caching will only be allowed if *all* the modules that supply 
54          * data for a given request return a cache mode of public.
55          */
56         public function getCacheMode( $params ) {
57                 return 'private';
58         }
59
60         /**
61          * Blank the internal arrays with query parameters
62          */
63         protected function resetQueryParams() {
64                 $this->tables = array ();
65                 $this->where = array ();
66                 $this->fields = array ();
67                 $this->options = array ();
68                 $this->join_conds = array ();
69         }
70
71         /**
72          * Add a set of tables to the internal array
73          * @param $tables mixed Table name or array of table names
74          * @param $alias mixed Table alias, or null for no alias. Cannot be
75          *  used with multiple tables
76          */
77         protected function addTables($tables, $alias = null) {
78                 if (is_array($tables)) {
79                         if (!is_null($alias))
80                                 ApiBase :: dieDebug(__METHOD__, 'Multiple table aliases not supported');
81                         $this->tables = array_merge($this->tables, $tables);
82                 } else {
83                         if (!is_null($alias))
84                                 $tables = $this->getAliasedName($tables, $alias);
85                         $this->tables[] = $tables;
86                 }
87         }
88         
89         /**
90          * Get the SQL for a table name with alias
91          * @param $table string Table name
92          * @param $alias string Alias
93          * @return string SQL
94          */
95         protected function getAliasedName($table, $alias) {
96                 return $this->getDB()->tableName($table) . ' ' . $alias;
97         }
98         
99         /**
100          * Add a set of JOIN conditions to the internal array
101          *
102          * JOIN conditions are formatted as array( tablename => array(jointype,
103          * conditions) e.g. array('page' => array('LEFT JOIN',
104          * 'page_id=rev_page')) . conditions may be a string or an
105          * addWhere()-style array
106          * @param $join_conds array JOIN conditions
107          */
108         protected function addJoinConds($join_conds) {
109                 if(!is_array($join_conds))
110                         ApiBase::dieDebug(__METHOD__, 'Join conditions have to be arrays');
111                 $this->join_conds = array_merge($this->join_conds, $join_conds);
112         }
113
114         /**
115          * Add a set of fields to select to the internal array
116          * @param $value mixed Field name or array of field names
117          */
118         protected function addFields($value) {
119                 if (is_array($value))
120                         $this->fields = array_merge($this->fields, $value);
121                 else
122                         $this->fields[] = $value;
123         }
124
125         /**
126          * Same as addFields(), but add the fields only if a condition is met
127          * @param $value mixed 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          * Same as addWhere(), but add the WHERE clauses only if a condition is met
163          * @param $value mixed See addWhere()
164          * @param $condition boolIf 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          * Add a WHERE clause corresponding to a range, and an ORDER BY
189          * clause to sort in the right direction
190          * @param $field string Field name
191          * @param $dir string If 'newer', sort in ascending order, otherwise
192          *  sort in descending order
193          * @param $start string Value to start the list at. If $dir == 'newer'
194          *  this is the lower boundary, otherwise it's the upper boundary
195          * @param $end string Value to end the list at. If $dir == 'newer' this
196          *  is the upper boundary, otherwise it's the lower boundary
197          * @param $sort bool If false, don't add an ORDER BY clause
198          */
199         protected function addWhereRange($field, $dir, $start, $end, $sort = true) {
200                 $isDirNewer = ($dir === 'newer');
201                 $after = ($isDirNewer ? '>=' : '<=');
202                 $before = ($isDirNewer ? '<=' : '>=');
203                 $db = $this->getDB();
204
205                 if (!is_null($start))
206                         $this->addWhere($field . $after . $db->addQuotes($start));
207
208                 if (!is_null($end))
209                         $this->addWhere($field . $before . $db->addQuotes($end));
210
211                 if ($sort) {
212                         $order = $field . ($isDirNewer ? '' : ' DESC');
213                         if (!isset($this->options['ORDER BY']))
214                                 $this->addOption('ORDER BY', $order);
215                         else
216                                 $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
217                 }
218         }
219
220         /**
221          * Add an option such as LIMIT or USE INDEX. If an option was set
222          * before, the old value will be overwritten
223          * @param $name string Option name
224          * @param $value string Option value
225          */
226         protected function addOption($name, $value = null) {
227                 if (is_null($value))
228                         $this->options[] = $name;
229                 else
230                         $this->options[$name] = $value;
231         }
232
233         /**
234          * Execute a SELECT query based on the values in the internal arrays
235          * @param $method string Function the query should be attributed to.
236          *  You should usually use __METHOD__ here
237          * @return ResultWrapper
238          */
239         protected function select($method) {
240
241                 // getDB has its own profileDBIn/Out calls
242                 $db = $this->getDB();
243
244                 $this->profileDBIn();
245                 $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds);
246                 $this->profileDBOut();
247
248                 return $res;
249         }
250
251         /**
252          * Estimate the row count for the SELECT query that would be run if we
253          * called select() right now, and check if it's acceptable.
254          * @return bool true if acceptable, false otherwise
255          */
256         protected function checkRowCount() {
257                 $db = $this->getDB();
258                 $this->profileDBIn();
259                 $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
260                 $this->profileDBOut();
261
262                 global $wgAPIMaxDBRows;
263                 if($rowcount > $wgAPIMaxDBRows)
264                         return false;
265                 return true;
266         }
267
268         /**
269          * Add information (title and namespace) about a Title object to a
270          * result array
271          * @param $arr array Result array à la ApiResult
272          * @param $title Title
273          * @param $prefix string Module prefix
274          */
275         public static function addTitleInfo(&$arr, $title, $prefix='') {
276                 $arr[$prefix . 'ns'] = intval($title->getNamespace());
277                 $arr[$prefix . 'title'] = $title->getPrefixedText();
278         }
279
280         /**
281          * Override this method to request extra fields from the pageSet
282          * using $pageSet->requestField('fieldName')
283          * @param $pageSet ApiPageSet
284          */
285         public function requestExtraData($pageSet) {
286         }
287
288         /**
289          * Get the main Query module
290          * @return ApiQuery
291          */
292         public function getQuery() {
293                 return $this->mQueryModule;
294         }
295
296         /**
297          * Add a sub-element under the page element with the given page ID
298          * @param $pageId int Page ID
299          * @param $data array Data array à la ApiResult 
300          * @return bool Whether the element fit in the result
301          */
302         protected function addPageSubItems($pageId, $data) {
303                 $result = $this->getResult();
304                 $result->setIndexedTagName($data, $this->getModulePrefix());
305                 return $result->addValue(array('query', 'pages', intval($pageId)),
306                         $this->getModuleName(),
307                         $data);
308         }
309         
310         /**
311          * Same as addPageSubItems(), but one element of $data at a time
312          * @param $pageId int Page ID
313          * @param $data array Data array à la ApiResult
314          * @param $elemname string XML element name. If null, getModuleName()
315          *  is used
316          * @return bool Whether the element fit in the result
317          */
318         protected function addPageSubItem($pageId, $item, $elemname = null) {
319                 if(is_null($elemname))
320                         $elemname = $this->getModulePrefix();
321                 $result = $this->getResult();
322                 $fit = $result->addValue(array('query', 'pages', $pageId,
323                                          $this->getModuleName()), null, $item);
324                 if(!$fit)
325                         return false;
326                 $result->setIndexedTagName_internal(array('query', 'pages', $pageId,
327                                 $this->getModuleName()), $elemname);
328                 return true;
329         }
330
331         /**
332          * Set a query-continue value
333          * @param $paramName string Parameter name
334          * @param $paramValue string Parameter value
335          */
336         protected function setContinueEnumParameter($paramName, $paramValue) {
337                 $paramName = $this->encodeParamName($paramName);
338                 $msg = array( $paramName => $paramValue );
339                 $this->getResult()->disableSizeCheck();
340                 $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
341                 $this->getResult()->enableSizeCheck();
342         }
343
344         /**
345          * Get the Query database connection (read-only)
346          * @return Database
347          */
348         protected function getDB() {
349                 if (is_null($this->mDb))
350                         $this->mDb = $this->getQuery()->getDB();
351                 return $this->mDb;
352         }
353
354         /**
355          * Selects the query database connection with the given name.
356          * See ApiQuery::getNamedDB() for more information
357          * @param $name string Name to assign to the database connection
358          * @param $db int One of the DB_* constants
359          * @param $groups array Query groups
360          * @return Database 
361          */
362         public function selectNamedDB($name, $db, $groups) {
363                 $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
364         }
365
366         /**
367          * Get the PageSet object to work on
368          * @return ApiPageSet
369          */
370         protected function getPageSet() {
371                 return $this->getQuery()->getPageSet();
372         }
373
374         /**
375          * Convert a title to a DB key
376          * @param $title string Page title with spaces
377          * @return string Page title with underscores
378          */
379         public function titleToKey($title) {
380                 # Don't throw an error if we got an empty string
381                 if(trim($title) == '')
382                         return '';
383                 $t = Title::newFromText($title);
384                 if(!$t)
385                         $this->dieUsageMsg(array('invalidtitle', $title));
386                 return $t->getPrefixedDbKey();
387         }
388
389         /**
390          * The inverse of titleToKey()
391          * @param $key string Page title with underscores
392          * @return string Page title with spaces
393          */
394         public function keyToTitle($key) {
395                 # Don't throw an error if we got an empty string
396                 if(trim($key) == '')
397                         return '';
398                 $t = Title::newFromDbKey($key);
399                 # This really shouldn't happen but we gotta check anyway
400                 if(!$t)
401                         $this->dieUsageMsg(array('invalidtitle', $key));
402                 return $t->getPrefixedText();
403         }
404         
405         /**
406          * An alternative to titleToKey() that doesn't trim trailing spaces
407          * @param $titlePart string Title part with spaces
408          * @return string Title part with underscores
409          */
410         public function titlePartToKey($titlePart) {
411                 return substr($this->titleToKey($titlePart . 'x'), 0, -1);
412         }
413         
414         /**
415          * An alternative to keyToTitle() that doesn't trim trailing spaces
416          * @param $keyPart string Key part with spaces
417          * @return string Key part with underscores
418          */
419         public function keyPartToTitle($keyPart) {
420                 return substr($this->keyToTitle($keyPart . 'x'), 0, -1);
421         }
422
423         /**
424          * Get version string for use in the API help output
425          * @return string
426          */
427         public static function getBaseVersion() {
428                 return __CLASS__ . ': $Id: ApiQueryBase.php 69986 2010-07-27 03:57:39Z tstarling $';
429         }
430 }
431
432 /**
433  * @ingroup API
434  */
435 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
436
437         private $mIsGenerator;
438
439         public function __construct($query, $moduleName, $paramPrefix = '') {
440                 parent :: __construct($query, $moduleName, $paramPrefix);
441                 $this->mIsGenerator = false;
442         }
443
444         /**
445          * Switch this module to generator mode. By default, generator mode is
446          * switched off and the module acts like a normal query module.
447          */
448         public function setGeneratorMode() {
449                 $this->mIsGenerator = true;
450         }
451
452         /**
453          * Overrides base class to prepend 'g' to every generator parameter
454          * @param $paramNames string Parameter name
455          * @return string Prefixed parameter name
456          */
457         public function encodeParamName($paramName) {
458                 if ($this->mIsGenerator)
459                         return 'g' . parent :: encodeParamName($paramName);
460                 else
461                         return parent :: encodeParamName($paramName);
462         }
463
464         /**
465          * Execute this module as a generator
466          * @param $resultPageSet ApiPageSet: All output should be appended to
467          *  this object
468          */
469         public abstract function executeGenerator($resultPageSet);
470 }