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