Use XDB in all CLI scripts and remove all mysql_ calls
[platal.git] / classes / xdb.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 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 (mysqli_connect_errno() && $globals->debug & 1) {
31 $GLOBALS['XDB::trace_data'][] = array('query' => 'MySQLI connection', 'explain' => array(),
32 'error' => mysqli_connect_error(), 'exectime' => 0, 'rows' => 0);
33 $GLOBALS['XDB::error'] = true;
34 return false;
35 }
36 XDB::$mysqli->autocommit(true);
37 XDB::$mysqli->set_charset($globals->dbcharset);
38 return true;
39 }
40
41 public static function _prepare($args)
42 {
43 $query = array_map(Array('XDB', '_db_escape'), $args);
44 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
45 return call_user_func_array('sprintf', $query);
46 }
47
48 public static function _reformatQuery($query)
49 {
50 $query = preg_split("/\n\\s*/", trim($query));
51 $length = 0;
52 foreach ($query as $key=>$line) {
53 $local = -2;
54 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
55 && $matches[1] != 'AND' && $matches[1] != 'OR')
56 {
57 $local = strlen($matches[1]);
58 $line = $matches[1] . ' ' . $matches[2];
59 $length = max($length, $local);
60 }
61 $query[$key] = array($line, $local);
62 }
63 $res = '';
64 foreach ($query as $array) {
65 list($line, $local) = $array;
66 $local = max(0, $length - $local);
67 $res .= str_repeat(' ', $local) . $line . "\n";
68 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
69 }
70 return $res;
71 }
72
73 public static function _query($query)
74 {
75 global $globals;
76
77 if (!XDB::$mysqli && !XDB::connect()) {
78 return false;
79 }
80
81 if ($globals->debug & 1) {
82 $explain = array();
83 if (strpos($query, 'FOUND_ROWS()') === false) {
84 $res = XDB::$mysqli->query("EXPLAIN $query");
85 if ($res) {
86 while ($row = $res->fetch_assoc()) {
87 $explain[] = $row;
88 }
89 $res->free();
90 }
91 }
92 $trace_data = array('query' => XDB::_reformatQuery($query), 'explain' => $explain);
93 $time_start = microtime();
94 }
95
96 $res = XDB::$mysqli->query($query);
97
98 if ($globals->debug & 1) {
99 list($ue, $se) = explode(" ", microtime());
100 list($us, $ss) = explode(" ", $time_start);
101 $time = intval((($ue - $us) + ($se - $ss)) * 1000);
102 $trace_data['error'] = XDB::$mysqli->error;
103 $trace_data['errno'] = XDB::$mysqli->errno;
104 $trace_data['exectime'] = $time;
105 $trace_data['rows'] = @$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows;
106 $GLOBALS['XDB::trace_data'][] = $trace_data;
107 if (XDB::$mysqli->errno) {
108 $GLOBALS['XDB::error'] = true;
109 }
110 }
111 return $res;
112 }
113
114 public static function query()
115 {
116 return new XOrgDBResult(XDB::_prepare(func_get_args()));
117 }
118
119 public static function execute()
120 {
121 return XDB::_query(XDB::_prepare(func_get_args()));
122 }
123
124 public static function iterator()
125 {
126 return new XOrgDBIterator(XDB::_prepare(func_get_args()));
127 }
128
129 public static function iterRow()
130 {
131 return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
132 }
133
134 public static function insertId()
135 {
136 return XDB::$mysqli->insert_id;
137 }
138
139 public static function errno()
140 {
141 global $globals;
142 if ($globals->debug & 1) {
143 $count = count($GLOBALS['XDB::trace_data']);
144 if (!$count) {
145 return 0;
146 }
147 return $GLOBALS['XDB::trace_data'][$count - 1]['errno'];
148 }
149 return XDB::$mysqli->errno;
150 }
151
152 public static function error()
153 {
154 global $globals;
155 if ($globals->debug & 1) {
156 $count = count($GLOBALS['XDB::trace_data']);
157 if (!$count) {
158 return null;
159 }
160 return $GLOBALS['XDB::trace_data'][$count - 1]['error'];
161 }
162 return XDB::$mysqli->error;
163 }
164
165 public static function affectedRows()
166 {
167 return XDB::$mysqli->affected_rows;
168 }
169
170 public static function _db_escape($var)
171 {
172 switch (gettype($var)) {
173 case 'boolean':
174 return $var ? 1 : 0;
175
176 case 'integer':
177 case 'double':
178 case 'float':
179 return $var;
180
181 case 'string':
182 return "'".addslashes($var)."'";
183
184 case 'NULL':
185 return 'NULL';
186
187 case 'object':
188 case 'array':
189 return "'".addslashes(serialize($var))."'";
190
191 default:
192 die(var_export($var, true).' is not a valid for a database entry');
193 }
194 }
195
196 public static function trace_format(&$page, $template = 'skin/common.database-debug.tpl') {
197 $page->assign('trace_data', @$GLOBALS['XDB::trace_data']);
198 $page->assign('db_error', @$GLOBALS['XDB::error']);
199 return $page->fetch($template);
200 }
201 }
202
203 class XOrgDBResult
204 {
205
206 private $_res;
207
208 function XOrgDBResult($query)
209 {
210 $this->_res = XDB::_query($query);
211 }
212
213 function free()
214 {
215 $this->_res->free();
216 unset($this);
217 }
218
219 function _fetchRow()
220 {
221 return $this->_res->fetch_row();
222 }
223
224 function _fetchAssoc()
225 {
226 return $this->_res->fetch_assoc();
227 }
228
229 function fetchAllRow()
230 {
231 $result = Array();
232 while ($result[] = $this->_res->fetch_row());
233 array_pop($result);
234 $this->free();
235 return $result;
236 }
237
238 function fetchAllAssoc()
239 {
240 $result = Array();
241 while ($result[] = $this->_res->fetch_assoc());
242 array_pop($result);
243 $this->free();
244 return $result;
245 }
246
247 function fetchOneAssoc()
248 {
249 $tmp = $this->_fetchAssoc();
250 $this->free();
251 return $tmp;
252 }
253
254 function fetchOneRow()
255 {
256 $tmp = $this->_fetchRow();
257 $this->free();
258 return $tmp;
259 }
260
261 function fetchOneCell()
262 {
263 $tmp = $this->_fetchRow();
264 $this->free();
265 return $tmp[0];
266 }
267
268 function fetchColumn($key = 0)
269 {
270 $res = Array();
271 if (is_numeric($key)) {
272 while($tmp = $this->_fetchRow()) {
273 $res[] = $tmp[$key];
274 }
275 } else {
276 while($tmp = $this->_fetchAssoc()) {
277 $res[] = $tmp[$key];
278 }
279 }
280 $this->free();
281 return $res;
282 }
283
284 function fetchOneField()
285 {
286 return $this->_res->fetch_field();
287 }
288
289 function fetchFields()
290 {
291 $res = array();
292 while ($res[] = $this->fetchOneField());
293 return $res;
294 }
295
296 function numRows()
297 {
298 return $this->_res->num_rows;
299 }
300
301 function fieldCount()
302 {
303 return $this->_res->field_count;
304 }
305 }
306
307 class XOrgDBIterator
308 {
309 private $_result;
310 private $_pos;
311 private $_total;
312 private $_fpos;
313 private $_fields;
314 private $_mode = MYSQL_ASSOC;
315
316 function __construct($query, $mode = MYSQL_ASSOC)
317 {
318 $this->_result = new XOrgDBResult($query);
319 $this->_pos = 0;
320 $this->_total = $this->_result->numRows();
321 $this->_fpost = 0;
322 $this->_fields = $this->_result->fieldCount();
323 $this->_mode = $mode;
324 }
325
326 function next()
327 {
328 $this->_pos ++;
329 if ($this->_pos > $this->_total) {
330 $this->_result->free();
331 unset($this);
332 return null;
333 }
334 return $this->_mode != MYSQL_ASSOC ? $this->_result->_fetchRow() : $this->_result->_fetchAssoc();
335 }
336
337 function first()
338 {
339 return $this->_pos == 1;
340 }
341
342 function last()
343 {
344 return $this->_pos == $this->_total;
345 }
346
347 function total()
348 {
349 return $this->_total;
350 }
351
352 function nextField()
353 {
354 $this->_fpos++;
355 if ($this->_fpos > $this->_fields) {
356 return null;
357 }
358 return $this->_result->fetchOneField();
359 }
360
361 function firstField()
362 {
363 return $this->_fpos == 1;
364 }
365
366 function lastField()
367 {
368 return $this->_fpos == $this->_fields;
369 }
370
371 function totalFields()
372 {
373 return $this->_fields;
374 }
375 }
376
377 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
378 ?>