Log SQL errors.
[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 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
80 Platal::page()->kill('Impossible de se connecter à la base de données.');
81 exit;
82 }
83
84 if ($globals->debug & DEBUG_BT) {
85 $explain = array();
86 if (strpos($query, 'FOUND_ROWS()') === false) {
87 $res = XDB::$mysqli->query("EXPLAIN $query");
88 if ($res) {
89 while ($row = $res->fetch_assoc()) {
90 $explain[] = $row;
91 }
92 $res->free();
93 }
94 }
95 PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
96 }
97
98 $res = XDB::$mysqli->query($query);
99
100 if ($globals->debug & DEBUG_BT) {
101 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows,
102 XDB::$mysqli->error,
103 $explain);
104 }
105
106 if ($res === false) {
107 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
108 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
109 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
110 $text = 'Erreur lors de l\'interrogation de la base de données';
111 } else {
112 $text = 'Erreur lors de l\'écriture dans la base de données';
113 }
114 if ($globals->debug) {
115 $text .= '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>';
116 } else {
117 $file = fopen($globals->spoolroot . '/spool/tmp/query_errors', 'a');
118 fwrite($file, '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>'
119 . '<pre>' . XDB::$mysqli->error . '</pre>' . "\n");
120 fclose($file);
121 }
122 Platal::page()->kill($text);
123 exit;
124 }
125 return $res;
126 }
127
128 public static function query()
129 {
130 return new XOrgDBResult(XDB::_prepare(func_get_args()));
131 }
132
133 public static function execute()
134 {
135 global $globals;
136 $args = func_get_args();
137 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
138 return;
139 }
140 return XDB::_query(XDB::_prepare($args));
141 }
142
143 public static function iterator()
144 {
145 return new XOrgDBIterator(XDB::_prepare(func_get_args()));
146 }
147
148 public static function iterRow()
149 {
150 return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
151 }
152
153 public static function insertId()
154 {
155 return XDB::$mysqli->insert_id;
156 }
157
158 public static function errno()
159 {
160 return XDB::$mysqli->errno;
161 }
162
163 public static function error()
164 {
165 return XDB::$mysqli->error;
166 }
167
168 public static function affectedRows()
169 {
170 return XDB::$mysqli->affected_rows;
171 }
172
173 public static function escape($var)
174 {
175 switch (gettype($var)) {
176 case 'boolean':
177 return $var ? 1 : 0;
178
179 case 'integer':
180 case 'double':
181 case 'float':
182 return $var;
183
184 case 'string':
185 return "'".addslashes($var)."'";
186
187 case 'NULL':
188 return 'NULL';
189
190 case 'object':
191 if ($var instanceof PlFlagSet) {
192 return "'" . addslashes($var->flags()) . "'";
193 }
194 case 'array':
195 return "'".addslashes(serialize($var))."'";
196
197 default:
198 die(var_export($var, true).' is not a valid for a database entry');
199 }
200 }
201 }
202
203 class XOrgDBResult
204 {
205
206 private $_res;
207
208 public function __construct($query)
209 {
210 $this->_res = XDB::_query($query);
211 }
212
213 public function free()
214 {
215 if ($this->_res) {
216 $this->_res->free();
217 }
218 unset($this);
219 }
220
221 protected function _fetchRow()
222 {
223 return $this->_res ? $this->_res->fetch_row() : null;
224 }
225
226 protected function _fetchAssoc()
227 {
228 return $this->_res ? $this->_res->fetch_assoc() : null;
229 }
230
231 public function fetchAllRow()
232 {
233 $result = Array();
234 if (!$this->_res) {
235 return $result;
236 }
237 while ($result[] = $this->_res->fetch_row());
238 array_pop($result);
239 $this->free();
240 return $result;
241 }
242
243 public function fetchAllAssoc()
244 {
245 $result = Array();
246 if (!$this->_res) {
247 return $result;
248 }
249 while ($result[] = $this->_res->fetch_assoc());
250 array_pop($result);
251 $this->free();
252 return $result;
253 }
254
255 public function fetchOneAssoc()
256 {
257 $tmp = $this->_fetchAssoc();
258 $this->free();
259 return $tmp;
260 }
261
262 public function fetchOneRow()
263 {
264 $tmp = $this->_fetchRow();
265 $this->free();
266 return $tmp;
267 }
268
269 public function fetchOneCell()
270 {
271 $tmp = $this->_fetchRow();
272 $this->free();
273 return $tmp[0];
274 }
275
276 public function fetchColumn($key = 0)
277 {
278 $res = Array();
279 if (is_numeric($key)) {
280 while($tmp = $this->_fetchRow()) {
281 $res[] = $tmp[$key];
282 }
283 } else {
284 while($tmp = $this->_fetchAssoc()) {
285 $res[] = $tmp[$key];
286 }
287 }
288 $this->free();
289 return $res;
290 }
291
292 public function fetchOneField()
293 {
294 return $this->_res ? $this->_res->fetch_field() : null;
295 }
296
297 public function fetchFields()
298 {
299 $res = array();
300 while ($res[] = $this->fetchOneField());
301 return $res;
302 }
303
304 public function numRows()
305 {
306 return $this->_res ? $this->_res->num_rows : 0;
307 }
308
309 public function fieldCount()
310 {
311 return $this->_res ? $this->_res->field_count : 0;
312 }
313 }
314
315 require_once dirname(__FILE__) . '/pliterator.php';
316
317 class XOrgDBIterator extends XOrgDBResult implements PlIterator
318 {
319 private $_result;
320 private $_pos;
321 private $_total;
322 private $_fpos;
323 private $_fields;
324 private $_mode = MYSQL_ASSOC;
325
326 public function __construct($query, $mode = MYSQL_ASSOC)
327 {
328 parent::__construct($query);
329 $this->_pos = 0;
330 $this->_total = $this->numRows();
331 $this->_fpost = 0;
332 $this->_fields = $this->fieldCount();
333 $this->_mode = $mode;
334 }
335
336 public function next()
337 {
338 $this->_pos ++;
339 if ($this->_pos > $this->_total) {
340 $this->free();
341 unset($this);
342 return null;
343 }
344 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
345 }
346
347 public function first()
348 {
349 return $this->_pos == 1;
350 }
351
352 public function last()
353 {
354 return $this->_pos == $this->_total;
355 }
356
357 public function total()
358 {
359 return $this->_total;
360 }
361
362 public function nextField()
363 {
364 $this->_fpos++;
365 if ($this->_fpos > $this->_fields) {
366 return null;
367 }
368 return $this->fetchOneField();
369 }
370
371 public function firstField()
372 {
373 return $this->_fpos == 1;
374 }
375
376 public function lastField()
377 {
378 return $this->_fpos == $this->_fields;
379 }
380
381 public function totalFields()
382 {
383 return $this->_fields;
384 }
385 }
386
387 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
388 ?>