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 manually set with set(), not by using setExisting()
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 $errors = array();
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 string Error message
138 protected function _error($message)
140 $this->errors
[] = $message;
143 // ###################################################################
145 * This runs through all the errors in the error queue and processes
146 * them all at once. Error builders then get a list of all the errors,
147 * and die-by-hit callbacks stop at the first one
149 * @param string A string param
151 * @return integer Return value
153 private function _processErrorQueue()
155 // we want to explicitly specify silence
156 if (APIError() == 'silent')
161 if (!is_callable(APIError()))
163 trigger_error('No APIError() handler has been set');
166 foreach ($this->errors
AS $e)
168 call_user_func(APIError(), $e);
172 // ###################################################################
174 * Returns the error list. This is because we don't want people mucking
175 * with the error system. It will return an empty array if there are
178 * @return array Array of errors
180 public function checkErrors()
182 if (sizeof($this->errors
) < 1)
187 return $this->errors
;
190 // ###################################################################
192 * Sets a value, sanitizes it, and verifies it
194 * @param string Field name
196 * @param bool Do clean?
197 * @param bool Do verify?
199 public function set($field, $value, $doclean = true, $doverify = true)
201 if (!isset($this->fields
["$field"]))
203 trigger_error('Field "' . $field . '" is not valid');
207 $this->values["$field"] = ($doclean ? BSApp
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
209 $this->setfields["$field"] = $field;
211 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
213 if ($this->fields["$field"][F_VERIFY
] == ':self')
215 $verify = $this->{"verify_$field"}($field);
219 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
222 if ($verify !== true)
224 if ($verify === false)
226 $this->_error(sprintf(_('Validation of "%1$s" failed'), $field));
230 $this->_error($verify);
236 // ###################################################################
238 * Sets the condition to use in the WHERE clause; if not passed, then
239 * it calculates it from the REQ_AUTO field
241 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
243 public function setCondition($condition = '')
245 if (is_array($condition) AND sizeof($condition) > 0)
247 $this->condition
= '';
249 foreach ($condition AS $field)
251 if (!$this->values
["$field"])
253 trigger_error('The specified field "' . $field . '" for the condition could not be found as it is not set');
257 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
259 $this->condition = implode(' AND ', $condbits);
261 else if ($condition != '')
263 $this->condition = $condition;
267 foreach ($this->fields AS $name => $options)
269 if ($options[F_REQ] == REQ_AUTO)
271 if (!$this->values["$name"])
273 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
277 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
281 if ($this->condition
== '')
283 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
288 // ###################################################################
290 * Sets existing data into $values where it's not already present
292 public function setExisting()
302 foreach ($this->objdata
AS $field => $value)
304 if (!isset($this->values
["$field"]))
306 $this->values["$field"] = $value;
313 // ###################################################################
315 * Fetches a record based on the condition
317 * @param bool Run pre_fetch()?
318 * @param bool Run post_fetch()?
320 * @return boolean Whether or not the row was successfully fetched
322 public function fetch($doPre = true, $doPost = true)
324 if ($this->condition
== '')
326 $this->setCondition();
329 // reset the error queue due to any validation errors caused by fetchable fields
330 $this->errors
= array();
332 $this->_runActionMethod('pre_fetch', $doPre);
334 $result = BSApp
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
340 $this->_runActionMethod('post_fetch', $doPost);
342 $this->objdata
= $result;
347 // ###################################################################
349 * Inserts a record in the database
351 * @param bool Run pre_insert()?
352 * @param bool Run post_insert()?
354 public function insert($doPre = true, $doPost = true)
357 $this->_processErrorQueue();
359 $this->_runActionMethod('pre_insert', $doPre);
361 foreach ($this->setfields
AS $field)
364 $values[] = $this->_prepareFieldForSql($field);
367 BSApp
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
369 if (BSApp
::GetType('DbPostgreSql'))
371 foreach ($this->fields
AS $field => $info)
373 if ($info[F_REQ
] == REQ_AUTO
)
380 $this->insertid
= BSApp
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
384 $this->insertid
= BSApp
::GetType('Db')->insertId();
387 $this->_runActionMethod('post_insert', $doPost);
390 // ###################################################################
392 * Updates a record in the database using the data in $vaues
394 * @param bool Run pre_update()?
395 * @param bool Run post_update()?
397 public function update($doPre = true, $doPost = true)
399 if ($this->condition
== '')
401 $this->setCondition();
404 $this->_processErrorQueue();
406 $this->_runActionMethod('pre_update', $doPre);
408 foreach ($this->setfields
AS $field)
410 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
412 $updates = implode(', ', $updates);
414 BSApp
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
416 $this->_runActionMethod('post_update', $doPost);
419 // ###################################################################
423 * @param bool Run pre_remove()?
424 * @param bool Run post_remove()?
426 public function remove($doPre = true, $doPost = true)
428 if ($this->condition
== '')
430 $this->setCondition();
435 $this->_runActionMethod('pre_remove', $doPre);
437 BSApp
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
439 $this->_runActionMethod('post_remove', $doPost);
442 // ###################################################################
444 * Verifies that all required fields are set
446 private function verify()
448 foreach ($this->fields
AS $name => $options)
450 if ($options[F_REQ
] == REQ_YES
)
452 if (!isset($this->values
["$name"]))
454 $this->_error(sprintf(_('The required field "%
1$s" was not set
'), $name));
457 else if ($options[F_REQ] == REQ_SET)
459 $this->{"set_$name"}();
464 // ###################################################################
466 * Runs a pre- or post-action method for database commands
468 * @param string Action to run
469 * @param bool Actually run it?
471 private function _runActionMethod($method, $doRun)
478 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
481 // ###################################################################
483 * Prepares a value for use in a SQL query; it encases and escapes
484 * strings and string-like values
486 * @param string Field name
488 * @return string Prepared value entry
490 private function _prepareFieldForSql($name)
492 $type = $this->fields["$name"][F_TYPE];
494 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
496 return "'" . BSApp::GetType('Db')->escapeString($this->values["$name"]) . "'";
498 else if ($type == TYPE_BOOL
)
500 return ($this->values
["$name"] == true ? "'1'" : "'0'");
502 else if ($type == TYPE_BIN)
504 return "'" . BSApp::GetType('Db
')->escapeBinary($this->values["$name"]) . "'";
508 return $this->values["$name"];
512 // ###################################################################
514 * Verify field: not a zero value
516 protected function verify_nozero($field)
518 if ($this->values
["$field"] == 0)
520 return sprintf(_('The field "%
1$s" cannot be zero
'), $field);
526 // ###################################################################
528 * Verify field: not empty
530 protected function verify_noempty($field)
532 if (empty($this->values["$field"]))
534 return sprintf(_('The field
"%1$s" cannot be empty'), $field);
540 // ###################################################################
542 * Verify field: unique
544 protected function verify_unique($field)
546 $res = BSApp::GetType('Db')->queryFirst("SELECT
$field FROM {$this
->prefix
}{$this
->table
} WHERE
$field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this
->condition
})"));
549 return sprintf(_('The "%
1$s" field must contain a unique value
'), $field);
556 // ###################################################################
558 * Setter and getter method for the API error reporting system. Passing
559 * a name will cause the set, no arguments will cause the get.
561 * @param mixed Method name in callable form
563 * @return mixed Method name in callable form
565 function APIError($new = null)
567 static $caller, $prev;
573 else if ($new !== null)