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 * The callback function for the error handler
84 public static $errorHandler;
87 * Fields: used for verification and sanitization
88 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
91 protected $fields = array();
94 * Values array: sanitized and verified field values
97 public $values = array();
100 * Fields that were manually set with set(), not by using setExisting()
103 private $setfields = array();
109 private $condition = '';
112 * The object table row; a fetched row that represents this instance
115 public $objdata = array();
118 * Insert ID from the insert() command
121 public $insertid = 0;
124 * Error queue that builds up errors
127 private $errors = array();
129 // ###################################################################
131 * Constructor: cannot instantiate class directly
133 public function __construct()
135 BSApp
::RequiredModules(array('Db', 'Input'));
138 // ###################################################################
140 * Adds an error into the error queue that is then hit
142 * @param string Error message
144 protected function _error($message)
146 $this->errors
[] = $message;
149 // ###################################################################
151 * This runs through all the errors in the error queue and processes
152 * them all at once. Error builders then get a list of all the errors,
153 * and die-by-hit callbacks stop at the first one
155 * @param string A string param
157 * @return integer Return value
159 private function _processErrorQueue()
161 // we want to explicitly specify silence
162 if (self
::$errorHandler == 'silent')
167 if (!is_callable(self
::$errorHandler))
169 throw new Exception('No BSApi::$errorHandler handler has been set');
172 foreach ($this->errors
AS $e)
174 call_user_func(BSApi
::$errorHandler, $e);
178 // ###################################################################
180 * Returns the error list. This is because we don't want people mucking
181 * with the error system. It will return an empty array if there are
184 * @return array Array of errors
186 public function checkErrors()
188 if (sizeof($this->errors
) < 1)
193 return $this->errors
;
196 // ###################################################################
198 * Sets a value, sanitizes it, and verifies it
200 * @param string Field name
202 * @param bool Do clean?
203 * @param bool Do verify?
205 public function set($field, $value, $doclean = true, $doverify = true)
207 if (!isset($this->fields
["$field"]))
209 throw new Exception('Field "' . $field . '" is not valid');
213 $this->values["$field"] = ($doclean ? BSApp
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
215 $this->setfields["$field"] = $field;
217 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
219 if ($this->fields["$field"][F_VERIFY
] == ':self')
221 $verify = $this->{"verify_$field"}($field);
225 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
228 if ($verify !== true)
230 if ($verify === false)
232 $this->_error(sprintf(_('Validation of "%1$s" failed'), $field));
236 $this->_error($verify);
242 // ###################################################################
244 * Sets the condition to use in the WHERE clause; if not passed, then
245 * it calculates it from the REQ_AUTO field
247 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
249 public function setCondition($condition = '')
251 if (is_array($condition) AND sizeof($condition) > 0)
253 $this->condition
= '';
255 foreach ($condition AS $field)
257 if (!$this->values
["$field"])
259 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
263 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
265 $this->condition = implode(' AND ', $condbits);
267 else if ($condition != '')
269 $this->condition = $condition;
273 foreach ($this->fields AS $name => $options)
275 if ($options[F_REQ] == REQ_AUTO)
277 if (!$this->values["$name"])
279 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
283 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
287 if ($this->condition
== '')
289 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
294 // ###################################################################
296 * Sets existing data into $values where it's not already present
298 public function setExisting()
308 foreach ($this->objdata
AS $field => $value)
310 if (!isset($this->values
["$field"]))
312 $this->values["$field"] = $value;
319 // ###################################################################
321 * Fetches a record based on the condition
323 * @param bool Run pre_fetch()?
324 * @param bool Run post_fetch()?
326 * @return boolean Whether or not the row was successfully fetched
328 public function fetch($doPre = true, $doPost = true)
330 if ($this->condition
== '')
332 $this->setCondition();
335 // reset the error queue due to any validation errors caused by fetchable fields
336 $this->errors
= array();
338 $this->_runActionMethod('pre_fetch', $doPre);
340 $result = BSApp
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
346 $this->_runActionMethod('post_fetch', $doPost);
348 $this->objdata
= $result;
353 // ###################################################################
355 * Inserts a record in the database
357 * @param bool Run pre_insert()?
358 * @param bool Run post_insert()?
360 public function insert($doPre = true, $doPost = true)
363 $this->_processErrorQueue();
365 $this->_runActionMethod('pre_insert', $doPre);
367 foreach ($this->setfields
AS $field)
370 $values[] = $this->_prepareFieldForSql($field);
373 BSApp
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
375 if (BSApp
::GetType('DbPostgreSql'))
377 foreach ($this->fields
AS $field => $info)
379 if ($info[F_REQ
] == REQ_AUTO
)
386 $this->insertid
= BSApp
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
390 $this->insertid
= BSApp
::GetType('Db')->insertId();
393 $this->_runActionMethod('post_insert', $doPost);
396 // ###################################################################
398 * Updates a record in the database using the data in $vaues
400 * @param bool Run pre_update()?
401 * @param bool Run post_update()?
403 public function update($doPre = true, $doPost = true)
405 if ($this->condition
== '')
407 $this->setCondition();
410 $this->_processErrorQueue();
412 $this->_runActionMethod('pre_update', $doPre);
414 foreach ($this->setfields
AS $field)
416 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
418 $updates = implode(', ', $updates);
420 BSApp
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
422 $this->_runActionMethod('post_update', $doPost);
425 // ###################################################################
429 * @param bool Run pre_remove()?
430 * @param bool Run post_remove()?
432 public function remove($doPre = true, $doPost = true)
434 if ($this->condition
== '')
436 $this->setCondition();
441 $this->_runActionMethod('pre_remove', $doPre);
443 BSApp
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
445 $this->_runActionMethod('post_remove', $doPost);
448 // ###################################################################
450 * Verifies that all required fields are set
452 private function verify()
454 foreach ($this->fields
AS $name => $options)
456 if ($options[F_REQ
] == REQ_YES
)
458 if (!isset($this->values
["$name"]))
460 $this->_error(sprintf(_('The required field "%
1$s" was not set
'), $name));
463 else if ($options[F_REQ] == REQ_SET)
465 $this->{"set_$name"}();
470 // ###################################################################
472 * Runs a pre- or post-action method for database commands
474 * @param string Action to run
475 * @param bool Actually run it?
477 private function _runActionMethod($method, $doRun)
484 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
487 // ###################################################################
489 * Prepares a value for use in a SQL query; it encases and escapes
490 * strings and string-like values
492 * @param string Field name
494 * @return string Prepared value entry
496 private function _prepareFieldForSql($name)
498 $type = $this->fields["$name"][F_TYPE];
500 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
502 return "'" . BSApp::GetType('Db')->escapeString($this->values["$name"]) . "'";
504 else if ($type == TYPE_BOOL
)
506 return ($this->values
["$name"] == true ? "'1'" : "'0'");
508 else if ($type == TYPE_BIN)
510 return "'" . BSApp::GetType('Db
')->escapeBinary($this->values["$name"]) . "'";
514 return $this->values["$name"];
518 // ###################################################################
520 * Verify field: not a zero value
522 protected function verify_nozero($field)
524 if ($this->values
["$field"] == 0)
526 return sprintf(_('The field "%
1$s" cannot be zero
'), $field);
532 // ###################################################################
534 * Verify field: not empty
536 protected function verify_noempty($field)
538 if (empty($this->values["$field"]))
540 return sprintf(_('The field
"%1$s" cannot be empty'), $field);
546 // ###################################################################
548 * Verify field: unique
550 protected function verify_unique($field)
552 $res = BSApp::GetType('Db')->queryFirst("SELECT
$field FROM {$this
->prefix
}{$this
->table
} WHERE
$field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this
->condition
})"));
555 return sprintf(_('The "%
1$s" field must contain a unique value
'), $field);