]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/api/ApiQueryBase.php
9d1cbceae741de61cfb224da0c2e0313fd0715fa
[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          * Blank the internal arrays with query parameters
51          */
52         protected function resetQueryParams() {
53                 $this->tables = array ();
54                 $this->where = array ();
55                 $this->fields = array ();
56                 $this->options = array ();
57                 $this->join_conds = array ();
58         }
59
60         /**
61          * Add a set of tables to the internal array
62          * @param $tables mixed Table name or array of table names
63          * @param $alias mixed Table alias, or null for no alias. Cannot be
64          *  used with multiple tables
65          */
66         protected function addTables($tables, $alias = null) {
67                 if (is_array($tables)) {
68                         if (!is_null($alias))
69                                 ApiBase :: dieDebug(__METHOD__, 'Multiple table aliases not supported');
70                         $this->tables = array_merge($this->tables, $tables);
71                 } else {
72                         if (!is_null($alias))
73                                 $tables = $this->getAliasedName($tables, $alias);
74                         $this->tables[] = $tables;
75                 }
76         }
77         
78         /**
79          * Get the SQL for a table name with alias
80          * @param $table string Table name
81          * @param $alias string Alias
82          * @return string SQL
83          */
84         protected function getAliasedName($table, $alias) {
85                 return $this->getDB()->tableName($table) . ' ' . $alias;
86         }
87         
88         /**
89          * Add a set of JOIN conditions to the internal array
90          *
91          * JOIN conditions are formatted as array( tablename => array(jointype,
92          * conditions) e.g. array('page' => array('LEFT JOIN',
93          * 'page_id=rev_page')) . conditions may be a string or an
94          * addWhere()-style array
95          * @param $join_conds array JOIN conditions
96          */
97         protected function addJoinConds($join_conds) {
98                 if(!is_array($join_conds))
99                         ApiBase::dieDebug(__METHOD__, 'Join conditions have to be arrays');
100                 $this->join_conds = array_merge($this->join_conds, $join_conds);
101         }
102
103         /**
104          * Add a set of fields to select to the internal array
105          * @param $value mixed Field name or array of field names
106          */
107         protected function addFields($value) {
108                 if (is_array($value))
109                         $this->fields = array_merge($this->fields, $value);
110                 else
111                         $this->fields[] = $value;
112         }
113
114         /**
115          * Same as addFields(), but add the fields only if a condition is met
116          * @param $value mixed See addFields()
117          * @param $condition bool If false, do nothing
118          * @return bool $condition
119          */
120         protected function addFieldsIf($value, $condition) {
121                 if ($condition) {
122                         $this->addFields($value);
123                         return true;
124                 }
125                 return false;
126         }
127
128         /**
129          * Add a set of WHERE clauses to the internal array.
130          * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
131          * the latter only works if the value is a constant (i.e. not another field)
132          *
133          * If $value is an empty array, this function does nothing.
134          *
135          * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
136          * to "foo=bar AND baz='3' AND bla='foo'"
137          * @param $value mixed String or array
138          */
139         protected function addWhere($value) {
140                 if (is_array($value)) {
141                         // Sanity check: don't insert empty arrays,
142                         // Database::makeList() chokes on them
143                         if ( count( $value ) )
144                                 $this->where = array_merge($this->where, $value);
145                 }
146                 else
147                         $this->where[] = $value;
148         }
149
150         /**
151          * Same as addWhere(), but add the WHERE clauses only if a condition is met
152          * @param $value mixed See addWhere()
153          * @param $condition boolIf false, do nothing
154          * @return bool $condition
155          */
156         protected function addWhereIf($value, $condition) {
157                 if ($condition) {
158                         $this->addWhere($value);
159                         return true;
160                 }
161                 return false;
162         }
163
164         /**
165          * Equivalent to addWhere(array($field => $value))
166          * @param $field string Field name
167          * @param $value string Value; ignored if null or empty array;
168          */
169         protected function addWhereFld($field, $value) {
170                 // Use count() to its full documented capabilities to simultaneously 
171                 // test for null, empty array or empty countable object
172                 if ( count( $value ) )
173                         $this->where[$field] = $value;
174         }
175
176         /**
177          * Add a WHERE clause corresponding to a range, and an ORDER BY
178          * clause to sort in the right direction
179          * @param $field string Field name
180          * @param $dir string If 'newer', sort in ascending order, otherwise
181          *  sort in descending order
182          * @param $start string Value to start the list at. If $dir == 'newer'
183          *  this is the lower boundary, otherwise it's the upper boundary
184          * @param $end string Value to end the list at. If $dir == 'newer' this
185          *  is the upper boundary, otherwise it's the lower boundary
186          * @param $sort bool If false, don't add an ORDER BY clause
187          */
188         protected function addWhereRange($field, $dir, $start, $end, $sort = true) {
189                 $isDirNewer = ($dir === 'newer');
190                 $after = ($isDirNewer ? '>=' : '<=');
191                 $before = ($isDirNewer ? '<=' : '>=');
192                 $db = $this->getDB();
193
194                 if (!is_null($start))
195                         $this->addWhere($field . $after . $db->addQuotes($start));
196
197                 if (!is_null($end))
198                         $this->addWhere($field . $before . $db->addQuotes($end));
199
200                 if ($sort) {
201                         $order = $field . ($isDirNewer ? '' : ' DESC');
202                         if (!isset($this->options['ORDER BY']))
203                                 $this->addOption('ORDER BY', $order);
204                         else
205                                 $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
206                 }
207         }
208
209         /**
210          * Add an option such as LIMIT or USE INDEX. If an option was set
211          * before, the old value will be overwritten
212          * @param $name string Option name
213          * @param $value string Option value
214          */
215         protected function addOption($name, $value = null) {
216                 if (is_null($value))
217                         $this->options[] = $name;
218                 else
219                         $this->options[$name] = $value;
220         }
221
222         /**
223          * Execute a SELECT query based on the values in the internal arrays
224          * @param $method string Function the query should be attributed to.
225          *  You should usually use __METHOD__ here
226          * @return ResultWrapper
227          */
228         protected function select($method) {
229
230                 // getDB has its own profileDBIn/Out calls
231                 $db = $this->getDB();
232
233                 $this->profileDBIn();
234                 $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds);
235                 $this->profileDBOut();
236
237                 return $res;
238         }
239
240         /**
241          * Estimate the row count for the SELECT query that would be run if we
242          * called select() right now, and check if it's acceptable.
243          * @return bool true if acceptable, false otherwise
244          */
245         protected function checkRowCount() {
246                 $db = $this->getDB();
247                 $this->profileDBIn();
248                 $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
249                 $this->profileDBOut();
250
251                 global $wgAPIMaxDBRows;
252                 if($rowcount > $wgAPIMaxDBRows)
253                         return false;
254                 return true;
255         }
256
257         /**
258          * Add information (title and namespace) about a Title object to a
259          * result array
260          * @param $arr array Result array à la ApiResult
261          * @param $title Title
262          * @param $prefix string Module prefix
263          */
264         public static function addTitleInfo(&$arr, $title, $prefix='') {
265                 $arr[$prefix . 'ns'] = intval($title->getNamespace());
266                 $arr[$prefix . 'title'] = $title->getPrefixedText();
267         }
268
269         /**
270          * Override this method to request extra fields from the pageSet
271          * using $pageSet->requestField('fieldName')
272          * @param $pageSet ApiPageSet
273          */
274         public function requestExtraData($pageSet) {
275         }
276
277         /**
278          * Get the main Query module
279          * @return ApiQuery
280          */
281         public function getQuery() {
282                 return $this->mQueryModule;
283         }
284
285         /**
286          * Add a sub-element under the page element with the given page ID
287          * @param $pageId int Page ID
288          * @param $data array Data array à la ApiResult 
289          * @return bool Whether the element fit in the result
290          */
291         protected function addPageSubItems($pageId, $data) {
292                 $result = $this->getResult();
293                 $result->setIndexedTagName($data, $this->getModulePrefix());
294                 return $result->addValue(array('query', 'pages', intval($pageId)),
295                         $this->getModuleName(),
296                         $data);
297         }
298         
299         /**
300          * Same as addPageSubItems(), but one element of $data at a time
301          * @param $pageId int Page ID
302          * @param $data array Data array à la ApiResult
303          * @param $elemname string XML element name. If null, getModuleName()
304          *  is used
305          * @return bool Whether the element fit in the result
306          */
307         protected function addPageSubItem($pageId, $item, $elemname = null) {
308                 if(is_null($elemname))
309                         $elemname = $this->getModulePrefix();
310                 $result = $this->getResult();
311                 $fit = $result->addValue(array('query', 'pages', $pageId,
312                                          $this->getModuleName()), null, $item);
313                 if(!$fit)
314                         return false;
315                 $result->setIndexedTagName_internal(array('query', 'pages', $pageId,
316                                 $this->getModuleName()), $elemname);
317                 return true;
318         }
319
320         /**
321          * Set a query-continue value
322          * @param $paramName string Parameter name
323          * @param $paramValue string Parameter value
324          */
325         protected function setContinueEnumParameter($paramName, $paramValue) {
326                 $paramName = $this->encodeParamName($paramName);
327                 $msg = array( $paramName => $paramValue );
328                 $this->getResult()->disableSizeCheck();
329                 $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
330                 $this->getResult()->enableSizeCheck();
331         }
332
333         /**
334          * Get the Query database connection (read-only)
335          * @return Database
336          */
337         protected function getDB() {
338                 if (is_null($this->mDb))
339                         $this->mDb = $this->getQuery()->getDB();
340                 return $this->mDb;
341         }
342
343         /**
344          * Selects the query database connection with the given name.
345          * See ApiQuery::getNamedDB() for more information
346          * @param $name string Name to assign to the database connection
347          * @param $db int One of the DB_* constants
348          * @param $groups array Query groups
349          * @return Database 
350          */
351         public function selectNamedDB($name, $db, $groups) {
352                 $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
353         }
354
355         /**
356          * Get the PageSet object to work on
357          * @return ApiPageSet
358          */
359         protected function getPageSet() {
360                 return $this->getQuery()->getPageSet();
361         }
362
363         /**
364          * Convert a title to a DB key
365          * @param $title string Page title with spaces
366          * @return string Page title with underscores
367          */
368         public function titleToKey($title) {
369                 # Don't throw an error if we got an empty string
370                 if(trim($title) == '')
371                         return '';
372                 $t = Title::newFromText($title);
373                 if(!$t)
374                         $this->dieUsageMsg(array('invalidtitle', $title));
375                 return $t->getPrefixedDbKey();
376         }
377
378         /**
379          * The inverse of titleToKey()
380          * @param $key string Page title with underscores
381          * @return string Page title with spaces
382          */
383         public function keyToTitle($key) {
384                 # Don't throw an error if we got an empty string
385                 if(trim($key) == '')
386                         return '';
387                 $t = Title::newFromDbKey($key);
388                 # This really shouldn't happen but we gotta check anyway
389                 if(!$t)
390                         $this->dieUsageMsg(array('invalidtitle', $key));
391                 return $t->getPrefixedText();
392         }
393         
394         /**
395          * An alternative to titleToKey() that doesn't trim trailing spaces
396          * @param $titlePart string Title part with spaces
397          * @return string Title part with underscores
398          */
399         public function titlePartToKey($titlePart) {
400                 return substr($this->titleToKey($titlePart . 'x'), 0, -1);
401         }
402         
403         /**
404          * An alternative to keyToTitle() that doesn't trim trailing spaces
405          * @param $keyPart string Key part with spaces
406          * @return string Key part with underscores
407          */
408         public function keyPartToTitle($keyPart) {
409                 return substr($this->keyToTitle($keyPart . 'x'), 0, -1);
410         }
411
412         /**
413          * Get version string for use in the API help output
414          * @return string
415          */
416         public static function getBaseVersion() {
417                 return __CLASS__ . ': $Id: ApiQueryBase.php 47450 2009-02-18 15:26:09Z catrope $';
418         }
419 }
420
421 /**
422  * @ingroup API
423  */
424 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
425
426         private $mIsGenerator;
427
428         public function __construct($query, $moduleName, $paramPrefix = '') {
429                 parent :: __construct($query, $moduleName, $paramPrefix);
430                 $this->mIsGenerator = false;
431         }
432
433         /**
434          * Switch this module to generator mode. By default, generator mode is
435          * switched off and the module acts like a normal query module.
436          */
437         public function setGeneratorMode() {
438                 $this->mIsGenerator = true;
439         }
440
441         /**
442          * Overrides base class to prepend 'g' to every generator parameter
443          * @param $paramNames string Parameter name
444          * @return string Prefixed parameter name
445          */
446         public function encodeParamName($paramName) {
447                 if ($this->mIsGenerator)
448                         return 'g' . parent :: encodeParamName($paramName);
449                 else
450                         return parent :: encodeParamName($paramName);
451         }
452
453         /**
454          * Execute this module as a generator
455          * @param $resultPageSet ApiPageSet: All output should be appended to
456          *  this object
457          */
458         public abstract function executeGenerator($resultPageSet);
459 }