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