Base layout of the core.
[platal.git] / classes / xdb.php
index 958b3e2..a9cb068 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2006 Polytechnique.org                              *
+ *  Copyright (C) 2003-2008 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
 
 class XDB
 {
-    var $_trace_data = array();
+    private static $mysqli = null;
 
-    // {{{ public static function _prepare
+    public static function connect()
+    {
+        global $globals;
+        XDB::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
+        if ($globals->debug & DEBUG_BT) {
+            $bt = new PlBacktrace('MySQL');
+            if (mysqli_connect_errno()) {
+                $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
+                return false;
+            }
+        }
+        XDB::$mysqli->autocommit(true);
+        XDB::$mysqli->set_charset($globals->dbcharset);
+        return true;
+    }
 
-    public static function _prepare($args) {
-        $query    = array_map(Array('XDB', '_db_escape'), $args);
+    public static function _prepare($args)
+    {
+        $query    = array_map(Array('XDB', 'escape'), $args);
         $query[0] = str_replace('{?}', '%s', str_replace('%',   '%%', $args[0]));
         return call_user_func_array('sprintf', $query);
     }
 
-    // }}}
-    // {{{ public static function _reformatQuery
-
     public static function _reformatQuery($query)
     {
-        $query  = preg_split("/\n\\s*/", $query);
+        $query  = preg_split("/\n\\s*/", trim($query));
         $length = 0;
         foreach ($query as $key=>$line) {
             $local = -2;
-            if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/', $line, $matches)
-                && $matches[1] != 'AND' && $matches[1] != 'OR') {
+            if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
+            && $matches[1] != 'AND' && $matches[1] != 'OR')
+            {
                 $local  = strlen($matches[1]);
                 $line   = $matches[1] . '  ' . $matches[2];
                 $length = max($length, $local);
@@ -58,79 +71,84 @@ class XDB
         return $res;
     }
 
-    // }}}
-    // {{{ public static function _query
-
-    public static function _query($query) {
+    public static function _query($query)
+    {
         global $globals;
 
-        if ($globals->debug & 1) {
-            $_res = mysql_query("EXPLAIN $query");
+        if (!XDB::$mysqli && !XDB::connect()) {
+            return false;
+        }
+
+        if ($globals->debug & DEBUG_BT) {
             $explain = array();
-            while ($row = @mysql_fetch_assoc($_res)) {
-                $explain[] = $row;
+            if (strpos($query, 'FOUND_ROWS()') === false) {
+                $res = XDB::$mysqli->query("EXPLAIN $query");
+                if ($res) {
+                    while ($row = $res->fetch_assoc()) {
+                        $explain[] = $row;
+                    }
+                    $res->free();
+                }
             }
-            $trace_data = array('query' => XDB::_reformatQuery($query), 'explain' => $explain);
-            @mysql_free_result($_res);
+            PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
         }
 
-        $res = mysql_query($query);
+        $res = XDB::$mysqli->query($query);
 
-        if ($globals->debug & 1) {
-            $trace_data['error'] = mysql_error();
-            $GLOBALS['XDB::trace_data'][] = $trace_data;
-            if (mysql_errno()) {
-                $GLOBALS['XDB::error'] = true;
-            }
+        if ($globals->debug & DEBUG_BT) {
+            PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows,
+                                            XDB::$mysqli->error,
+                                            $explain);
         }
-
         return $res;
     }
 
-    // }}}
-    // {{{ public static function query
-
     public static function query()
     {
         return new XOrgDBResult(XDB::_prepare(func_get_args()));
     }
 
-    // }}}
-    // {{{ public static function execute()
-
     public static function execute()
     {
-        return XDB::_query(XDB::_prepare(func_get_args()));
+        global $globals;
+        $args = func_get_args();
+        if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
+            return;
+        }
+        return XDB::_query(XDB::_prepare($args));
     }
 
-    // }}}
-    // {{{ public static function iterator()
-
     public static function iterator()
     {
         return new XOrgDBIterator(XDB::_prepare(func_get_args()));
     }
 
-    // }}}
-    // {{{ public static function iterRow()
-
     public static function iterRow()
     {
         return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
     }
 
-    // }}}
-    // {{{ public static function insertId()
-
     public static function insertId()
     {
-        return mysql_insert_id();
+        return XDB::$mysqli->insert_id;
+    }
+
+    public static function errno()
+    {
+        return XDB::$mysqli->errno;
     }
 
-    // }}}
-    // {{{ public static function _db_escape
+    public static function error()
+    {
+        return XDB::$mysqli->error;
+    }
+
+    public static function affectedRows()
+    {
+        return XDB::$mysqli->affected_rows;
+    }
 
-    public static function _db_escape($var)
+    public static function escape($var)
     {
         switch (gettype($var)) {
           case 'boolean':
@@ -148,6 +166,9 @@ class XDB
             return 'NULL';
 
           case 'object':
+            if ($var instanceof PlFlagSet) {
+                return "'" . addslashes($var->flags()) . "'";
+            }
           case 'array':
             return "'".addslashes(serialize($var))."'";
 
@@ -155,113 +176,82 @@ class XDB
             die(var_export($var, true).' is not a valid for a database entry');
         }
     }
-
-    // }}}
-
-    public static function trace_format(&$page, $template = 'database-debug.tpl') {
-        $page->assign('trace_data', @$GLOBALS['XDB::trace_data']);
-        $page->assign('db_error', @$GLOBALS['XDB::error']);
-        return $page->fetch($template);
-    }
 }
 
 class XOrgDBResult
 {
-    // {{{ properties
 
-    var $_res;
+    private $_res;
 
-    // }}}
-    // {{{ constructor
-
-    function XOrgDBResult($query)
+    public function __construct($query)
     {
         $this->_res = XDB::_query($query);
     }
 
-    // }}}
-    // {{{ destructor
-
-    function free()
+    public function free()
     {
-        mysql_free_result($this->_res);
+        if ($this->_res) {
+            $this->_res->free();
+        }
         unset($this);
     }
 
-    // }}}
-    // {{{ function fetchRow
-
-    function _fetchRow()
+    protected function _fetchRow()
     {
-        return mysql_fetch_row($this->_res);
+        return $this->_res ? $this->_res->fetch_row() : null;
     }
 
-    // }}}
-    // {{{ function fetchAssoc
-
-    function _fetchAssoc()
+    protected function _fetchAssoc()
     {
-        return mysql_fetch_assoc($this->_res);
+        return $this->_res ? $this->_res->fetch_assoc() : null;
     }
 
-    // }}}
-    // {{{ function fetchAllRow
-
-    function fetchAllRow()
+    public function fetchAllRow()
     {
         $result = Array();
-        while ($result[] = mysql_fetch_row($this->_res)) { }
+        if (!$this->_res) {
+            return $result;
+        }
+        while ($result[] = $this->_res->fetch_row());
         array_pop($result);
         $this->free();
         return $result;
     }
 
-    // }}}
-    // {{{ function fetchAllAssoc
-
-    function fetchAllAssoc()
+    public function fetchAllAssoc()
     {
         $result = Array();
-        while ($result[] = mysql_fetch_assoc($this->_res)) { }
+        if (!$this->_res) {
+            return $result;
+        }
+        while ($result[] = $this->_res->fetch_assoc());
         array_pop($result);
         $this->free();
         return $result;
     }
 
-    // }}}
-    // {{{ function fetchOneAssoc()
-
-    function fetchOneAssoc()
+    public function fetchOneAssoc()
     {
         $tmp = $this->_fetchAssoc();
         $this->free();
         return $tmp;
     }
 
-    // }}}
-    // {{{ function fetchOneRow()
-
-    function fetchOneRow()
+    public function fetchOneRow()
     {
         $tmp = $this->_fetchRow();
         $this->free();
         return $tmp;
     }
 
-    // }}}
-    // {{{ function fetchOneCell()
-
-    function fetchOneCell()
+    public function fetchOneCell()
     {
         $tmp = $this->_fetchRow();
         $this->free();
         return $tmp[0];
     }
 
-    // }}}
-    // {{{ function fetchColumn()
-
-    function fetchColumn($key = 0)
+    public function fetchColumn($key = 0)
     {
         $res = Array();
         if (is_numeric($key)) {
@@ -277,77 +267,100 @@ class XOrgDBResult
         return $res;
     }
 
-    // }}}
-    // {{{ function numRows
-
-    function numRows()
+    public function fetchOneField()
     {
-        return mysql_num_rows($this->_res);
+        return $this->_res ? $this->_res->fetch_field() : null;
     }
 
-    // }}}
-}
+    public function fetchFields()
+    {
+        $res = array();
+        while ($res[] = $this->fetchOneField());
+        return $res;
+    }
 
-class XOrgDBIterator
-{
-    // {{{ properties
+    public function numRows()
+    {
+        return $this->_res ? $this->_res->num_rows : 0;
+    }
 
-    var $_result;
-    var $_pos;
-    var $_total;
-    var $_mode = MYSQL_ASSOC;
+    public function fieldCount()
+    {
+        return $this->_res ? $this->_res->field_count : 0;
+    }
+}
 
-    // }}}
-    // {{{ constructor
+require_once dirname(__FILE__) . '/pliterator.php';
 
-    function XOrgDBIterator($query, $mode = MYSQL_ASSOC)
+class XOrgDBIterator extends XOrgDBResult implements PlIterator
+{
+    private $_result;
+    private $_pos;
+    private $_total;
+    private $_fpos;
+    private $_fields;
+    private $_mode = MYSQL_ASSOC;
+
+    public function __construct($query, $mode = MYSQL_ASSOC)
     {
-        $this->_result =& new XOrgDBResult($query);
+        parent::__construct($query);
         $this->_pos    = 0;
-        $this->_total  = $this->_result->numRows();
+        $this->_total  = $this->numRows();
+        $this->_fpost  = 0;
+        $this->_fields = $this->fieldCount();
         $this->_mode   = $mode;
     }
 
-    // }}}
-    // {{{ function next ()
-
-    function next()
+    public function next()
     {
         $this->_pos ++;
         if ($this->_pos > $this->_total) {
-            $this->_result->free();
+            $this->free();
             unset($this);
             return null;
         }
-        return $this->_mode != MYSQL_ASSOC ? $this->_result->_fetchRow() : $this->_result->_fetchAssoc();
+        return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
     }
 
-    // }}}
-    // {{{ function first
-
-    function first()
+    public function first()
     {
         return $this->_pos == 1;
     }
 
-    // }}}
-    // {{{ function last
+    public function last()
+    {
+        return $this->_pos == $this->_total;
+    }
+
+    public function total()
+    {
+        return $this->_total;
+    }
 
-    function last()
+    public function nextField()
     {
-        return $this->_last == $this->_total;
+        $this->_fpos++;
+        if ($this->_fpos > $this->_fields) {
+            return null;
+        }
+        return $this->fetchOneField();
     }
 
-    // }}}
-    // {{{ function total()
+    public function firstField()
+    {
+        return $this->_fpos == 1;
+    }
 
-    function total()
+    public function lastField()
     {
-        return $this->_total;
+        return $this->_fpos == $this->_fields;
     }
 
-    // }}}
+    public function totalFields()
+    {
+        return $this->_fields;
+    }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
 ?>