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 * The table name the API maps objects for
91 protected $table = '___UNDEFINED___';
94 * The database table prefix
97 protected $prefix = '';
100 * Values array: sanitized and verified field values
103 public $values = array();
106 * Fields that were set by the client
109 private $setfields = array();
115 private $condition = '';
118 * The object table row; a fetched row that represents this instance
121 public $record = array();
124 * Insert ID from the insert() command
127 public $insertid = 0;
130 * Error queue that builds up errors
133 private $exception = null;
135 // ###################################################################
137 * Constructor: cannot instantiate class directly
139 public function __construct()
141 BSApp
::RequiredModules(array('Db', 'Input'));
144 // ###################################################################
146 * Adds an error into the error queue that is then hit
148 * @param Exception Error message
150 protected function _error(Exception
$e)
152 if ($this->exception
== null)
154 $this->exception
= new ApiException();
156 $this->exception
->addException($e);
159 // ###################################################################
161 * This simply throws the ApiException if it exists, which inside holds
162 * all of the individual and specific errors
164 private function _processErrorQueue()
166 if ($this->exception
)
168 throw $this->exception
;
172 // ###################################################################
174 * Returns the list of exceptions contained in the ApiException
176 * @return array Array of errors
178 public function isValid()
180 if ($this->exception
== null)
185 return $this->exception
->getExceptions();
188 // ###################################################################
190 * Sets a value, sanitizes it, and verifies it
192 * @param string Field name
194 * @param bool Do clean?
195 * @param bool Do verify?
197 public function set($field, $value, $doclean = true, $doverify = true)
199 if (!isset($this->fields
["$field"]))
201 throw new Exception('Field "' . $field . '" is not valid');
204 $this->values["$field"] = ($doclean ? BSApp
::Registry()->getType('Input')->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
206 $this->setfields["$field"] = $field;
208 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
210 if ($this->fields["$field"][F_VERIFY
] == ':self')
212 $verify = $this->{"verify_$field"}($field);
216 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
219 if ($verify !== true)
221 if ($verify === false)
223 $this->_error(new FieldException(sprintf(_('Validation of "%1$s" failed'), $field)));
227 $this->_error($verify);
233 // ###################################################################
235 * Sets the condition to use in the WHERE clause; if not passed, then
236 * it calculates it from the REQ_AUTO field
238 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
240 public function setCondition($condition = '')
242 if (is_array($condition) AND sizeof($condition) > 0)
244 $this->condition
= '';
246 foreach ($condition AS $field)
248 if (!$this->values
["$field"])
250 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
253 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
255 $this->condition = implode(' AND ', $condbits);
257 else if ($condition != '')
259 $this->condition = $condition;
263 foreach ($this->fields AS $name => $options)
265 if ($options[F_REQ] == REQ_AUTO)
267 if (!$this->values["$name"])
269 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
272 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
276 if ($this->condition
== '')
278 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
283 // ###################################################################
285 * Fetches a record based on the condition
287 * @param bool Run pre_fetch()?
288 * @param bool Run post_fetch()?
290 * @return boolean Whether or not the row was successfully fetched
292 public function fetch($doPre = true, $doPost = true)
294 if ($this->condition
== '')
296 $this->setCondition();
299 // reset the error queue due to any validation errors caused by fetchable fields
300 $this->errors
= null;
302 $this->_runActionMethod('pre_fetch', $doPre);
304 $result = BSApp
::Registry()->getType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
310 $this->_runActionMethod('post_fetch', $doPost);
312 $this->record
= $result;
317 // ###################################################################
319 * Inserts a record in the database
321 * @param bool Run pre_insert()?
322 * @param bool Run post_insert()?
324 public function insert($doPre = true, $doPost = true)
327 $this->_processErrorQueue();
329 $this->_runActionMethod('pre_insert', $doPre);
331 foreach ($this->setfields
AS $field)
334 $values[] = $this->_prepareFieldForSql($field);
337 BSApp
::Registry()->getType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
339 if (BSApp
::Registry()->getType('DbPostgreSql'))
341 foreach ($this->fields
AS $field => $info)
343 if ($info[F_REQ
] == REQ_AUTO
)
350 $this->insertid
= BSApp
::Registry()->getType('Db')->insertId($this->prefix
. $this->table
, $autofield);
354 $this->insertid
= BSApp
::Registry()->getType('Db')->insertId();
357 $this->_runActionMethod('post_insert', $doPost);
360 // ###################################################################
362 * Updates a record in the database using the data in $vaues
364 * @param bool Run pre_update()?
365 * @param bool Run post_update()?
367 public function update($doPre = true, $doPost = true)
369 if ($this->condition
== '')
371 $this->setCondition();
374 $this->_processErrorQueue();
376 $this->_runActionMethod('pre_update', $doPre);
378 foreach ($this->setfields
AS $field)
380 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
382 $updates = implode(', ', $updates);
384 BSApp
::Registry()->getType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
386 $this->_runActionMethod('post_update', $doPost);
389 // ###################################################################
393 * @param bool Run pre_remove()?
394 * @param bool Run post_remove()?
396 public function remove($doPre = true, $doPost = true)
398 if ($this->condition
== '')
400 $this->setCondition();
405 $this->_runActionMethod('pre_remove', $doPre);
407 BSApp
::Registry()->getType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
409 $this->_runActionMethod('post_remove', $doPost);
412 // ###################################################################
414 * Verifies that all required fields are set
416 private function verify()
418 foreach ($this->fields
AS $name => $options)
420 if ($options[F_REQ
] == REQ_YES
)
422 if (!isset($this->values
["$name"]))
424 $this->_error(new FieldException(sprintf(_('The required field "%
1$s" was not set
'), $name), $name));
427 else if ($options[F_REQ] == REQ_SET)
429 $this->{"set_$name"}();
434 // ###################################################################
436 * Runs a pre- or post-action method for database commands
438 * @param string Action to run
439 * @param bool Actually run it?
441 private function _runActionMethod($method, $doRun)
443 if (!$doRun OR !method_exists($this, $method))
451 // ###################################################################
453 * Prepares a value for use in a SQL query; it encases and escapes
454 * strings and string-like values
456 * @param string Field name
458 * @return string Prepared value entry
460 private function _prepareFieldForSql($name)
462 $type = $this->fields["$name"][F_TYPE];
464 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
466 return "'" . BSApp::Registry()->getType('Db')->escapeString($this->values["$name"]) . "'";
468 else if ($type == TYPE_BOOL
)
470 return ($this->values
["$name"] == true ? "'1'" : "'0'");
472 else if ($type == TYPE_BIN)
474 return "'" . BSApp::Registry()->getType('Db
')->escapeBinary($this->values["$name"]) . "'";
478 return $this->values["$name"];
482 // ###################################################################
484 * Verify field: not a zero value
486 protected function verify_nozero($field)
488 if ($this->values
["$field"] == 0)
490 return new FieldException(sprintf(_('The field "%
1$s" cannot be zero
'), $field), $field);
496 // ###################################################################
498 * Verify field: not empty
500 protected function verify_noempty($field)
502 if (empty($this->values["$field"]))
504 return new FieldException(sprintf(_('The field
"%1$s" cannot be empty'), $field), $field);
510 // ###################################################################
512 * Verify field: unique
514 protected function verify_unique($field)
516 $res = BSApp::Registry()->getType('Db')->queryFirst("SELECT
$field FROM {$this
->prefix
}{$this
->table
} WHERE
$field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this
->condition
})"));
519 return new FieldException(sprintf(_('The "%
1$s" field must contain a unique value
'), $field), $field);
529 * This class is an exception container that can be used to store a series
530 * of exceptions that can be thrown as one
533 * @copyright Copyright (c)2002 - 2007, Blue Static
537 class ApiException extends Exception
540 * Array of exceptions
543 private $exceptions = array();
545 // ###################################################################
549 public function __construct()
551 parent::__construct(_('An error occurred
while processing the API data
.'));
554 // ###################################################################
556 * Adds an exception to the collection
558 * @param Exception $e
560 public function addException(Exception $e)
562 $this->exceptions[] = $e;
565 // ###################################################################
567 * Returns an array of all the exceptions in the collection
571 public function getExceptions()
573 return $this->exceptions;
580 * This exception represents a problem with an API field
583 * @copyright Copyright (c)2002 - 2007, Blue Static
588 class FieldException extends Exception
591 * The name of the erroring field
596 // ###################################################################
598 * Constructor: create a new exception
600 public function __construct($error, $field)
602 $this->field = $field;
603 parent::__construct($error);
606 // ###################################################################
608 * Returns the name of the field the exception is for
612 public function getField()