Base layout of the core.
[platal.git] / classes / xdb.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2008 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 **************************************************************************/
21
22 class XDB
23 {
24 private static $mysqli = null;
25
26 public static function connect()
27 {
28 global $globals;
29 XDB::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
30 if ($globals->debug & DEBUG_BT) {
31 $bt = new PlBacktrace('MySQL');
32 if (mysqli_connect_errno()) {
33 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
34 return false;
35 }
36 }
37 XDB::$mysqli->autocommit(true);
38 XDB::$mysqli->set_charset($globals->dbcharset);
39 return true;
40 }
41
42 public static function _prepare($args)
43 {
44 $query = array_map(Array('XDB', 'escape'), $args);
45 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
46 return call_user_func_array('sprintf', $query);
47 }
48
49 public static function _reformatQuery($query)
50 {
51 $query = preg_split("/\n\\s*/", trim($query));
52 $length = 0;
53 foreach ($query as $key=>$line) {
54 $local = -2;
55 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
56 && $matches[1] != 'AND' && $matches[1] != 'OR')
57 {
58 $local = strlen($matches[1]);
59 $line = $matches[1] . ' ' . $matches[2];
60 $length = max($length, $local);
61 }
62 $query[$key] = array($line, $local);
63 }
64 $res = '';
65 foreach ($query as $array) {
66 list($line, $local) = $array;
67 $local = max(0, $length - $local);
68 $res .= str_repeat(' ', $local) . $line . "\n";
69 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
70 }
71 return $res;
72 }
73
74 public static function _query($query)
75 {
76 global $globals;
77
78 if (!XDB::$mysqli && !XDB::connect()) {
79 return false;
80 }
81
82 if ($globals->debug & DEBUG_BT) {
83 $explain = array();
84 if (strpos($query, 'FOUND_ROWS()') === false) {
85 $res = XDB::$mysqli->query("EXPLAIN $query");
86 if ($res) {
87 while ($row = $res->fetch_assoc()) {
88 $explain[] = $row;
89 }
90 $res->free();
91 }
92 }
93 PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
94 }
95
96 $res = XDB::$mysqli->query($query);
97
98 if ($globals->debug & DEBUG_BT) {
99 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows,
100 XDB::$mysqli->error,
101 $explain);
102 }
103 return $res;
104 }
105
106 public static function query()
107 {
108 return new XOrgDBResult(XDB::_prepare(func_get_args()));
109 }
110
111 public static function execute()
112 {
113 global $globals;
114 $args = func_get_args();
115 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
116 return;
117 }
118 return XDB::_query(XDB::_prepare($args));
119 }
120
121 public static function iterator()
122 {
123 return new XOrgDBIterator(XDB::_prepare(func_get_args()));
124 }
125
126 public static function iterRow()
127 {
128 return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
129 }
130
131 public static function insertId()
132 {
133 return XDB::$mysqli->insert_id;
134 }
135
136 public static function errno()
137 {
138 return XDB::$mysqli->errno;
139 }
140
141 public static function error()
142 {
143 return XDB::$mysqli->error;
144 }
145
146 public static function affectedRows()
147 {
148 return XDB::$mysqli->affected_rows;
149 }
150
151 public static function escape($var)
152 {
153 switch (gettype($var)) {
154 case 'boolean':
155 return $var ? 1 : 0;
156
157 case 'integer':
158 case 'double':
159 case 'float':
160 return $var;
161
162 case 'string':
163 return "'".addslashes($var)."'";
164
165 case 'NULL':
166 return 'NULL';
167
168 case 'object':
169 if ($var instanceof PlFlagSet) {
170 return "'" . addslashes($var->flags()) . "'";
171 }
172 case 'array':
173 return "'".addslashes(serialize($var))."'";
174
175 default:
176 die(var_export($var, true).' is not a valid for a database entry');
177 }
178 }
179 }
180
181 class XOrgDBResult
182 {
183
184 private $_res;
185
186 public function __construct($query)
187 {
188 $this->_res = XDB::_query($query);
189 }
190
191 public function free()
192 {
193 if ($this->_res) {
194 $this->_res->free();
195 }
196 unset($this);
197 }
198
199 protected function _fetchRow()
200 {
201 return $this->_res ? $this->_res->fetch_row() : null;
202 }
203
204 protected function _fetchAssoc()
205 {
206 return $this->_res ? $this->_res->fetch_assoc() : null;
207 }
208
209 public function fetchAllRow()
210 {
211 $result = Array();
212 if (!$this->_res) {
213 return $result;
214 }
215 while ($result[] = $this->_res->fetch_row());
216 array_pop($result);
217 $this->free();
218 return $result;
219 }
220
221 public function fetchAllAssoc()
222 {
223 $result = Array();
224 if (!$this->_res) {
225 return $result;
226 }
227 while ($result[] = $this->_res->fetch_assoc());
228 array_pop($result);
229 $this->free();
230 return $result;
231 }
232
233 public function fetchOneAssoc()
234 {
235 $tmp = $this->_fetchAssoc();
236 $this->free();
237 return $tmp;
238 }
239
240 public function fetchOneRow()
241 {
242 $tmp = $this->_fetchRow();
243 $this->free();
244 return $tmp;
245 }
246
247 public function fetchOneCell()
248 {
249 $tmp = $this->_fetchRow();
250 $this->free();
251 return $tmp[0];
252 }
253
254 public function fetchColumn($key = 0)
255 {
256 $res = Array();
257 if (is_numeric($key)) {
258 while($tmp = $this->_fetchRow()) {
259 $res[] = $tmp[$key];
260 }
261 } else {
262 while($tmp = $this->_fetchAssoc()) {
263 $res[] = $tmp[$key];
264 }
265 }
266 $this->free();
267 return $res;
268 }
269
270 public function fetchOneField()
271 {
272 return $this->_res ? $this->_res->fetch_field() : null;
273 }
274
275 public function fetchFields()
276 {
277 $res = array();
278 while ($res[] = $this->fetchOneField());
279 return $res;
280 }
281
282 public function numRows()
283 {
284 return $this->_res ? $this->_res->num_rows : 0;
285 }
286
287 public function fieldCount()
288 {
289 return $this->_res ? $this->_res->field_count : 0;
290 }
291 }
292
293 require_once dirname(__FILE__) . '/pliterator.php';
294
295 class XOrgDBIterator extends XOrgDBResult implements PlIterator
296 {
297 private $_result;
298 private $_pos;
299 private $_total;
300 private $_fpos;
301 private $_fields;
302 private $_mode = MYSQL_ASSOC;
303
304 public function __construct($query, $mode = MYSQL_ASSOC)
305 {
306 parent::__construct($query);
307 $this->_pos = 0;
308 $this->_total = $this->numRows();
309 $this->_fpost = 0;
310 $this->_fields = $this->fieldCount();
311 $this->_mode = $mode;
312 }
313
314 public function next()
315 {
316 $this->_pos ++;
317 if ($this->_pos > $this->_total) {
318 $this->free();
319 unset($this);
320 return null;
321 }
322 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
323 }
324
325 public function first()
326 {
327 return $this->_pos == 1;
328 }
329
330 public function last()
331 {
332 return $this->_pos == $this->_total;
333 }
334
335 public function total()
336 {
337 return $this->_total;
338 }
339
340 public function nextField()
341 {
342 $this->_fpos++;
343 if ($this->_fpos > $this->_fields) {
344 return null;
345 }
346 return $this->fetchOneField();
347 }
348
349 public function firstField()
350 {
351 return $this->_fpos == 1;
352 }
353
354 public function lastField()
355 {
356 return $this->_fpos == $this->_fields;
357 }
358
359 public function totalFields()
360 {
361 return $this->_fields;
362 }
363 }
364
365 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
366 ?>