Merge commit 'origin/core-1.0.0' into core
[platal.git] / classes / xdb.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 self::$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 self::$mysqli->autocommit(true);
38 self::$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 (!self::$mysqli && !self::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 = self::$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 : self::$mysqli->affected_rows,
102 self::$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 private static function queryv($query)
129 {
130 return new XOrgDBResult(self::_prepare($query));
131 }
132
133 public static function query()
134 {
135 return self::queryv(func_get_args());
136 }
137
138 public static function format()
139 {
140 return self::_prepare(func_get_args());
141 }
142
143 // Produce the SQL statement for setting/unsetting a flag
144 public static function changeFlag($fieldname, $flagname, $state)
145 {
146 if ($state) {
147 return XDB::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
148 } else {
149 return XDB::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
150 }
151 }
152
153 // Produce the SQL statement representing an array
154 public static function formatArray(array $array)
155 {
156 return '(' . implode(', ', array_map(array('XDB', 'escape'), $array)) . ')';
157 }
158
159 public static function execute()
160 {
161 global $globals;
162 $args = func_get_args();
163 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
164 return;
165 }
166 return self::_query(XDB::_prepare($args));
167 }
168
169 public static function iterator()
170 {
171 return new XOrgDBIterator(self::_prepare(func_get_args()));
172 }
173
174 public static function iterRow()
175 {
176 return new XOrgDBIterator(self::_prepare(func_get_args()), MYSQL_NUM);
177 }
178
179 private static function findQuery($params, $default = array())
180 {
181 for ($i = 0 ; $i < count($default) ; ++$i) {
182 $is_query = false;
183 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
184 if (stripos($params[0], $kwd) !== false) {
185 $is_query = true;
186 break;
187 }
188 }
189 if ($is_query) {
190 break;
191 } else {
192 $default[$i] = array_shift($params);
193 }
194 }
195 return array($default, $params);
196 }
197
198 /** Fetch all rows returned by the given query.
199 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
200 * Optional arguments are given *before* the query.
201 */
202 public static function fetchAllRow()
203 {
204 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
205 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
206 }
207
208 /** Fetch all rows returned by the given query.
209 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
210 * Optional arguments are given *before* the query.
211 */
212 public static function fetchAllAssoc()
213 {
214 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
215 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
216 }
217
218 public static function fetchOneCell()
219 {
220 list($args, $query) = self::findQuery(func_get_args());
221 return self::queryv($query)->fetchOneCell();
222 }
223
224 public static function fetchOneRow()
225 {
226 list($args, $query) = self::findQuery(func_get_args());
227 return self::queryv($query)->fetchOneRow();
228 }
229
230 public static function fetchOneAssoc()
231 {
232 list($args, $query) = self::findQuery(func_get_args());
233 return self::queryv($query)->fetchOneAssoc();
234 }
235
236 /** Fetch a column from the result of the given query.
237 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
238 * Optional arguments are given *before* the query.
239 */
240 public static function fetchColumn()
241 {
242 list($args, $query) = self::findQuery(func_get_args(), array(0));
243 return self::queryv($query)->fetchColumn();
244 }
245
246 public static function insertId()
247 {
248 return self::$mysqli->insert_id;
249 }
250
251 public static function errno()
252 {
253 return self::$mysqli->errno;
254 }
255
256 public static function error()
257 {
258 return self::$mysqli->error;
259 }
260
261 public static function affectedRows()
262 {
263 return self::$mysqli->affected_rows;
264 }
265
266 public static function escape($var)
267 {
268 switch (gettype($var)) {
269 case 'boolean':
270 return $var ? 1 : 0;
271
272 case 'integer':
273 case 'double':
274 case 'float':
275 return $var;
276
277 case 'string':
278 return "'".addslashes($var)."'";
279
280 case 'NULL':
281 return 'NULL';
282
283 case 'object':
284 if ($var instanceof PlFlagSet) {
285 return "'" . addslashes($var->flags()) . "'";
286 }
287 case 'array':
288 return "'".addslashes(serialize($var))."'";
289
290 default:
291 die(var_export($var, true).' is not a valid for a database entry');
292 }
293 }
294 }
295
296 class XOrgDBResult
297 {
298
299 private $_res;
300
301 public function __construct($query)
302 {
303 $this->_res = XDB::_query($query);
304 }
305
306 public function free()
307 {
308 if ($this->_res) {
309 $this->_res->free();
310 }
311 unset($this);
312 }
313
314 protected function _fetchRow()
315 {
316 return $this->_res ? $this->_res->fetch_row() : null;
317 }
318
319 protected function _fetchAssoc()
320 {
321 return $this->_res ? $this->_res->fetch_assoc() : null;
322 }
323
324 public function fetchAllRow($id = false, $keep_array = false)
325 {
326 $result = Array();
327 if (!$this->_res) {
328 return $result;
329 }
330 while (($data = $this->_res->fetch_row())) {
331 if ($id !== false) {
332 $key = $data[$id];
333 unset($data[$id]);
334 if (!$keep_array && count($data) == 1) {
335 reset($data);
336 $result[$key] = current($data);
337 } else {
338 $result[$key] = $data;
339 }
340 } else {
341 $result[] = $data;
342 }
343 }
344 $this->free();
345 return $result;
346 }
347
348 public function fetchAllAssoc($id = false, $keep_array = false)
349 {
350 $result = Array();
351 if (!$this->_res) {
352 return $result;
353 }
354 while (($data = $this->_res->fetch_assoc())) {
355 if ($id !== false) {
356 $key = $data[$id];
357 unset($data[$id]);
358 if (!$keep_array && count($data) == 1) {
359 reset($data);
360 $result[$key] = current($data);
361 } else {
362 $result[$key] = $data;
363 }
364 } else {
365 $result[] = $data;
366 }
367 }
368 $this->free();
369 return $result;
370 }
371
372 public function fetchOneAssoc()
373 {
374 $tmp = $this->_fetchAssoc();
375 $this->free();
376 return $tmp;
377 }
378
379 public function fetchOneRow()
380 {
381 $tmp = $this->_fetchRow();
382 $this->free();
383 return $tmp;
384 }
385
386 public function fetchOneCell()
387 {
388 $tmp = $this->_fetchRow();
389 $this->free();
390 return $tmp[0];
391 }
392
393 public function fetchColumn($key = 0)
394 {
395 $res = Array();
396 if (is_numeric($key)) {
397 while($tmp = $this->_fetchRow()) {
398 $res[] = $tmp[$key];
399 }
400 } else {
401 while($tmp = $this->_fetchAssoc()) {
402 $res[] = $tmp[$key];
403 }
404 }
405 $this->free();
406 return $res;
407 }
408
409 public function fetchOneField()
410 {
411 return $this->_res ? $this->_res->fetch_field() : null;
412 }
413
414 public function fetchFields()
415 {
416 $res = array();
417 while ($res[] = $this->fetchOneField());
418 return $res;
419 }
420
421 public function numRows()
422 {
423 return $this->_res ? $this->_res->num_rows : 0;
424 }
425
426 public function fieldCount()
427 {
428 return $this->_res ? $this->_res->field_count : 0;
429 }
430 }
431
432 require_once dirname(__FILE__) . '/pliterator.php';
433
434 class XOrgDBIterator extends XOrgDBResult implements PlIterator
435 {
436 private $_result;
437 private $_pos;
438 private $_total;
439 private $_fpos;
440 private $_fields;
441 private $_mode = MYSQL_ASSOC;
442
443 public function __construct($query, $mode = MYSQL_ASSOC)
444 {
445 parent::__construct($query);
446 $this->_pos = 0;
447 $this->_total = $this->numRows();
448 $this->_fpost = 0;
449 $this->_fields = $this->fieldCount();
450 $this->_mode = $mode;
451 }
452
453 public function next()
454 {
455 $this->_pos ++;
456 if ($this->_pos > $this->_total) {
457 $this->free();
458 unset($this);
459 return null;
460 }
461 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
462 }
463
464 public function first()
465 {
466 return $this->_pos == 1;
467 }
468
469 public function last()
470 {
471 return $this->_pos == $this->_total;
472 }
473
474 public function total()
475 {
476 return $this->_total;
477 }
478
479 public function nextField()
480 {
481 $this->_fpos++;
482 if ($this->_fpos > $this->_fields) {
483 return null;
484 }
485 return $this->fetchOneField();
486 }
487
488 public function firstField()
489 {
490 return $this->_fpos == 1;
491 }
492
493 public function lastField()
494 {
495 return $this->_fpos == $this->_fields;
496 }
497
498 public function totalFields()
499 {
500 return $this->_fields;
501 }
502 }
503
504 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
505 ?>