API performance enhancements (bug 13511):
[lhc/web/wiklou.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 queries.
34 *
35 * @addtogroup API
36 */
37 abstract class ApiQueryBase extends ApiBase {
38
39 private $mQueryModule, $mDb, $tables, $where, $fields, $options;
40
41 public function __construct($query, $moduleName, $paramPrefix = '') {
42 parent :: __construct($query->getMain(), $moduleName, $paramPrefix);
43 $this->mQueryModule = $query;
44 $this->mDb = null;
45 $this->resetQueryParams();
46 }
47
48 protected function resetQueryParams() {
49 $this->tables = array ();
50 $this->where = array ();
51 $this->fields = array ();
52 $this->options = array ();
53 }
54
55 protected function addTables($tables, $alias = null) {
56 if (is_array($tables)) {
57 if (!is_null($alias))
58 ApiBase :: dieDebug(__METHOD__, 'Multiple table aliases not supported');
59 $this->tables = array_merge($this->tables, $tables);
60 } else {
61 if (!is_null($alias))
62 $tables = $this->getDB()->tableName($tables) . ' ' . $alias;
63 $this->tables[] = $tables;
64 }
65 }
66
67 protected function addFields($value) {
68 if (is_array($value))
69 $this->fields = array_merge($this->fields, $value);
70 else
71 $this->fields[] = $value;
72 }
73
74 protected function addFieldsIf($value, $condition) {
75 if ($condition) {
76 $this->addFields($value);
77 return true;
78 }
79 return false;
80 }
81
82 protected function addWhere($value) {
83 if (is_array($value))
84 $this->where = array_merge($this->where, $value);
85 else
86 $this->where[] = $value;
87 }
88
89 protected function addWhereIf($value, $condition) {
90 if ($condition) {
91 $this->addWhere($value);
92 return true;
93 }
94 return false;
95 }
96
97 protected function addWhereFld($field, $value) {
98 if (!is_null($value))
99 $this->where[$field] = $value;
100 }
101
102 protected function addWhereRange($field, $dir, $start, $end) {
103 $isDirNewer = ($dir === 'newer');
104 $after = ($isDirNewer ? '>=' : '<=');
105 $before = ($isDirNewer ? '<=' : '>=');
106 $db = $this->getDB();
107
108 if (!is_null($start))
109 $this->addWhere($field . $after . $db->addQuotes($start));
110
111 if (!is_null($end))
112 $this->addWhere($field . $before . $db->addQuotes($end));
113
114 $order = $field . ($isDirNewer ? '' : ' DESC');
115 if (!isset($this->options['ORDER BY']))
116 $this->addOption('ORDER BY', $order);
117 else
118 $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
119 }
120
121 protected function addOption($name, $value = null) {
122 if (is_null($value))
123 $this->options[] = $name;
124 else
125 $this->options[$name] = $value;
126 }
127
128 protected function select($method) {
129
130 // getDB has its own profileDBIn/Out calls
131 $db = $this->getDB();
132
133 $this->profileDBIn();
134 $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options);
135 $this->profileDBOut();
136
137 return $res;
138 }
139
140 protected function checkRowCount() {
141 $db = $this->getDB();
142 $this->profileDBIn();
143 $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
144 $this->profileDBOut();
145
146 global $wgAPIMaxDBRows;
147 if($rowcount > $wgAPIMaxDBRows)
148 return false;
149 return true;
150 }
151
152 public static function addTitleInfo(&$arr, $title, $prefix='') {
153 $arr[$prefix . 'ns'] = intval($title->getNamespace());
154 $arr[$prefix . 'title'] = $title->getPrefixedText();
155 }
156
157 /**
158 * Override this method to request extra fields from the pageSet
159 * using $pageSet->requestField('fieldName')
160 */
161 public function requestExtraData($pageSet) {
162 }
163
164 /**
165 * Get the main Query module
166 */
167 public function getQuery() {
168 return $this->mQueryModule;
169 }
170
171 /**
172 * Add sub-element under the page element with the given pageId.
173 */
174 protected function addPageSubItems($pageId, $data) {
175 $result = $this->getResult();
176 $result->setIndexedTagName($data, $this->getModulePrefix());
177 $result->addValue(array ('query', 'pages', intval($pageId)),
178 $this->getModuleName(),
179 $data);
180 }
181
182 protected function setContinueEnumParameter($paramName, $paramValue) {
183
184 $paramName = $this->encodeParamName($paramName);
185 $msg = array( $paramName => $paramValue );
186
187 // This is an alternative continue format as a part of the URL string
188 // ApiResult :: setContent($msg, $paramName . '=' . urlencode($paramValue));
189
190 $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
191 }
192
193 /**
194 * Get the Query database connection (readonly)
195 */
196 protected function getDB() {
197 if (is_null($this->mDb))
198 $this->mDb = $this->getQuery()->getDB();
199 return $this->mDb;
200 }
201
202 /**
203 * Selects the query database connection with the given name.
204 * If no such connection has been requested before, it will be created.
205 * Subsequent calls with the same $name will return the same connection
206 * as the first, regardless of $db or $groups new values.
207 */
208 public function selectNamedDB($name, $db, $groups) {
209 $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
210 }
211
212 /**
213 * Get the PageSet object to work on
214 * @return ApiPageSet data
215 */
216 protected function getPageSet() {
217 return $this->getQuery()->getPageSet();
218 }
219
220 /**
221 * This is a very simplistic utility function
222 * to convert a non-namespaced title string to a db key.
223 * It will replace all ' ' with '_'
224 */
225 public static function titleToKey($title) {
226 return str_replace(' ', '_', $title);
227 }
228
229 public static function keyToTitle($key) {
230 return str_replace('_', ' ', $key);
231 }
232
233 public function getTokenFlag($tokenArr, $action) {
234 if ($this->getMain()->getRequest()->getVal('callback') !== null) {
235 // Don't do any session-specific data.
236 return false;
237 }
238 if (in_array($action, $tokenArr)) {
239 global $wgUser;
240 if ($wgUser->isAllowed($action))
241 return true;
242 else
243 $this->dieUsage("Action '$action' is not allowed for the current user", 'permissiondenied');
244 }
245 return false;
246 }
247
248 public static function getBaseVersion() {
249 return __CLASS__ . ': $Id$';
250 }
251 }
252
253 /**
254 * @addtogroup API
255 */
256 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
257
258 private $mIsGenerator;
259
260 public function __construct($query, $moduleName, $paramPrefix = '') {
261 parent :: __construct($query, $moduleName, $paramPrefix);
262 $this->mIsGenerator = false;
263 }
264
265 public function setGeneratorMode() {
266 $this->mIsGenerator = true;
267 }
268
269 /**
270 * Overrides base class to prepend 'g' to every generator parameter
271 */
272 public function encodeParamName($paramName) {
273 if ($this->mIsGenerator)
274 return 'g' . parent :: encodeParamName($paramName);
275 else
276 return parent :: encodeParamName($paramName);
277 }
278
279 /**
280 * Execute this module as a generator
281 * @param $resultPageSet PageSet: All output should be appended to this object
282 */
283 public abstract function executeGenerator($resultPageSet);
284 }
285