Update version.php to 3.3.0
[isso.git] / Api.php
diff --git a/Api.php b/Api.php
index 4049f52614a7e6d40a910eb63874d51058448af4..aa6d6ca79b91b5482c13fc60485e44e66b611da6 100644 (file)
--- a/Api.php
+++ b/Api.php
@@ -2,7 +2,7 @@
 /*=====================================================================*\
 || ###################################################################
 || # Blue Static ISSO Framework
-|| # Copyright (c)2002-2007 Blue Static
+|| # Copyright (c)2005-2009 Blue Static
 || #
 || # This program is free software; you can redistribute it and/or modify
 || # it under the terms of the GNU General Public License as published by
 \*=====================================================================*/
 
 /**
-* Abstract Datamanger API (api.php)
-*
-* @package     ISSO
-*/
+ * Abstract Datamanger API (api.php)
+ *
+ * @package    ISSO
+ */
 
 if (!defined('REQ_AUTO'))
 {      
        /**
-       * Yes, required
-       */
+        * Yes, required
+        */
        define('REQ_YES', 1);
        
        /**
-       * No, not required
-       */
+        * No, not required
+        */
        define('REQ_NO', 0);
 
        /**
-       * Auto-increasing value
-       */
+        * Auto-increasing value
+        */
        define('REQ_AUTO', -1);
        
        /**
-       * Set by a cusotm set_*() function
-       */
+        * Set by a cusotm set_*() function
+        */
        define('REQ_SET', 2);
        
        /**
-       * Index for cleaning type
-       */
+        * Index for cleaning type
+        */
        define('F_TYPE', 0);
        
        /**
-       * Index for requirement type
-       */
+        * Index for requirement type
+        */
        define('F_REQ', 1);
 }
 
 /**
-* Abstract API
-*
-* Abstract class that is used as an API base for most common database interaction
-* schemes. Creates a simple structure that holds data and can update, remove, and
-* insert.
-* 
-* Life-cycle of a new object:
-* 1. $o = new SubApi();
-* 2. $o->set('foo', 'abc');
-* 3. $o->set('test', 45);
-* 4. try { $o->insert(); <other actions that depend on the saved record> } catch (ApiException $e) {}
-*
-* @author              Blue Static
-* @copyright   Copyright (c)2002 - 2007, Blue Static
-* @package             ISSO
-* 
-*/
+ * Abstract API
+ *
+ * Abstract class that is used as an API base for most common database interaction
+ * schemes. Creates a simple structure that holds data and can update, delete, and
+ * insert.
+ 
+ * Life-cycle of a new object:
+ * 1. $o = new SubApi();
+ * 2. $o->set('foo', 'abc');
+ * 3. $o->set('test', 45);
+ * 4. try { $o->insert(); <other actions that depend on the saved record> } catch (ApiException $e) {}
+ *
+ * @author             Blue Static
+ * @copyright  Copyright (c)2005 - 2009, Blue Static
+ * @package            ISSO
+ 
+ */
 abstract class BSApi
 {
        /**
-       * Fields: used for verification and sanitization
-       * NAME => array(TYPE, REQUIRED)
-       * @var  array
-       */
+        * Fields: used for verification and sanitization
+        * NAME => array(TYPE, REQUIRED)
+        * @var array
+        */
        protected $fields = array();
        
        /**
@@ -98,56 +98,61 @@ abstract class BSApi
        protected $prefix = '';
        
        /**
-       * Values array: sanitized and validated field values
-       * @var  array
-       */
+        * Values array: sanitized and validated field values
+        * @var array
+        */
        public $values = array();
        
        /**
-       * Fields that were set by the client
-       * @var  array
-       */
+        * Fields that were set by the client
+        * @var array
+        */
        private $setfields = array();
        
        /**
-       * WHERE condition
-       * @var  string
-       */
+        * WHERE condition
+        * @var string
+        */
        protected $condition = '';
        
        /**
-       * The object table row; a fetched row that represents this instance
-       * @var  array
-       */
+        * The object table row; a fetched row that represents this instance
+        * @var array
+        */
        public $record = array();
        
        /**
-       * Insert ID from the insert() command
-       * @var  integer
-       */
+        * Insert ID from the insert() command
+        * @var integer
+        */
        public $insertid = 0;
        
        /**
-       * Error queue that builds up errors
-       * @var  ApiException
-       */
+        * Error queue that builds up errors
+        * @var ApiException
+        */
        private $exception = null;
        
-       // ###################################################################
        /**
-       * Constructor: cannot instantiate class directly
-       */
+        * Constructor
+        */
        public function __construct()
        {
-               BSApp::RequiredModules(array('Db', 'Input'));
+               if (!BSApp::$input instanceof BSInput)
+               {
+                       throw new Exception('BSApp::$input is not an instance of BSInput');
+               }
+               if (!BSApp::$db instanceof BSDb)
+               {
+                       throw new Exception('BSApp::$db is not an instance of BSDb');
+               }
        }
        
-       // ###################################################################
        /**
-       * Adds an error into the error queue that is then hit 
-       *
-       * @param        Exception       Error message
-       */
+        * Adds an error into the error queue that is then hit 
+        *
+        * @param       Exception       Error message
+        */
        protected function _error(Exception $e)
        {
                if ($this->exception == null)
@@ -157,12 +162,11 @@ abstract class BSApi
                $this->exception->addException($e);
        }
        
-       // ###################################################################
        /**
-       * This simply throws the ApiException if it exists, which inside holds
-       * all of the individual and specific errors
-       */
-       private function _processErrorQueue()
+        * This simply throws the ApiException if it exists, which inside holds
+        * all of the individual and specific errors
+        */
+       protected function _processErrorQueue()
        {
                if ($this->exception)
                {
@@ -170,15 +174,59 @@ abstract class BSApi
                }
        }
        
-       // ###################################################################
        /**
-       * Sets a value, sanitizes it, and validates it
-       *
-       * @param        string  Field name
-       * @param        mixed   Value
-       * @param        bool    Do clean?
-       * @param        bool    Do validation?
-       */
+        * Sets an array of data into the API, ignoring things in $exclude. Keys
+        * in the array that don't exist in the API will be ignored.
+        * 
+        * @param       array   A dictionary of field names and values to set
+        * @param       array   Array of keys to exclude
+        */
+       public function setArray(Array $data, $exclude = array())
+       {
+               foreach ($data as $key => $value)
+               {
+                       if (in_array($key, $exclude) || !isset($this->fields[$key]))
+                       {
+                               continue;
+                       }
+                       $this->set($key, $value);
+               }
+       }
+       
+       /**
+        * Resets the API object to an initial state. This will NOT clear the primary (REQ_AUTO)
+        * field.
+        */
+       public function reset()
+       {
+               foreach ($this->fields as $field => $settings)
+               {
+                       if ($settings[F_REQ] == REQ_AUTO)
+                       {
+                               $savename       = $field;
+                               $savevalue      = $this->fetchValue($field);
+                               $savevalue      = ($savevalue ? $savevalue : $this->insertid);
+                               break;
+                       }
+               }
+               
+               $this->setfields        = array();
+               $this->values           = array();
+               $this->condition        = '';
+               $this->insertid         = 0;
+               $this->exception        = null;
+               
+               $this->set($savename, $savevalue);
+       }
+       
+       /**
+        * Sets a value, sanitizes it, and validates it
+        *
+        * @param       string  Field name
+        * @param       mixed   Value
+        * @param       bool    Do clean?
+        * @param       bool    Do validation?
+        */
        public function set($field, $value, $doclean = true, $dovalidate = true)
        {
                if (!isset($this->fields["$field"]))
@@ -186,30 +234,29 @@ abstract class BSApi
                        throw new Exception('Field "' . $field . '" is not valid');
                }
                
-               $this->values["$field"] = ($doclean ? BSApp::Registry()->getType('Input')->clean($value, $this->fields["$field"][F_TYPE]) : $value);
+               $this->values["$field"] = ($doclean ? BSApp::$input->clean($value, $this->fields["$field"][F_TYPE]) : $value);
                
                $this->setfields["$field"] = $field;
                
-               if ($dovalidate AND method_exists($this, "validate_$field"))
+               if ($dovalidate && method_exists($this, "validate_$field"))
                {
                        $this->{"validate_$field"}($field);
                }
        }
        
-       // ###################################################################
        /**
-       * Sets the condition to use in the WHERE clause; if not passed, then
-       * it calculates it from the REQ_AUTO field
-       *
-       * @param        mixed   String with WHERE condition; array of fields to use for WHERE builder
-       */
+        * Sets the condition to use in the WHERE clause; if not passed, then
+        * it calculates it from the REQ_AUTO field
+        *
+        * @param       mixed   String with WHERE condition; array of fields to use for WHERE builder
+        */
        public function setCondition($condition = null)
        {
-               if (is_array($condition) AND sizeof($condition) > 0)
+               if (is_array($condition) && sizeof($condition) > 0)
                {
                        $this->condition = '';
                        
-                       foreach ($condition AS $field)
+                       foreach ($condition as $field)
                        {
                                if (!$this->values["$field"])
                                {
@@ -226,7 +273,7 @@ abstract class BSApi
                }
                else 
                {
-                       foreach ($this->fields AS $name => $options)
+                       foreach ($this->fields as $name => $options)
                        {
                                if ($options[F_REQ] == REQ_AUTO)
                                {
@@ -246,15 +293,14 @@ abstract class BSApi
                }
        }
        
-       // ###################################################################
        /**
-       * Fetches a record based on the condition
-       *
-       * @param        bool    Run pre_fetch()?
-       * @param        bool    Run post_fetch()?
-       *
-       * @return       boolean Whether or not the row was successfully fetched
-       */
+        * Fetches a record based on the condition
+        *
+        * @param       bool    Run pre_fetch()?
+        * @param       bool    Run post_fetch()?
+        *
+        * @return      boolean Whether or not the row was successfully fetched
+        */
        public function fetch($doPre = true, $doPost = true)
        {
                if (!$this->condition)
@@ -267,7 +313,7 @@ abstract class BSApi
                
                $this->_runActionMethod('pre_fetch', $doPre);
                
-               $result = BSApp::Registry()->getType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
+               $result = BSApp::$db->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
                if (!$result)
                {
                        return false;
@@ -280,13 +326,12 @@ abstract class BSApi
                return true;
        }
        
-       // ###################################################################
        /**
-       * Inserts a record in the database
-       *
-       * @param        bool    Run pre_insert()?
-       * @param        bool    Run post_insert()?
-       */
+        * Inserts a record in the database
+        *
+        * @param       bool    Run pre_insert()?
+        * @param       bool    Run post_insert()?
+        */
        public function insert($doPre = true, $doPost = true)
        {
                $this->_verifyRequired();
@@ -295,17 +340,17 @@ abstract class BSApi
                $this->_runActionMethod('pre_insert', $doPre);
                
                $fields = $values = array();
-               foreach ($this->setfields AS $field)
+               foreach ($this->setfields as $field)
                {
                        $fields[] = $field;
                        $values[] = $this->_prepareFieldForSql($field);
                }
                
-               BSApp::Registry()->getType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
+               BSApp::$db->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
                
-               if (BSApp::Registry()->getType('DbPostgreSql'))
+               if (BSApp::$db instanceof BSDbPostgreSql)
                {
-                       foreach ($this->fields AS $field => $info)
+                       foreach ($this->fields as $field => $info)
                        {
                                if ($info[F_REQ] == REQ_AUTO)
                                {
@@ -314,23 +359,22 @@ abstract class BSApi
                                }
                        }
                        
-                       $this->insertid = BSApp::Registry()->getType('Db')->insertId($this->prefix . $this->table, $autofield);
+                       $this->insertid = BSApp::$db->insertId($this->prefix . $this->table, $autofield);
                }
                else
                {
-                       $this->insertid = BSApp::Registry()->getType('Db')->insertId();
+                       $this->insertid = BSApp::$db->insertId();
                }
                
                $this->_runActionMethod('post_insert', $doPost);
        }
        
-       // ###################################################################
        /**
-       * Updates a record in the database using the data in $vaues
-       *
-       * @param        bool    Run pre_update()?
-       * @param        bool    Run post_update()?
-       */
+        * Updates a record in the database using the data in $vaues
+        *
+        * @param       bool    Run pre_update()?
+        * @param       bool    Run post_update()?
+        */
        public function update($doPre = true, $doPost = true)
        {
                if (!$this->condition)
@@ -342,25 +386,24 @@ abstract class BSApi
                
                $this->_runActionMethod('pre_update', $doPre);
                
-               foreach ($this->setfields AS $field)
+               foreach ($this->setfields as $field)
                {
                        $updates[] = "$field = " . $this->_prepareFieldForSql($field);
                }
                $updates = implode(', ', $updates);
                
-               BSApp::Registry()->getType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
+               BSApp::$db->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
                
                $this->_runActionMethod('post_update', $doPost);
        }
        
-       // ###################################################################
        /**
-       * Deletes a record
-       *
-       * @param        bool    Run pre_remove()?
-       * @param        bool    Run post_remove()?
-       */
-       public function remove($doPre = true, $doPost = true)
+        * Deletes a record
+        *
+        * @param       bool    Run pre_delete()?
+        * @param       bool    Run post_delete()?
+        */
+       public function delete($doPre = true, $doPost = true)
        {
                if (!$this->condition)
                {
@@ -369,20 +412,19 @@ abstract class BSApi
                
                $this->fetch();
                
-               $this->_runActionMethod('pre_remove', $doPre);
+               $this->_runActionMethod('pre_delete', $doPre);
                
-               BSApp::Registry()->getType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
+               BSApp::$db->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
                
-               $this->_runActionMethod('post_remove', $doPost);
+               $this->_runActionMethod('post_delete', $doPost);
        }
        
-       // ###################################################################
        /**
-       * Verifies that all required fields are set
-       */
-       private function _verifyRequired()
+        * Verifies that all required fields are set
+        */
+       protected function _verifyRequired()
        {
-               foreach ($this->fields AS $name => $options)
+               foreach ($this->fields as $name => $options)
                {
                        if ($options[F_REQ] == REQ_YES)
                        {
@@ -398,16 +440,15 @@ abstract class BSApi
                }
        }
        
-       // ###################################################################
        /**
-       * Runs a pre- or post-action method for database commands
-       *
-       * @param        string  Action to run
-       * @param        bool    Actually run it?
-       */
-       private function _runActionMethod($method, $doRun)
+        * Runs a pre- or post-action method for database commands
+        *
+        * @param       string  Action to run
+        * @param       bool    Actually run it?
+        */
+       protected function _runActionMethod($method, $doRun)
        {
-               if (!$doRun OR !method_exists($this, $method))
+               if (!$doRun || !method_exists($this, $method))
                {
                        return;
                }
@@ -415,22 +456,21 @@ abstract class BSApi
                $this->$method();
        }
        
-       // ###################################################################
        /**
-       * Prepares a value for use in a SQL query; it encases and escapes
-       * strings and string-like values
-       *
-       * @param        string  Field name
-       *
-       * @return       string  Prepared value entry
-       */
-       private function _prepareFieldForSql($name)
+        * Prepares a value for use in a SQL query; it encases and escapes
+        * strings and string-like values
+        *
+        * @param       string  Field name
+        *
+        * @return      string  Prepared value entry
+        */
+       protected function _prepareFieldForSql($name)
        {
                $type = $this->fields["$name"][F_TYPE];
                
-               if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
+               if ($type == TYPE_NONE || $type == TYPE_STR || $type == TYPE_STRUN)
                {
-                       return "'" . BSApp::Registry()->getType('Db')->escapeString($this->values["$name"]) . "'";
+                       return "'" . BSApp::$db->escapeString($this->values["$name"]) . "'";
                }
                else if ($type == TYPE_BOOL)
                {
@@ -438,7 +478,7 @@ abstract class BSApi
                }
                else if ($type == TYPE_BIN)
                {
-                       return "'" . BSApp::Registry()->getType('Db')->escapeBinary($this->values["$name"]) . "'";
+                       return "'" . BSApp::$db->escapeBinary($this->values["$name"]) . "'";
                }
                else
                {
@@ -446,10 +486,30 @@ abstract class BSApi
                }
        }
        
-       // ###################################################################
        /**
-       * Verify field: not a zero value
-       */
+        * Determines the value of a field from Api->record[], Api->values[] (in that order)
+        *
+        * @param       string  The field ID to determine for
+        *
+        * @return      mixed
+        */
+       public function fetchValue($field)
+       {
+               if ($this->record[$field])
+               {
+                       return $this->record[$field];
+               }
+               else if ($this->values[$field])
+               {
+                       return $this->values[$field];
+               }
+               
+               return null;
+       }
+       
+       /**
+        * Verify field: not a zero value
+        */
        protected function _verifyIsNotZero($field)
        {
                if ($this->values[$field] == 0)
@@ -461,10 +521,9 @@ abstract class BSApi
                return true;
        }
        
-       // ###################################################################
        /**
-       * Verify field: not empty
-       */
+        * Verify field: not empty
+        */
        protected function _verifyIsNotEmpty($field)
        {
                if (empty($this->values[$field]))
@@ -476,13 +535,12 @@ abstract class BSApi
                return true;
        }
        
-       // ###################################################################
        /**
-       * Verify field: unique
-       */
+        * Verify field: unique
+        */
        protected function _verifyIsNotUnique($field)
        {
-               $res = BSApp::Registry()->getType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
+               $res = BSApp::$db->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
                if ($res)
                {
                        $this->_error(new FieldException(sprintf(_('The "%1$s" field must contain a unique value'), $field), $field));
@@ -500,7 +558,7 @@ abstract class BSApi
  * of exceptions that can be thrown as one
  *
  * @author             rsesek
- * @copyright  Copyright (c)2002 - 2007, Blue Static
+ * @copyright  Copyright (c)2005 - 2009, Blue Static
  * @package            ISSO
  *
  */
@@ -512,16 +570,14 @@ class ApiException extends Exception
         */
        private $exceptions = array();
        
-       // ###################################################################
        /**
         * Constructor
         */
        public function __construct()
        {
-               parent::__construct(_('An error occurred while processing the API data.'));
+               parent::__construct(_('An error occurred while processing the API data. Errors: '));
        }
        
-       // ###################################################################
        /**
         * Adds an exception to the collection
         *
@@ -530,9 +586,9 @@ class ApiException extends Exception
        public function addException(Exception $e)
        {
                $this->exceptions[] = $e;
+               $this->message .= ' (' . sizeof($this->exceptions) . ') ' . $e->getMessage();
        }
        
-       // ###################################################################
        /**
         * Returns an array of all the exceptions in the collection
         *
@@ -550,8 +606,7 @@ class ApiException extends Exception
  * This exception represents a problem with an API field
  *
  * @author             rsesek
- * @copyright  Copyright (c)2002 - 2007, Blue Static
- * @version            $Id$
+ * @copyright  Copyright (c)2005 - 2009, Blue Static
  * @package            ISSO
  *
  */
@@ -563,7 +618,6 @@ class FieldException extends Exception
         */
        private $field;
        
-       // ###################################################################
        /**
         * Constructor: create a new exception
         */
@@ -573,7 +627,6 @@ class FieldException extends Exception
                parent::__construct($error);
        }
        
-       // ###################################################################
        /**
         * Returns the name of the field the exception is for
         *