Happy New Year
[platal.git] / classes / xdb.php
index 3436fc7..5f200d8 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2007 Polytechnique.org                              *
+ *  Copyright (C) 2003-2009 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
 
 class XDB
 {
-    public static $connec = null;
-    var $_trace_data = array();
+    private static $mysqli = null;
+
+    public static function connect()
+    {
+        global $globals;
+        self::$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;
+            }
+        }
+        self::$mysqli->autocommit(true);
+        self::$mysqli->set_charset($globals->dbcharset);
+        return true;
+    }
 
     public static function _prepare($args)
     {
-        $query    = array_map(Array('XDB', '_db_escape'), $args);
+        $query    = array_map(Array('XDB', 'escape'), $args);
         $query[0] = str_replace('{?}', '%s', str_replace('%',   '%%', $args[0]));
         return call_user_func_array('sprintf', $query);
     }
@@ -60,64 +75,179 @@ class XDB
     {
         global $globals;
 
-        if ($globals->debug & 1 && strpos($query, 'FOUND_ROWS()') === false) {
-            $_res = mysqli_query(XDB::$connec, "EXPLAIN $query");
+        if (!self::$mysqli && !self::connect()) {
+            header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
+            Platal::page()->kill('Impossible de se connecter à la base de données.');
+            exit;
+        }
+
+        if ($globals->debug & DEBUG_BT) {
             $explain = array();
-            while ($row = mysqli_fetch_assoc($_res)) {
-                $explain[] = $row;
+            if (strpos($query, 'FOUND_ROWS()') === false) {
+                $res = self::$mysqli->query("EXPLAIN $query");
+                if ($res) {
+                    while ($row = $res->fetch_assoc()) {
+                        $explain[] = $row;
+                    }
+                    $res->free();
+                }
             }
-            $trace_data = array('query' => XDB::_reformatQuery($query), 'explain' => $explain);
-            @mysqli_free_result($_res);
-            $time_start = microtime();
-        } elseif ($globals->debug & 1) {
-            $trace_data = array('query' =>  XDB::_reformatQuery($query), 'explain' => array());
-            $time_start = microtime();
+            PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
         }
 
-        $res = mysqli_query(XDB::$connec, $query);
-        
-        if ($globals->debug & 1) {
-            list($ue, $se) = explode(" ", microtime());
-            list($us, $ss) = explode(" ", $time_start);
-            $time = intval((($ue - $us) + ($se - $ss)) * 1000);            
-            $trace_data['error'] = mysqli_error(XDB::$connec);
-            $trace_data['exectime'] = $time;
-            $trace_data['rows'] = @mysqli_num_rows($res) ? mysqli_num_rows($res) : mysqli_affected_rows(XDB::$connec);
-            $GLOBALS['XDB::trace_data'][] = $trace_data;
-            if (mysqli_errno(XDB::$connec)) {
-                $GLOBALS['XDB::error'] = true;
-            }
+        $res = XDB::$mysqli->query($query);
+
+        if ($globals->debug & DEBUG_BT) {
+            PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : self::$mysqli->affected_rows,
+                                            self::$mysqli->error,
+                                            $explain);
         }
 
+        if ($res === false) {
+            header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
+            if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
+                && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
+                $text = 'Erreur lors de l\'interrogation de la base de données';
+            } else {
+                $text = 'Erreur lors de l\'écriture dans la base de données';
+            }
+            if ($globals->debug) {
+                $text .= '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>';
+            } else {
+                $file = fopen($globals->spoolroot . '/spool/tmp/query_errors', 'a');
+                fwrite($file, '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>'
+                            . '<pre>' . XDB::$mysqli->error . '</pre>' . "\n");
+                fclose($file);
+            }
+            Platal::page()->kill($text);
+            exit;
+        }
         return $res;
     }
 
+    private static function queryv($query)
+    {
+        return new XOrgDBResult(self::_prepare($query));
+    }
+
     public static function query()
     {
-        return new XOrgDBResult(XDB::_prepare(func_get_args()));
+        return self::queryv(func_get_args());
+    }
+
+    public static function format()
+    {
+        return self::_prepare(func_get_args());
     }
 
     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 self::_query(XDB::_prepare($args));
     }
 
     public static function iterator()
     {
-        return new XOrgDBIterator(XDB::_prepare(func_get_args()));
+        return new XOrgDBIterator(self::_prepare(func_get_args()));
     }
 
     public static function iterRow()
     {
-        return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
+        return new XOrgDBIterator(self::_prepare(func_get_args()), MYSQL_NUM);
+    }
+
+    private static function findQuery($params, $default = array())
+    {
+        for ($i = 0 ; $i < count($default) ; ++$i) {
+            $is_query = false;
+            foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
+                if (stripos($params[0], $kwd) !== false) {
+                    $is_query = true;
+                    break;
+                }
+            }
+            if ($is_query) {
+                break;
+            } else {
+                $default[$i] = array_shift($params);
+            }
+        }
+        return array($default, $params);
+    }
+
+    /** Fetch all rows returned by the given query.
+     * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
+     * Optional arguments are given *before* the query.
+     */
+    public static function fetchAllRow()
+    {
+        list($args, $query) = self::findQuery(func_get_args(), array(false, false));
+        return self::queryv($query)->fetchAllRow($args[0], $args[1]);
+    }
+
+    /** Fetch all rows returned by the given query.
+     * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
+     * Optional arguments are given *before* the query.
+     */
+    public static function fetchAllAssoc()
+    {
+        list($args, $query) = self::findQuery(func_get_args(), array(false, false));
+        return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
+    }
+
+    public static function fetchOneCell()
+    {
+        list($args, $query) = self::findQuery(func_get_args());
+        return self::queryv($query)->fetchOneCell();
+    }
+
+    public static function fetchOneRow()
+    {
+        list($args, $query) = self::findQuery(func_get_args());
+        return self::queryv($query)->fetchOneRow();
+    }
+
+    public static function fetchOneAssoc()
+    {
+        list($args, $query) = self::findQuery(func_get_args());
+        return self::queryv($query)->fetchOneAssoc();
+    }
+
+    /** Fetch a column from the result of the given query.
+     * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
+     * Optional arguments are given *before* the query.
+     */
+    public static function fetchColumn()
+    {
+        list($args, $query) = self::findQuery(func_get_args(), array(0));
+        return self::queryv($query)->fetchColumn();
     }
 
     public static function insertId()
     {
-        return mysqli_insert_id(XDB::$connec);
+        return self::$mysqli->insert_id;
     }
 
