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, remove, 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');
151 // ###################################################################
153 * Adds an error into the error queue that is then hit
155 * @param Exception Error message
157 protected function _error(Exception
$e)
159 if ($this->exception
== null
)
161 $this->exception
= new ApiException();
163 $this->exception
->addException($e);
166 // ###################################################################
168 * This simply throws the ApiException if it exists, which inside holds
169 * all of the individual and specific errors
171 private function _processErrorQueue()
173 if ($this->exception
)
175 throw $this->exception
;
179 // ###################################################################
181 * Sets a value, sanitizes it, and validates it
183 * @param string Field name
185 * @param bool Do clean?
186 * @param bool Do validation?
188 public function set($field, $value, $doclean = true
, $dovalidate = true
)
190 if (!isset($this->fields
["$field"]))
192 throw new Exception('Field "' . $field . '" is not valid');
195 $this->values
["$field"] = ($doclean ? BSApp
::$input->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
197 $this->setfields
["$field"] = $field;
199 if ($dovalidate && method_exists($this, "validate_$field"))
201 $this->{"validate_$field"}($field);
205 // ###################################################################
207 * Sets the condition to use in the WHERE clause; if not passed, then
208 * it calculates it from the REQ_AUTO field
210 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
212 public function setCondition($condition = null
)
214 if (is_array($condition) && sizeof($condition) > 0)
216 $this->condition
= '';
218 foreach ($condition as $field)
220 if (!$this->values
["$field"])
222 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
225 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
227 $this->condition
= implode(' AND ', $condbits);
231 $this->condition
= $condition;
235 foreach ($this->fields
as $name => $options)
237 if ($options[F_REQ
] == REQ_AUTO
)
239 if (!$this->values
["$name"])
241 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
244 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
248 if (!$this->condition
)
250 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
255 // ###################################################################
257 * Fetches a record based on the condition
259 * @param bool Run pre_fetch()?
260 * @param bool Run post_fetch()?
262 * @return boolean Whether or not the row was successfully fetched
264 public function fetch($doPre = true
, $doPost = true
)
266 if (!$this->condition
)
268 $this->setCondition();
271 // reset the error queue due to any validation errors caused by fetchable fields
272 $this->errors
= null
;
274 $this->_runActionMethod('pre_fetch', $doPre);
276 $result = BSApp
::$db->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
282 $this->_runActionMethod('post_fetch', $doPost);
284 $this->record
= $result;
289 // ###################################################################
291 * Inserts a record in the database
293 * @param bool Run pre_insert()?
294 * @param bool Run post_insert()?
296 public function insert($doPre = true
, $doPost = true
)
298 $this->_verifyRequired();
299 $this->_processErrorQueue();
301 $this->_runActionMethod('pre_insert', $doPre);
303 $fields = $values = array();
304 foreach ($this->setfields
as $field)
307 $values[] = $this->_prepareFieldForSql($field);
310 BSApp
::$db->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
312 if (BSApp
::$db instanceof BSDbPostgreSql
)
314 foreach ($this->fields
as $field => $info)
316 if ($info[F_REQ
] == REQ_AUTO
)
323 $this->insertid
= BSApp
::$db->insertId($this->prefix
. $this->table
, $autofield);
327 $this->insertid
= BSApp
::$db->insertId();
330 $this->_runActionMethod('post_insert', $doPost);
333 // ###################################################################
335 * Updates a record in the database using the data in $vaues
337 * @param bool Run pre_update()?
338 * @param bool Run post_update()?
340 public function update($doPre = true
, $doPost = true
)
342 if (!$this->condition
)
344 $this->setCondition();
347 $this->_processErrorQueue();
349 $this->_runActionMethod('pre_update', $doPre);
351 foreach ($this->setfields
as $field)
353 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
355 $updates = implode(', ', $updates);
357 BSApp
::$db->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
359 $this->_runActionMethod('post_update', $doPost);
362 // ###################################################################
366 * @param bool Run pre_remove()?
367 * @param bool Run post_remove()?
369 public function remove($doPre = true
, $doPost = true
)
371 if (!$this->condition
)
373 $this->setCondition();
378 $this->_runActionMethod('pre_remove', $doPre);
380 BSApp
::$db->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
382 $this->_runActionMethod('post_remove', $doPost);
385 // ###################################################################
387 * Verifies that all required fields are set
389 private function _verifyRequired()
391 foreach ($this->fields
as $name => $options)
393 if ($options[F_REQ
] == REQ_YES
)
395 if (!isset($this->values
["$name"]))
397 $this->_error(new FieldException(sprintf(_('The required field "%1$s" was not set'), $name), $name));
400 else if ($options[F_REQ
] == REQ_SET
)
402 $this->{"set_$name"}();
407 // ###################################################################
409 * Runs a pre- or post-action method for database commands
411 * @param string Action to run
412 * @param bool Actually run it?
414 private function _runActionMethod($method, $doRun)
416 if (!$doRun ||
!method_exists($this, $method))
424 // ###################################################################
426 * Prepares a value for use in a SQL query; it encases and escapes
427 * strings and string-like values
429 * @param string Field name
431 * @return string Prepared value entry
433 private function _prepareFieldForSql($name)
435 $type = $this->fields
["$name"][F_TYPE
];
437 if ($type == TYPE_NONE ||
$type == TYPE_STR ||
$type == TYPE_STRUN
)
439 return "'" . BSApp
::$db->escapeString($this->values
["$name"]) . "'";
441 else if ($type == TYPE_BOOL
)
443 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
445 else if ($type == TYPE_BIN
)
447 return "'" . BSApp
::$db->escapeBinary($this->values
["$name"]) . "'";
451 return $this->values
["$name"];
455 // ###################################################################
457 * Verify field: not a zero value
459 protected function _verifyIsNotZero($field)
461 if ($this->values
[$field] == 0)
463 $this->_error(new FieldException(sprintf(_('The field "%1$s" cannot be zero'), $field), $field));
470 // ###################################################################
472 * Verify field: not empty
474 protected function _verifyIsNotEmpty($field)
476 if (empty($this->values
[$field]))
478 $this->_error(new FieldException(sprintf(_('The field "%1$s" cannot be empty'), $field), $field));
485 // ###################################################################
487 * Verify field: unique
489 protected function _verifyIsNotUnique($field)
491 $res = BSApp
::$db->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition
) ?
"" : " AND !({$this->condition})"));
494 $this->_error(new FieldException(sprintf(_('The "%1$s" field must contain a unique value'), $field), $field));
505 * This class is an exception container that can be used to store a series
506 * of exceptions that can be thrown as one
509 * @copyright Copyright (c)2005 - 2008, Blue Static
513 class ApiException
extends Exception
516 * Array of exceptions
519 private $exceptions = array();
521 // ###################################################################
525 public function __construct()
527 parent
::__construct(_('An error occurred while processing the API data.'));
530 // ###################################################################
532 * Adds an exception to the collection
534 * @param Exception $e
536 public function addException(Exception
$e)
538 $this->exceptions
[] = $e;
541 // ###################################################################
543 * Returns an array of all the exceptions in the collection
547 public function getExceptions()
549 return $this->exceptions
;
556 * This exception represents a problem with an API field
559 * @copyright Copyright (c)2005 - 2008, Blue Static
564 class FieldException
extends Exception
567 * The name of the erroring field
572 // ###################################################################
574 * Constructor: create a new exception
576 public function __construct($error, $field)
578 $this->field
= $field;
579 parent
::__construct($error);
582 // ###################################################################
584 * Returns the name of the field the exception is for
588 public function getField()