Merge branch 'mysql4-utf8' of git://github.com/takuya-o/scuttle
[scuttle] / includes / db / mysql4.php
1 <?php
2 /** 
3 *
4 * @package dbal_mysql4
5 * @version $Id: mysql4.php,v 1.4 2006/02/10 01:30:19 scronide Exp $
6 * @copyright (c) 2005 phpBB Group 
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License 
8 *
9 */
10
11 /**
12 * @ignore
13 */
14 if (!defined('SQL_LAYER'))
15 {
16
17 define('SQL_LAYER', 'mysql4');
18
19 /**
20 * @package dbal_mysql4
21 * MySQL4 Database Abstraction Layer
22 * Minimum Requirement is 4.0+/4.1+
23 */
24 class sql_db
25 {
26         var $db_connect_id;
27         var $query_result;
28         var $return_on_error = false;
29         var $transaction = false;
30         var $sql_time = 0;
31         var $num_queries = 0;
32         var $open_queries = array();
33
34         function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false)
35         {
36                 $this->persistency = $persistency;
37                 $this->user = $sqluser;
38                 $this->server = $sqlserver . (($port) ? ':' . $port : '');
39                 $this->dbname = $database;
40
41                 $this->db_connect_id = ($this->persistency) ? @mysql_pconnect($this->server, $this->user, $sqlpassword) : @mysql_connect($this->server, $this->user, $sqlpassword);
42
43                 if ($this->db_connect_id && $this->dbname != '')
44                 {
45                         if (@mysql_select_db($this->dbname))
46                         {
47                                 #Set utf-8
48                                 mysql_query('SET CHARACTER SET utf8', $this->db_connect_id);
49                                 return $this->db_connect_id;
50                         }
51                 }
52
53                 return $this->sql_error('');
54         }
55
56         //
57         // Other base methods
58         //
59         function sql_close()
60         {
61                 if (!$this->db_connect_id)
62                 {
63                         return false;
64                 }
65
66                 if (sizeof($this->open_queries))
67                 {
68                         foreach ($this->open_queries as $i_query_id => $query_id)
69                         {
70                                 @mysql_free_result($query_id);
71                         }
72                 }
73
74                 return @mysql_close($this->db_connect_id);
75         }
76
77         function sql_return_on_error($fail = false)
78         {
79                 $this->return_on_error = $fail;
80         }
81
82         function sql_num_queries()
83         {
84                 return $this->num_queries;
85         }
86
87         function sql_transaction($status = 'begin')
88         {
89                 switch ($status)
90                 {
91                         case 'begin':
92                                 $result = @mysql_query('BEGIN', $this->db_connect_id);
93                                 $this->transaction = true;
94                                 break;
95
96                         case 'commit':
97                                 $result = @mysql_query('COMMIT', $this->db_connect_id);
98                                 $this->transaction = false;
99                                 
100                                 if (!$result)
101                                 {
102                                         @mysql_query('ROLLBACK', $this->db_connect_id);
103                                 }
104                                 break;
105
106                         case 'rollback':
107                                 $result = @mysql_query('ROLLBACK', $this->db_connect_id);
108                                 $this->transaction = false;
109                                 break;
110
111                         default:
112                                 $result = true;
113                 }
114
115                 return $result;
116         }
117
118         // Base query method
119         function sql_query($query = '', $cache_ttl = 0)
120         {
121                 if ($query != '')
122                 {
123                         global $cache;
124
125                         // EXPLAIN only in extra debug mode
126                         if (defined('DEBUG_EXTRA'))
127                         {
128                                 $this->sql_report('start', $query);
129                         }
130
131                         $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
132
133                         if (!$this->query_result)
134                         {
135                                 $this->num_queries++;
136
137                                 if (($this->query_result = @mysql_query($query, $this->db_connect_id)) === false)
138                                 {
139                                         $this->sql_error($query);
140                                 }
141
142                                 if (defined('DEBUG_EXTRA'))
143                                 {
144                                         $this->sql_report('stop', $query);
145                                 }
146
147                                 if ($cache_ttl && method_exists($cache, 'sql_save'))
148                                 {
149                                         $this->open_queries[(int) $this->query_result] = $this->query_result;
150                                         $cache->sql_save($query, $this->query_result, $cache_ttl);
151                                         // mysql_free_result called within sql_save()
152                                 }
153                                 else if (strpos($query, 'SELECT') !== false && $this->query_result)
154                                 {
155                                         $this->open_queries[(int) $this->query_result] = $this->query_result;
156                                 }
157                         }
158                         else if (defined('DEBUG_EXTRA'))
159                         {
160                                 $this->sql_report('fromcache', $query);
161                         }
162                 }
163                 else
164                 {
165                         return false;
166                 }
167
168                 return ($this->query_result) ? $this->query_result : false;
169         }
170
171         function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) { 
172                 if ($query != '') {
173             $this->query_result = false; 
174
175                         // only limit the number of rows if $total is greater than 0
176                         if ($total > 0)
177                         $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total);
178
179                         return $this->sql_query($query, $cache_ttl); 
180                 } else { 
181             return false; 
182                 } 
183         }
184
185         // Idea for this from Ikonboard
186         function sql_build_array($query, $assoc_ary = false)
187         {
188                 if (!is_array($assoc_ary))
189                 {
190                         return false;
191                 }
192
193                 $fields = array();
194                 $values = array();
195                 if ($query == 'INSERT')
196                 {
197                         foreach ($assoc_ary as $key => $var)
198                         {
199                                 $fields[] = $key;
200
201                                 if (is_null($var))
202                                 {
203                                         $values[] = 'NULL';
204                                 }
205                                 elseif (is_string($var))
206                                 {
207                                         $values[] = "'" . $this->sql_escape($var) . "'";
208                                 }
209                                 else
210                                 {
211                                         $values[] = (is_bool($var)) ? intval($var) : $var;
212                                 }
213                         }
214
215                         $query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
216                 }
217                 else if ($query == 'UPDATE' || $query == 'SELECT')
218                 {
219                         $values = array();
220                         foreach ($assoc_ary as $key => $var)
221                         {
222                                 if (is_null($var))
223                                 {
224                                         $values[] = "$key = NULL";
225                                 }
226                                 elseif (is_string($var))
227                                 {
228                                         $values[] = "$key = '" . $this->sql_escape($var) . "'";
229                                 }
230                                 else
231                                 {
232                                         $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
233                                 }
234                         }
235                         $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
236                 }
237
238                 return $query;
239         }
240
241         // Other query methods
242         //
243         // NOTE :: Want to remove _ALL_ reliance on sql_numrows from core code ...
244         //         don't want this here by a middle Milestone
245         function sql_numrows($query_id = false)
246         {
247                 if (!$query_id)
248                 {
249                         $query_id = $this->query_result;
250                 }
251
252                 return ($query_id) ? @mysql_num_rows($query_id) : false;
253         }
254
255         function sql_affectedrows()
256         {
257                 return ($this->db_connect_id) ? @mysql_affected_rows($this->db_connect_id) : false;
258         }
259
260         function sql_fetchrow($query_id = false)
261         {
262                 global $cache;
263
264                 if (!$query_id)
265                 {
266                         $query_id = $this->query_result;
267                 }
268
269                 if (isset($cache->sql_rowset[$query_id]))
270                 {
271                         return $cache->sql_fetchrow($query_id);
272                 }
273
274                 return ($query_id) ? @mysql_fetch_assoc($query_id) : false;
275         }
276
277         function sql_fetchrowset($query_id = false)
278         {
279                 if (!$query_id)
280                 {
281                         $query_id = $this->query_result;
282                 }
283
284                 if ($query_id)
285                 {
286                         unset($this->rowset[$query_id]);
287                         unset($this->row[$query_id]);
288
289                         $result = array();
290                         while ($this->rowset[$query_id] = $this->sql_fetchrow($query_id))
291                         {
292                                 $result[] = $this->rowset[$query_id];
293                         }
294                         return $result;
295                 }
296                 
297                 return false;
298         }
299
300         function sql_fetchfield($field, $rownum = -1, $query_id = false)
301         {
302                 if (!$query_id)
303                 {
304                         $query_id = $this->query_result;
305                 }
306
307                 if ($query_id)
308                 {
309                         if ($rownum > -1)
310                         {
311                                 $result = @mysql_result($query_id, $rownum, $field);
312                         }
313                         else
314                         {
315                                 if (empty($this->row[$query_id]) && empty($this->rowset[$query_id]))
316                                 {
317                                         if ($this->sql_fetchrow($query_id))
318                                         {
319                                                 $result = $this->row[$query_id][$field];
320                                         }
321                                 }
322                                 else
323                                 {
324                                         if ($this->rowset[$query_id])
325                                         {
326                                                 $result = $this->rowset[$query_id][$field];
327                                         }
328                                         elseif ($this->row[$query_id])
329                                         {
330                                                 $result = $this->row[$query_id][$field];
331                                         }
332                                 }
333                         }
334                         return $result;
335                 }
336                 return false;
337         }
338
339         function sql_rowseek($rownum, $query_id = false)
340         {
341                 if (!$query_id)
342                 {
343                         $query_id = $this->query_result;
344                 }
345
346                 return ($query_id) ? @mysql_data_seek($query_id, $rownum) : false;
347         }
348
349         function sql_nextid()
350         {
351                 return ($this->db_connect_id) ? @mysql_insert_id($this->db_connect_id) : false;
352         }
353
354         function sql_freeresult($query_id = false)
355         {
356                 if (!$query_id)
357                 {
358                         $query_id = $this->query_result;
359                 }
360
361                 if (isset($this->open_queries[(int) $query_id]))
362                 {
363                         unset($this->open_queries[(int) $query_id]);
364                         return @mysql_free_result($query_id);
365                 }
366
367                 return false;
368         }
369
370         function sql_escape($msg) {
371                 if (function_exists('mysql_real_escape_string')) {
372                         return @mysql_real_escape_string($msg, $this->db_connect_id);
373                 } else {
374                         return mysql_escape_string($msg);
375                 }               
376         }
377         
378         function sql_error($sql = '')
379         {
380                 if (!$this->return_on_error)
381                 {
382                         $this_page = (isset($_SERVER['PHP_SELF']) && !empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
383                         $this_page .= '&' . ((isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : (isset($_ENV['QUERY_STRING']) ? $_ENV['QUERY_STRING'] : ''));
384
385                         $message = '<u>SQL ERROR</u> [ ' . SQL_LAYER . ' ]<br /><br />' . @mysql_error() . '<br /><br /><u>CALLING PAGE</u><br /><br />'  . htmlspecialchars($this_page) . (($sql != '') ? '<br /><br /><u>SQL</u><br /><br />' . $sql : '') . '<br />';
386
387                         if ($this->transaction)
388                         {
389                                 $this->sql_transaction('rollback');
390                         }
391                         
392                         trigger_error($message, E_USER_ERROR);
393                 }
394
395                 $result = array(
396                         'message'       => @mysql_error(),
397                         'code'          => @mysql_errno()
398                 );
399
400                 return $result;
401         }
402
403         function sql_report($mode, $query = '')
404         {
405                 if (empty($_GET['explain']))
406                 {
407                         return;
408                 }
409
410                 global $db, $cache, $starttime, $phpbb_root_path;
411                 static $curtime, $query_hold, $html_hold;
412                 static $sql_report = '';
413                 static $cache_num_queries = 0;
414
415                 if (!$query && !empty($query_hold))
416                 {
417                         $query = $query_hold;
418                 }
419
420                 switch ($mode)
421                 {
422                         case 'display':
423                                 if (!empty($cache))
424                                 {
425                                         $cache->unload();
426                                 }
427                                 $db->sql_close();
428
429                                 $mtime = explode(' ', microtime());
430                                 $totaltime = $mtime[0] + $mtime[1] - $starttime;
431
432                                 echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8869-1"><meta http-equiv="Content-Style-Type" content="text/css"><link rel="stylesheet" href="' . $phpbb_root_path . 'adm/subSilver.css" type="text/css"><style type="text/css">' . "\n";
433                                 echo 'th { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic3.gif\') }' . "\n";
434                                 echo 'td.cat    { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic1.gif\') }' . "\n";
435                                 echo '</style><title>' . $msg_title . '</title></head><body>';
436                                 echo '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><a href="' . htmlspecialchars(preg_replace('/&explain=([^&]*)/', '', $_SERVER['REQUEST_URI'])) . '"><img src="' . $phpbb_root_path . 'adm/images/header_left.jpg" width="200" height="60" alt="phpBB Logo" title="phpBB Logo" border="0"/></a></td><td width="100%" background="' . $phpbb_root_path . 'adm/images/header_bg.jpg" height="60" align="right" nowrap="nowrap"><span class="maintitle">SQL Report</span> &nbsp; &nbsp; &nbsp;</td></tr></table><br clear="all"/><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td height="40" align="center" valign="middle"><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries} queries" . (($cache_num_queries) ? " + $cache_num_queries " . (($cache_num_queries == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></td></tr><tr><td align="center" nowrap="nowrap">Time spent on MySQL queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></td></tr></table><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td>';
437                                 echo $sql_report;
438                                 echo '</td></tr></table><br /></body></html>';
439                                 exit;
440                                 break;
441
442                         case 'start':
443                                 $query_hold = $query;
444                                 $html_hold = '';
445
446                                 $explain_query = $query;
447                                 if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
448                                 {
449                                         $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
450                                 }
451                                 elseif (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
452                                 {
453                                         $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
454                                 }
455
456                                 if (preg_match('/^SELECT/', $explain_query))
457                                 {
458                                         $html_table = FALSE;
459
460                                         if ($result = mysql_query("EXPLAIN $explain_query", $this->db_connect_id))
461                                         {
462                                                 while ($row = mysql_fetch_assoc($result))
463                                                 {
464                                                         if (!$html_table && sizeof($row))
465                                                         {
466                                                                 $html_table = TRUE;
467                                                                 $html_hold .= '<table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0" align="center"><tr>';
468                                                                 
469                                                                 foreach (array_keys($row) as $val)
470                                                                 {
471                                                                         $html_hold .= '<th nowrap="nowrap">' . (($val) ? ucwords(str_replace('_', ' ', $val)) : '&nbsp;') . '</th>';
472                                                                 }
473                                                                 $html_hold .= '</tr>';
474                                                         }
475                                                         $html_hold .= '<tr>';
476
477                                                         $class = 'row1';
478                                                         foreach (array_values($row) as $val)
479                                                         {
480                                                                 $class = ($class == 'row1') ? 'row2' : 'row1';
481                                                                 $html_hold .= '<td class="' . $class . '">' . (($val) ? $val : '&nbsp;') . '</td>';
482                                                         }
483                                                         $html_hold .= '</tr>';
484                                                 }
485                                         }
486
487                                         if ($html_table)
488                                         {
489                                                 $html_hold .= '</table>';
490                                         }
491                                 }
492
493                                 $curtime = explode(' ', microtime());
494                                 $curtime = $curtime[0] + $curtime[1];
495                                 break;
496
497                         case 'fromcache':
498                                 $endtime = explode(' ', microtime());
499                                 $endtime = $endtime[0] + $endtime[1];
500
501                                 $result = mysql_query($query, $this->db_connect_id);
502                                 while ($void = mysql_fetch_assoc($result))
503                                 {
504                                         // Take the time spent on parsing rows into account
505                                 }
506                                 $splittime = explode(' ', microtime());
507                                 $splittime = $splittime[0] + $splittime[1];
508
509                                 $time_cache = $endtime - $curtime;
510                                 $time_db = $splittime - $endtime;
511                                 $color = ($time_db > $time_cache) ? 'green' : 'red';
512
513                                 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query results obtained from the cache</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table><p align="center">';
514
515                                 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p>';
516
517                                 // Pad the start time to not interfere with page timing
518                                 $starttime += $time_db;
519
520                                 mysql_free_result($result);
521                                 $cache_num_queries++;
522                                 break;
523
524                         case 'stop':
525                                 $endtime = explode(' ', microtime());
526                                 $endtime = $endtime[0] + $endtime[1];
527
528                                 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query #' . $this->num_queries . '</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table> ' . $html_hold . '<p align="center">';
529
530                                 if ($this->query_result)
531                                 {
532                                         if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
533                                         {
534                                                 $sql_report .= "Affected rows: <b>" . $this->sql_affectedrows($this->query_result) . '</b> | ';
535                                         }
536                                         $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $curtime) . 's</b>';
537                                 }
538                                 else
539                                 {
540                                         $error = $this->sql_error();
541                                         $sql_report .= '<b style="color: red">FAILED</b> - MySQL Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
542                                 }
543
544                                 $sql_report .= '</p>';
545
546                                 $this->sql_time += $endtime - $curtime;
547                                 break;
548                 }
549         }
550 } // class sql_db
551
552 } // if ... define
553
554 ?>

Benjamin Mako Hill || Want to submit a patch?