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