2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2002-2007 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
61 * Index for verification type
63 define('F_VERIFY', 2);
69 * Abstract class that is used as an API base for most common database interaction
70 * schemes. Creates a simple structure that holds data and can update, remove, and
74 * @copyright Copyright (c)2002 - 2007, Blue Static
81 * Fields: used for verification and sanitization
82 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
85 protected $fields = array();
88 * Values array: sanitized and verified field values
91 public $values = array();
94 * Fields that were set by the client
97 private $setfields = array();
103 private $condition = '';
106 * The object table row; a fetched row that represents this instance
109 public $objdata = array();
112 * Insert ID from the insert() command
115 public $insertid = 0;
118 * Error queue that builds up errors
121 private $exception = null
;
123 // ###################################################################
125 * Constructor: cannot instantiate class directly
127 public function __construct()
129 BSApp
::RequiredModules(array('Db', 'Input'));
132 // ###################################################################
134 * Adds an error into the error queue that is then hit
136 * @param Exception Error message
138 protected function _error(Exception
$e)
140 if ($this->exception
== null
)
142 $this->exception
= new ApiException();
144 $this->exception
->addException($e);
147 // ###################################################################
149 * This simply throws the ApiException if it exists, which inside holds
150 * all of the individual and specific errors
152 private function _processErrorQueue()
154 if ($this->exception
)
156 throw $this->exception
;
160 // ###################################################################
162 * Returns the list of exceptions contained in the ApiException
164 * @return array Array of errors
166 public function isValid()
168 if ($this->exception
== null
)
173 return $this->exception
->getExceptions();
176 // ###################################################################
178 * Sets a value, sanitizes it, and verifies it
180 * @param string Field name
182 * @param bool Do clean?
183 * @param bool Do verify?
185 public function set($field, $value, $doclean = true
, $doverify = true
)
187 if (!isset($this->fields
["$field"]))
189 throw new Exception('Field "' . $field . '" is not valid');
192 $this->values
["$field"] = ($doclean ? BSApp
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
194 $this->setfields
["$field"] = $field;
196 if (isset($this->fields
["$field"][F_VERIFY
]) AND $doverify)
198 if ($this->fields
["$field"][F_VERIFY
] == ':self')
200 $verify = $this->{"verify_$field"}($field);
204 $verify = $this->{$this->fields
["$field"][F_VERIFY
]}($field);
207 if ($verify !== true
)
209 if ($verify === false
)
211 $this->_error(new Exception(sprintf(_('Validation of "%1$s" failed'), $field)));
215 $this->_error($verify);
221 // ###################################################################
223 * Sets the condition to use in the WHERE clause; if not passed, then
224 * it calculates it from the REQ_AUTO field
226 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
228 public function setCondition($condition = '')
230 if (is_array($condition) AND sizeof($condition) > 0)
232 $this->condition
= '';
234 foreach ($condition AS $field)
236 if (!$this->values
["$field"])
238 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
241 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
243 $this->condition
= implode(' AND ', $condbits);
245 else if ($condition != '')
247 $this->condition
= $condition;
251 foreach ($this->fields
AS $name => $options)
253 if ($options[F_REQ
] == REQ_AUTO
)
255 if (!$this->values
["$name"])
257 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
260 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
264 if ($this->condition
== '')
266 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
271 // ###################################################################
273 * Fetches a record based on the condition
275 * @param bool Run pre_fetch()?
276 * @param bool Run post_fetch()?
278 * @return boolean Whether or not the row was successfully fetched
280 public function fetch($doPre = true
, $doPost = true
)
282 if ($this->condition
== '')
284 $this->setCondition();
287 // reset the error queue due to any validation errors caused by fetchable fields
288 $this->errors
= null
;
290 $this->_runActionMethod('pre_fetch', $doPre);
292 $result = BSApp
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
298 $this->_runActionMethod('post_fetch', $doPost);
300 $this->objdata
= $result;
305 // ###################################################################
307 * Inserts a record in the database
309 * @param bool Run pre_insert()?
310 * @param bool Run post_insert()?
312 public function insert($doPre = true
, $doPost = true
)
315 $this->_processErrorQueue();
317 $this->_runActionMethod('pre_insert', $doPre);
319 foreach ($this->setfields
AS $field)
322 $values[] = $this->_prepareFieldForSql($field);
325 BSApp
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
327 if (BSApp
::GetType('DbPostgreSql'))
329 foreach ($this->fields
AS $field => $info)
331 if ($info[F_REQ
] == REQ_AUTO
)
338 $this->insertid
= BSApp
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
342 $this->insertid
= BSApp
::GetType('Db')->insertId();
345 $this->_runActionMethod('post_insert', $doPost);
348 // ###################################################################
350 * Updates a record in the database using the data in $vaues
352 * @param bool Run pre_update()?
353 * @param bool Run post_update()?
355 public function update($doPre = true
, $doPost = true
)
357 if ($this->condition
== '')
359 $this->setCondition();
362 $this->_processErrorQueue();
364 $this->_runActionMethod('pre_update', $doPre);
366 foreach ($this->setfields
AS $field)
368 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
370 $updates = implode(', ', $updates);
372 BSApp
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
374 $this->_runActionMethod('post_update', $doPost);
377 // ###################################################################
381 * @param bool Run pre_remove()?
382 * @param bool Run post_remove()?
384 public function remove($doPre = true
, $doPost = true
)
386 if ($this->condition
== '')
388 $this->setCondition();
393 $this->_runActionMethod('pre_remove', $doPre);
395 BSApp
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
397 $this->_runActionMethod('post_remove', $doPost);
400 // ###################################################################
402 * Verifies that all required fields are set
404 private function verify()
406 foreach ($this->fields
AS $name => $options)
408 if ($options[F_REQ
] == REQ_YES
)
410 if (!isset($this->values
["$name"]))
412 $this->_error(new Exception(sprintf(_('The required field "%1$s" was not set'), $name), $name));
415 else if ($options[F_REQ
] == REQ_SET
)
417 $this->{"set_$name"}();
422 // ###################################################################
424 * Runs a pre- or post-action method for database commands
426 * @param string Action to run
427 * @param bool Actually run it?
429 private function _runActionMethod($method, $doRun)
436 $actmethod = (method_exists($this, $method) ?
$this->$method() : '');
439 // ###################################################################
441 * Prepares a value for use in a SQL query; it encases and escapes
442 * strings and string-like values
444 * @param string Field name
446 * @return string Prepared value entry
448 private function _prepareFieldForSql($name)
450 $type = $this->fields
["$name"][F_TYPE
];
452 if ($type == TYPE_NONE
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
454 return "'" . BSApp
::GetType('Db')->escapeString($this->values
["$name"]) . "'";
456 else if ($type == TYPE_BOOL
)
458 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
460 else if ($type == TYPE_BIN
)
462 return "'" . BSApp
::GetType('Db')->escapeBinary($this->values
["$name"]) . "'";
466 return $this->values
["$name"];
470 // ###################################################################
472 * Verify field: not a zero value
474 protected function verify_nozero($field)
476 if ($this->values
["$field"] == 0)
478 return new Exception(sprintf(_('The field "%1$s" cannot be zero'), $field), $field);
484 // ###################################################################
486 * Verify field: not empty
488 protected function verify_noempty($field)
490 if (empty($this->values
["$field"]))
492 return new Exception(sprintf(_('The field "%1$s" cannot be empty'), $field), $field);
498 // ###################################################################
500 * Verify field: unique
502 protected function verify_unique($field)
504 $res = BSApp
::GetType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition
) ?
"" : " AND !({$this->condition})"));
507 return new Exception(sprintf(_('The "%1$s" field must contain a unique value'), $field), $field);
517 * This class is an exception container that can be used to store a series
518 * of exceptions that can be thrown as one
521 * @copyright Copyright (c)2002 - 2007, Blue Static
525 class ApiException
extends Exception
528 * Array of exceptions
531 private $exceptions = array();
533 // ###################################################################
537 public function __construct()
539 parent
::__construct(_('An error occurred while processing the API data.'));
542 // ###################################################################
544 * Adds an exception to the collection
546 * @param Exception $e
548 public function addException(Exception
$e)
550 $this->exceptions
[] = $e;
553 // ###################################################################
555 * Returns an array of all the exceptions in the collection
559 public function getExceptions()
561 return $this->exceptions
;