Factorizes the content type / content cache headers, and improves caching of static...
[platal.git] / classes / xdb.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
a7f778a5 3 * Copyright (C) 2003-2009 Polytechnique.org *
0337d704 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
08cce2ff 22class XDB
0337d704 23{
32d9ae72 24 private static $mysqli = null;
25
821744e0 26 public static function connect()
32d9ae72 27 {
821744e0 28 global $globals;
e4f6c7d0 29 self::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
81e9c63f 30 if ($globals->debug & DEBUG_BT) {
d3f26be9 31 $bt = new PlBacktrace('MySQL');
32 if (mysqli_connect_errno()) {
33 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
34 return false;
35 }
32d9ae72 36 }
e4f6c7d0
FB
37 self::$mysqli->autocommit(true);
38 self::$mysqli->set_charset($globals->dbcharset);
32d9ae72 39 return true;
40 }
f1ca33de 41
ed3f4d3e 42 public static function _prepare($args)
43 {
f62bd784 44 $query = array_map(Array('XDB', 'escape'), $args);
0337d704 45 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
46 return call_user_func_array('sprintf', $query);
47 }
13a25546 48
6995a9b9 49 public static function _reformatQuery($query)
7c571120 50 {
a4f89886 51 $query = preg_split("/\n\\s*/", trim($query));
7c571120 52 $length = 0;
d3c52d30 53 foreach ($query as $key=>$line) {
54 $local = -2;
a14159bf 55 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
85d3b330 56 && $matches[1] != 'AND' && $matches[1] != 'OR')
57 {
d3c52d30 58 $local = strlen($matches[1]);
59 $line = $matches[1] . ' ' . $matches[2];
60 $length = max($length, $local);
7c571120 61 }
d3c52d30 62 $query[$key] = array($line, $local);
7c571120 63 }
64 $res = '';
d3c52d30 65 foreach ($query as $array) {
66 list($line, $local) = $array;
9630c649 67 $local = max(0, $length - $local);
7c571120 68 $res .= str_repeat(' ', $local) . $line . "\n";
69 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
70 }
71 return $res;
72 }
73
ed3f4d3e 74 public static function _query($query)
75 {
f1ca33de 76 global $globals;
77
e4f6c7d0 78 if (!self::$mysqli && !self::connect()) {
12ccfec7 79 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
80 Platal::page()->kill('Impossible de se connecter à la base de données.');
81 exit;
821744e0 82 }
83
81e9c63f 84 if ($globals->debug & DEBUG_BT) {
f1ca33de 85 $explain = array();
5fb22b39 86 if (strpos($query, 'FOUND_ROWS()') === false) {
e4f6c7d0 87 $res = self::$mysqli->query("EXPLAIN $query");
32d9ae72 88 if ($res) {
89 while ($row = $res->fetch_assoc()) {
5fb22b39 90 $explain[] = $row;
91 }
32d9ae72 92 $res->free();
5fb22b39 93 }
f1ca33de 94 }
d3f26be9 95 PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
f1ca33de 96 }
97
32d9ae72 98 $res = XDB::$mysqli->query($query);
0381e170 99
81e9c63f 100 if ($globals->debug & DEBUG_BT) {
e4f6c7d0
FB
101 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : self::$mysqli->affected_rows,
102 self::$mysqli->error,
d3f26be9 103 $explain);
f1ca33de 104 }
084a60da
FB
105
106 if ($res === false) {
12ccfec7 107 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
108 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
109 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
7f10bc61 110 $text = 'Erreur lors de l\'interrogation de la base de données';
084a60da 111 } else {
7f10bc61 112 $text = 'Erreur lors de l\'écriture dans la base de données';
084a60da 113 }
7f10bc61
FB
114 if ($globals->debug) {
115 $text .= '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>';
f8eaef22
FB
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);
7f10bc61
FB
121 }
122 Platal::page()->kill($text);
084a60da
FB
123 exit;
124 }
f1ca33de 125 return $res;
126 }
127
e4f6c7d0
FB
128 private static function queryv($query)
129 {
130 return new XOrgDBResult(self::_prepare($query));
131 }
132
6995a9b9 133 public static function query()
0337d704 134 {
e4f6c7d0 135 return self::queryv(func_get_args());
0337d704 136 }
137
20973bf8
FB
138 public static function format()
139 {
e4f6c7d0 140 return self::_prepare(func_get_args());
20973bf8
FB
141 }
142
0ef5bd4b
FB
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
6995a9b9 159 public static function execute()
f1ca33de 160 {
fe556813
FB
161 global $globals;
162 $args = func_get_args();
163 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
164 return;
165 }
e4f6c7d0 166 return self::_query(XDB::_prepare($args));
0337d704 167 }
13a25546 168
6995a9b9 169 public static function iterator()
0337d704 170 {
e4f6c7d0 171 return new XOrgDBIterator(self::_prepare(func_get_args()));
0337d704 172 }
13a25546 173
6995a9b9 174 public static function iterRow()
0337d704 175 {
e4f6c7d0
FB
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();
0337d704 244 }
13a25546 245
6995a9b9 246 public static function insertId()
13a25546 247 {
e4f6c7d0 248 return self::$mysqli->insert_id;
13a25546 249 }
250
0380bf85 251 public static function errno()
252 {
e4f6c7d0 253 return self::$mysqli->errno;
0380bf85 254 }
255
256 public static function error()
834fd0f6 257 {
e4f6c7d0 258 return self::$mysqli->error;
0380bf85 259 }
260
261 public static function affectedRows()
262 {
e4f6c7d0 263 return self::$mysqli->affected_rows;
0380bf85 264 }
265
f62bd784 266 public static function escape($var)
0337d704 267 {
268 switch (gettype($var)) {
13a25546 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':
113f6de8 284 if ($var instanceof PlFlagSet) {
04c1b2eb
FB
285 return "'" . addslashes($var->flags()) . "'";
286 }
13a25546 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');
0337d704 292 }
293 }
0337d704 294}
295
0337d704 296class XOrgDBResult
297{
0337d704 298
32d9ae72 299 private $_res;
0337d704 300
0381e170 301 public function __construct($query)
0337d704 302 {
755abda6 303 $this->_res = XDB::_query($query);
0337d704 304 }
305
0381e170 306 public function free()
0337d704 307 {
0381e170 308 if ($this->_res) {
309 $this->_res->free();
310 }
0337d704 311 unset($this);
312 }
313
0381e170 314 protected function _fetchRow()
0337d704 315 {
0381e170 316 return $this->_res ? $this->_res->fetch_row() : null;
0337d704 317 }
318
0381e170 319 protected function _fetchAssoc()
0337d704 320 {
0381e170 321 return $this->_res ? $this->_res->fetch_assoc() : null;
0337d704 322 }
323
e4f6c7d0 324 public function fetchAllRow($id = false, $keep_array = false)
0337d704 325 {
326 $result = Array();
0381e170 327 if (!$this->_res) {
328 return $result;
329 }
e4f6c7d0
FB
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 }
0337d704 344 $this->free();
345 return $result;
346 }
347
e4f6c7d0 348 public function fetchAllAssoc($id = false, $keep_array = false)
0337d704 349 {
350 $result = Array();
0381e170 351 if (!$this->_res) {
352 return $result;
353 }
e4f6c7d0
FB
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 }
0337d704 368 $this->free();
369 return $result;
370 }
371
0381e170 372 public function fetchOneAssoc()
0337d704 373 {
374 $tmp = $this->_fetchAssoc();
375 $this->free();
376 return $tmp;
377 }
378
0381e170 379 public function fetchOneRow()
0337d704 380 {
381 $tmp = $this->_fetchRow();
382 $this->free();
383 return $tmp;
384 }
385
0381e170 386 public function fetchOneCell()
0337d704 387 {
388 $tmp = $this->_fetchRow();
389 $this->free();
390 return $tmp[0];
391 }
392
0381e170 393 public function fetchColumn($key = 0)
0337d704 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
0381e170 409 public function fetchOneField()
0380bf85 410 {
0381e170 411 return $this->_res ? $this->_res->fetch_field() : null;
0380bf85 412 }
413
0381e170 414 public function fetchFields()
0380bf85 415 {
416 $res = array();
417 while ($res[] = $this->fetchOneField());
418 return $res;
419 }
420
0381e170 421 public function numRows()
0337d704 422 {
0381e170 423 return $this->_res ? $this->_res->num_rows : 0;
0337d704 424 }
0380bf85 425
0381e170 426 public function fieldCount()
0380bf85 427 {
0381e170 428 return $this->_res ? $this->_res->field_count : 0;
0380bf85 429 }
0337d704 430}
431
2b1ee50b 432require_once dirname(__FILE__) . '/pliterator.php';
433
0381e170 434class XOrgDBIterator extends XOrgDBResult implements PlIterator
0337d704 435{
85d3b330 436 private $_result;
437 private $_pos;
438 private $_total;
0380bf85 439 private $_fpos;
440 private $_fields;
85d3b330 441 private $_mode = MYSQL_ASSOC;
0337d704 442
0381e170 443 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 444 {
0381e170 445 parent::__construct($query);
0337d704 446 $this->_pos = 0;
0381e170 447 $this->_total = $this->numRows();
0380bf85 448 $this->_fpost = 0;
0381e170 449 $this->_fields = $this->fieldCount();
0337d704 450 $this->_mode = $mode;
451 }
452
0381e170 453 public function next()
0337d704 454 {
455 $this->_pos ++;
456 if ($this->_pos > $this->_total) {
0381e170 457 $this->free();
0337d704 458 unset($this);
459 return null;
460 }
0381e170 461 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
0337d704 462 }
463
0381e170 464 public function first()
0337d704 465 {
466 return $this->_pos == 1;
467 }
468
0381e170 469 public function last()
0337d704 470 {
0380bf85 471 return $this->_pos == $this->_total;
0337d704 472 }
473
0381e170 474 public function total()
0337d704 475 {
476 return $this->_total;
477 }
0380bf85 478
0381e170 479 public function nextField()
0380bf85 480 {
481 $this->_fpos++;
482 if ($this->_fpos > $this->_fields) {
483 return null;
484 }
0381e170 485 return $this->fetchOneField();
0380bf85 486 }
487
0381e170 488 public function firstField()
0380bf85 489 {
490 return $this->_fpos == 1;
491 }
492
0381e170 493 public function lastField()
0380bf85 494 {
495 return $this->_fpos == $this->_fields;
496 }
497
0381e170 498 public function totalFields()
0380bf85 499 {
500 return $this->_fields;
501 }
0337d704 502}
503
a7de4ef7 504// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 505?>