-    public static function _db_escape($var)
+    public static function errno()
+    {
+        return self::$mysqli->errno;
+    }
+
+    public static function error()
+    {
+        return self::$mysqli->error;
+    }
+
+    public static function affectedRows()
+    {
+        return self::$mysqli->affected_rows;
+    }
+
+    public static function escape($var)
     {
         switch (gettype($var)) {
           case 'boolean':
@@ -135,6 +265,9 @@ class XDB
             return 'NULL';
 
           case 'object':
+            if ($var instanceof PlFlagSet) {
+                return "'" . addslashes($var->flags()) . "'";
+            }
           case 'array':
             return "'".addslashes(serialize($var))."'";
 
@@ -142,80 +275,106 @@ class XDB
             die(var_export($var, true).' is not a valid for a database entry');
         }
     }
-
-    public static function trace_format(&$page, $template = 'skin/common.database-debug.tpl') {
-        $page->assign('trace_data', @$GLOBALS['XDB::trace_data']);
-        $page->assign('db_error', @$GLOBALS['XDB::error']);
-        return $page->fetch($template);
-    }
 }
 
 class XOrgDBResult
 {
 
-    var $_res;
+    private $_res;
 
-    function XOrgDBResult($query)
+    public function __construct($query)
     {
         $this->_res = XDB::_query($query);
     }
 
-    function free()
+    public function free()
     {
-        mysqli_free_result($this->_res);
+        if ($this->_res) {
+            $this->_res->free();
+        }
         unset($this);
     }
 
-    function _fetchRow()
+    protected function _fetchRow()
     {
-        return mysqli_fetch_row($this->_res);
+        return $this->_res ? $this->_res->fetch_row() : null;
     }
 
-    function _fetchAssoc()
+    protected function _fetchAssoc()
     {
-        return mysqli_fetch_assoc($this->_res);
+        return $this->_res ? $this->_res->fetch_assoc() : null;
     }
 
-    function fetchAllRow()
+    public function fetchAllRow($id = false, $keep_array = false)
     {
         $result = Array();
-        while ($result[] = mysqli_fetch_row($this->_res)) { }
-        array_pop($result);
+        if (!$this->_res) {
+            return $result;
+        }
+        while (($data = $this->_res->fetch_row())) {
+            if ($id !== false) {
+                $key = $data[$id];
+                unset($data[$id]);
+                if (!$keep_array && count($data) == 1) {
+                    reset($data);
+                    $result[$key] = current($data);
+                } else {
+                    $result[$key] = $data;
+                }
+            } else {
+                $result[] = $data;
+            }
+        }
         $this->free();
         return $result;
     }
 
-    function fetchAllAssoc()
+    public function fetchAllAssoc($id = false, $keep_array = false)
     {
         $result = Array();
-        while ($result[] = mysqli_fetch_assoc($this->_res)) { }
-        array_pop($result);
+        if (!$this->_res) {
+            return $result;
+        }
+        while (($data = $this->_res->fetch_assoc())) {
+            if ($id !== false) {
+                $key = $data[$id];
+                unset($data[$id]);
+                if (!$keep_array && count($data) == 1) {
+                    reset($data);
+                    $result[$key] = current($data);
+                } else {
+                    $result[$key] = $data;
+                }
+            } else {
+                $result[] = $data;
+            }
+        }
         $this->free();
         return $result;
     }
 
-    function fetchOneAssoc()
+    public function fetchOneAssoc()
     {
         $tmp = $this->_fetchAssoc();
         $this->free();
         return $tmp;
     }
 
-    function fetchOneRow()
+    public function fetchOneRow()
     {
         $tmp = $this->_fetchRow();
         $this->free();
         return $tmp;
     }
 
-    function fetchOneCell()
+    public function fetchOneCell()
     {
         $tmp = $this->_fetchRow();
         $this->free();
         return $tmp[0];
     }
 
-    function fetchColumn($key = 0)
+    public function fetchColumn($key = 0)
     {
         $res = Array();
         if (is_numeric($key)) {
@@ -231,52 +390,99 @@ class XOrgDBResult
         return $res;
     }
 
-    function numRows()
+    public function fetchOneField()
+    {
+        return $this->_res ? $this->_res->fetch_field() : null;
+    }
+
+    public function fetchFields()
+    {
+        $res = array();
+        while ($res[] = $this->fetchOneField());
+        return $res;
+    }
+
+    public function numRows()
     {
-        return mysqli_num_rows($this->_res);
+        return $this->_res ? $this->_res->num_rows : 0;
+    }
+
+    public function fieldCount()
+    {
+        return $this->_res ? $this->_res->field_count : 0;
     }
 }
 
-class XOrgDBIterator
+require_once dirname(__FILE__) . '/pliterator.php';
+
+class XOrgDBIterator extends XOrgDBResult implements PlIterator
 {
     private $_result;
     private $_pos;
     private $_total;
+    private $_fpos;
+    private $_fields;
     private $_mode = MYSQL_ASSOC;
 
-    function __construct($query, $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()
+    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()
+    public function first()
     {
         return $this->_pos == 1;
     }
 
-    function last()
+    public function last()
     {
-        return $this->_last == $this->_total;
+        return $this->_pos == $this->_total;
     }
 
-    function total()
+    public function total()
     {
         return $this->_total;
     }
+
+    public function nextField()
+    {
+        $this->_fpos++;
+        if ($this->_fpos > $this->_fields) {
+            return null;
+        }
+        return $this->fetchOneField();
+    }
+
+    public function firstField()
+    {
+        return $this->_fpos == 1;
+    }
+
+    public function lastField()
+    {
+        return $this->_fpos == $this->_fields;
+    }
+
+    public function totalFields()
+    {
+        return $this->_fields;
+    }
 }
 
 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: