2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 Blue Static
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version 2 of the License.
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
23 * Abstract Datamanger API (api.php)
28 if (!defined('REQ_AUTO'))
41 * Auto-increasing value
43 define('REQ_AUTO', -1);
46 * Set by a cusotm set_*() function
51 * Index for cleaning type
56 * Index for requirement type
64 * Abstract class that is used as an API base for most common database interaction
65 * schemes. Creates a simple structure that holds data and can update, delete, and
68 * Life-cycle of a new object:
69 * 1. $o = new SubApi();
70 * 2. $o->set('foo', 'abc');
71 * 3. $o->set('test', 45);
72 * 4. try { $o->insert(); <other actions that depend on the saved record> } catch (ApiException $e) {}
75 * @copyright Copyright (c)2005 - 2008, Blue Static
82 * Fields: used for verification and sanitization
83 * NAME => array(TYPE, REQUIRED)
86 protected $fields = array();
89 * The table name the API maps objects for
92 protected $table = '___UNDEFINED___';
95 * The database table prefix
98 protected $prefix = '';
101 * Values array: sanitized and validated field values
104 public $values = array();
107 * Fields that were set by the client
110 private $setfields = array();
116 protected $condition = '';
119 * The object table row; a fetched row that represents this instance
122 public $record = array();
125 * Insert ID from the insert() command
128 public $insertid = 0;
131 * Error queue that builds up errors
134 private $exception = null
;
139 public function __construct()
141 if (!BSApp
::$input instanceof BSInput
)
143 throw new Exception('BSApp::$input is not an instance of BSInput');
145 if (!BSApp
::$db instanceof BSDb
)
147 throw new Exception('BSApp::$db is not an instance of BSDb');
152 * Adds an error into the error queue that is then hit
154 * @param Exception Error message
156 protected function _error(Exception
$e)
158 if ($this->exception
== null
)
160 $this->exception
= new ApiException();
162 $this->exception
->addException($e);
166 * This simply throws the ApiException if it exists, which inside holds
167 * all of the individual and specific errors
169 protected function _processErrorQueue()
171 if ($this->exception
)
173 throw $this->exception
;
178 * Sets an array of data into the API, ignoring things in $exclude. Keys
179 * in the array that don't exist in the API will be ignored.
181 * @param array A dictionary of field names and values to set
182 * @param array Array of keys to exclude
184 public function setArray(Array $data, $exclude = array())
186 foreach ($data as $key => $value)
188 if (in_array($key, $exclude) ||
!isset($this->fields
[$key]))
192 $this->set($key, $value);
197 * Sets a value, sanitizes it, and validates it
199 * @param string Field name
201 * @param bool Do clean?
202 * @param bool Do validation?
204 public function set($field, $value, $doclean = true
, $dovalidate = true
)
206 if (!isset($this->fields
["$field"]))
208 throw new Exception('Field "' . $field . '" is not valid');
211 $this->values
["$field"] = ($doclean ? BSApp
::$input->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
213 $this->setfields
["$field"] = $field;
215 if ($dovalidate && method_exists($this, "validate_$field"))
217 $this->{"validate_$field"}($field);
222 * Sets the condition to use in the WHERE clause; if not passed, then
223 * it calculates it from the REQ_AUTO field
225 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
227 public function setCondition($condition = null
)
229 if (is_array($condition) && sizeof($condition) > 0)
231 $this->condition
= '';
233 foreach ($condition as $field)
235 if (!$this->values
["$field"])
237 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
240 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
242 $this->condition
= implode(' AND ', $condbits);
246 $this->condition
= $condition;
250 foreach ($this->fields
as $name => $options)
252 if ($options[F_REQ
] == REQ_AUTO
)
254 if (!$this->values
["$name"])
256 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
259 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
263 if (!$this->condition
)
265 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
271 * Fetches a record based on the condition
273 * @param bool Run pre_fetch()?
274 * @param bool Run post_fetch()?
276 * @return boolean Whether or not the row was successfully fetched
278 public function fetch($doPre = true
, $doPost = true
)
280 if (!$this->condition
)
282 $this->setCondition();
285 // reset the error queue due to any validation errors caused by fetchable fields
286 $this->errors
= null
;
288 $this->_runActionMethod('pre_fetch', $doPre);
290 $result = BSApp
::$db->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
296 $this->_runActionMethod('post_fetch', $doPost);
298 $this->record
= $result;
304 * Inserts a record in the database
306 * @param bool Run pre_insert()?
307 * @param bool Run post_insert()?
309 public function insert($doPre = true
, $doPost = true
)
311 $this->_verifyRequired();
312 $this->_processErrorQueue();
314 $this->_runActionMethod('pre_insert', $doPre);
316 $fields = $values = array();
317 foreach ($this->setfields
as $field)
320 $values[] = $this->_prepareFieldForSql($field);
323 BSApp
::$db->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
325 if (BSApp
::$db instanceof BSDbPostgreSql
)
327 foreach ($this->fields
as $field => $info)
329 if ($info[F_REQ
] == REQ_AUTO
)
336 $this->insertid
= BSApp
::$db->insertId($this->prefix
. $this->table
, $autofield);
340 $this->insertid
= BSApp
::$db->insertId();
343 $this->_runActionMethod('post_insert', $doPost);
347 * Updates a record in the database using the data in $vaues
349 * @param bool Run pre_update()?
350 * @param bool Run post_update()?
352 public function update($doPre = true
, $doPost = true
)
354 if (!$this->condition
)
356 $this->setCondition();
359 $this->_processErrorQueue();
361 $this->_runActionMethod('pre_update', $doPre);
363 foreach ($this->setfields
as $field)
365 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
367 $updates = implode(', ', $updates);
369 BSApp
::$db->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
371 $this->_runActionMethod('post_update', $doPost);
377 * @param bool Run pre_delete()?
378 * @param bool Run post_delete()?
380 public function delete($doPre = true
, $doPost = true
)
382 if (!$this->condition
)
384 $this->setCondition();
389 $this->_runActionMethod('pre_delete', $doPre);
391 BSApp
::$db->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
393 $this->_runActionMethod('post_delete', $doPost);
397 * Verifies that all required fields are set
399 protected function _verifyRequired()
401 foreach ($this->fields
as $name => $options)
403 if ($options[F_REQ
] == REQ_YES
)
405 if (!isset($this->values
["$name"]))
407 $this->_error(new FieldException(sprintf(_('The required field "%1$s" was not set'), $name), $name));
410 else if ($options[F_REQ
] == REQ_SET
)
412 $this->{"set_$name"}();
418 * Runs a pre- or post-action method for database commands
420 * @param string Action to run
421 * @param bool Actually run it?
423 protected function _runActionMethod($method, $doRun)
425 if (!$doRun ||
!method_exists($this, $method))
434 * Prepares a value for use in a SQL query; it encases and escapes
435 * strings and string-like values
437 * @param string Field name
439 * @return string Prepared value entry
441 protected function _prepareFieldForSql($name)
443 $type = $this->fields
["$name"][F_TYPE
];
445 if ($type == TYPE_NONE ||
$type == TYPE_STR ||
$type == TYPE_STRUN
)
447 return "'" . BSApp
::$db->escapeString($this->values
["$name"]) . "'";
449 else if ($type == TYPE_BOOL
)
451 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
453 else if ($type == TYPE_BIN
)
455 return "'" . BSApp
::$db->escapeBinary($this->values
["$name"]) . "'";
459 return $this->values
["$name"];
464 * Verify field: not a zero value
466 protected function _verifyIsNotZero($field)
468 if ($this->values
[$field] == 0)
470 $this->_error(new FieldException(sprintf(_('The field "%1$s" cannot be zero'), $field), $field));
478 * Verify field: not empty
480 protected function _verifyIsNotEmpty($field)
482 if (empty($this->values
[$field]))
484 $this->_error(new FieldException(sprintf(_('The field "%1$s" cannot be empty'), $field), $field));
492 * Verify field: unique
494 protected function _verifyIsNotUnique($field)
496 $res = BSApp
::$db->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition
) ?
"" : " AND !({$this->condition})"));
499 $this->_error(new FieldException(sprintf(_('The "%1$s" field must contain a unique value'), $field), $field));
510 * This class is an exception container that can be used to store a series
511 * of exceptions that can be thrown as one
514 * @copyright Copyright (c)2005 - 2008, Blue Static
518 class ApiException
extends Exception
521 * Array of exceptions
524 private $exceptions = array();
529 public function __construct()
531 parent
::__construct(_('An error occurred while processing the API data. Errors: '));
535 * Adds an exception to the collection
537 * @param Exception $e
539 public function addException(Exception
$e)
541 $this->exceptions
[] = $e;
542 $this->message
.= ' (' . sizeof($this->exceptions
) . ') ' . $e->getMessage();
546 * Returns an array of all the exceptions in the collection
550 public function getExceptions()
552 return $this->exceptions
;
559 * This exception represents a problem with an API field
562 * @copyright Copyright (c)2005 - 2008, Blue Static
566 class FieldException
extends Exception
569 * The name of the erroring field
575 * Constructor: create a new exception
577 public function __construct($error, $field)
579 $this->field
= $field;
580 parent
::__construct($error);
584 * Returns the name of the field the exception is for
588 public function getField()