2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright ©2002-[#]year[#] 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 [#]gpl[#] 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 ©2002 - [#]year[#], Blue Static
82 * Fields: used for verification and sanitization
83 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
86 protected $fields = array();
89 * Values array: sanitized and verified field values
92 public $values = array();
95 * Fields that were manually set with set(), not by using setExisting()
98 private $setfields = array();
104 private $condition = '';
107 * The object table row; a fetched row that represents this instance
110 public $objdata = array();
113 * Insert ID from the insert() command
116 public $insertid = 0;
119 * Error queue that builds up errors
122 private $errors = array();
124 // ###################################################################
126 * Constructor: cannot instantiate class directly
128 public function __construct()
130 BSRegister
::RequiredModules(array('Db', 'Input'));
133 // ###################################################################
135 * Adds an error into the error queue that is then hit
137 * @param string Error message
139 protected function _error($message)
141 $this->errors
[] = $message;
144 // ###################################################################
146 * This runs through all the errors in the error queue and processes
147 * them all at once. Error builders then get a list of all the errors,
148 * and die-by-hit callbacks stop at the first one
150 * @param string A string param
152 * @return integer Return value
154 private function _processErrorQueue()
156 // we want to explicitly specify silence
157 if (APIError() == 'silent')
162 if (!is_callable(APIError()))
164 trigger_error('No APIError() handler has been set');
167 foreach ($this->errors
AS $e)
169 call_user_func(APIError(), $e);
173 // ###################################################################
175 * Returns the error list. This is because we don't want people mucking
176 * with the error system. It will return an empty array if there are
179 * @return array Array of errors
181 public function checkErrors()
183 if (sizeof($this->errors
) < 1)
188 return $this->errors
;
191 // ###################################################################
193 * Sets a value, sanitizes it, and verifies it
195 * @param string Field name
197 * @param bool Do clean?
198 * @param bool Do verify?
200 public function set($field, $value, $doclean = true
, $doverify = true
)
202 if (!isset($this->fields
["$field"]))
204 trigger_error('Field "' . $field . '" is not valid');
208 $this->values
["$field"] = ($doclean ? BSRegister
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
210 $this->setfields
["$field"] = $field;
212 if (isset($this->fields
["$field"][F_VERIFY
]) AND $doverify)
214 if ($this->fields
["$field"][F_VERIFY
] == ':self')
216 $verify = $this->{"verify_$field"}($field);
220 $verify = $this->{$this->fields
["$field"][F_VERIFY
]}($field);
223 if ($verify !== true
)
225 if ($verify === false
)
227 $this->_error(sprintf(_('Validation of "%1$s" failed'), $field));
231 $this->_error($verify);
237 // ###################################################################
239 * Sets the condition to use in the WHERE clause; if not passed, then
240 * it calculates it from the REQ_AUTO field
242 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
244 public function setCondition($condition = '')
246 if (is_array($condition) AND sizeof($condition) > 0)
248 $this->condition
= '';
250 foreach ($condition AS $field)
252 if (!$this->values
["$field"])
254 trigger_error('The specified field "' . $field . '" for the condition could not be found as it is not set');
258 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
260 $this->condition
= implode(' AND ', $condbits);
262 else if ($condition != '')
264 $this->condition
= $condition;
268 foreach ($this->fields
AS $name => $options)
270 if ($options[F_REQ
] == REQ_AUTO
)
272 if (!$this->values
["$name"])
274 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
278 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
282 if ($this->condition
== '')
284 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
289 // ###################################################################
291 * Sets existing data into $values where it's not already present
293 public function setExisting()
303 foreach ($this->objdata
AS $field => $value)
305 if (!isset($this->values
["$field"]))
307 $this->values
["$field"] = $value;
314 // ###################################################################
316 * Fetches a record based on the condition
318 * @param bool Run pre_fetch()?
319 * @param bool Run post_fetch()?
321 * @return boolean Whether or not the row was successfully fetched
323 public function fetch($doPre = true
, $doPost = true
)
325 if ($this->condition
== '')
327 $this->setCondition();
330 // reset the error queue due to any validation errors caused by fetchable fields
331 $this->errors
= array();
333 $this->_runActionMethod('pre_fetch', $doPre);
335 $result = BSRegister
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
341 $this->_runActionMethod('post_fetch', $doPost);
343 $this->objdata
= $result;
347 foreach ($this->objdata
AS $key => $value)
349 if (!isset($this->values
["$key"]))
351 $this->values
["$key"] = $value;
359 // ###################################################################
361 * Inserts a record in the database
363 * @param bool Run pre_insert()?
364 * @param bool Run post_insert()?
366 public function insert($doPre = true
, $doPost = true
)
369 $this->_processErrorQueue();
371 $this->_runActionMethod('pre_insert', $doPre);
373 foreach ($this->setfields
AS $field)
376 $values[] = $this->_prepareFieldForSql($field);
379 BSRegister
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
381 if (BSRegister
::GetType('DbPostgreSql'))
383 foreach ($this->fields
AS $field => $info)
385 if ($info[F_REQ
] == REQ_AUTO
)
392 $this->insertid
= BSRegister
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
396 $this->insertid
= BSRegister
::GetType('Db')->insertId();
399 $this->_runActionMethod('post_insert', $doPost);
402 // ###################################################################
404 * Updates a record in the database using the data in $vaues
406 * @param bool Run pre_update()?
407 * @param bool Run post_update()?
409 public function update($doPre = true
, $doPost = true
)
411 if ($this->condition
== '')
413 $this->setCondition();
416 $this->_processErrorQueue();
418 $this->_runActionMethod('pre_update', $doPre);
420 foreach ($this->setfields
AS $field)
422 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
424 $updates = implode(', ', $updates);
426 BSRegister
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
428 $this->_runActionMethod('post_update', $doPost);
431 // ###################################################################
435 * @param bool Run pre_remove()?
436 * @param bool Run post_remove()?
438 public function remove($doPre = true
, $doPost = true
)
440 if ($this->condition
== '')
442 $this->setCondition();
447 $this->_runActionMethod('pre_remove', $doPre);
449 BSRegister
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
451 $this->_runActionMethod('post_remove', $doPost);
454 // ###################################################################
456 * Verifies that all required fields are set
458 private function verify()
460 foreach ($this->fields
AS $name => $options)
462 if ($options[F_REQ
] == REQ_YES
)
464 if (!isset($this->values
["$name"]))
466 $this->_error(sprintf(_('The required field "%1$s" was not set'), $name));
469 else if ($options[F_REQ
] == REQ_SET
)
471 $this->{"set_$name"}();
476 // ###################################################################
478 * Runs a pre- or post-action method for database commands
480 * @param string Action to run
481 * @param bool Actually run it?
483 private function _runActionMethod($method, $doRun)
490 $actmethod = (method_exists($this, $method) ?
$this->$method() : '');
493 // ###################################################################
495 * Prepares a value for use in a SQL query; it encases and escapes
496 * strings and string-like values
498 * @param string Field name
500 * @return string Prepared value entry
502 private function _prepareFieldForSql($name)
504 $type = $this->fields
["$name"][F_TYPE
];
506 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
508 return "'" . BSRegister
::GetType('Db')->escapeString($this->values
["$name"]) . "'";
510 else if ($type == TYPE_BOOL
)
512 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
514 else if ($type == TYPE_BIN
)
516 return "'" . BSRegister
::GetType('Db')->escapeBinary($this->values
["$name"]) . "'";
520 return $this->values
["$name"];
524 // ###################################################################
526 * Verify field: not a zero value
528 protected function verify_nozero($field)
530 if ($this->values
["$field"] == 0)
532 return sprintf(_('The field "%1$s" cannot be zero'), $field);
538 // ###################################################################
540 * Verify field: not empty
542 protected function verify_noempty($field)
544 if (empty($this->values
["$field"]))
546 return sprintf(_('The field "%1$s" cannot be empty'), $field);
552 // ###################################################################
554 * Verify field: unique
556 /*protected function verify_unique($field)
558 $res = BSRegister::GetType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
562 return sprintf(_('The "%1$s" field must contain a unique value'), $field);
569 // ###################################################################
571 * Setter and getter method for the API error reporting system. Passing
572 * a name will cause the set, no arguments will cause the get.
574 * @param mixed Method name in callable form
576 * @return mixed Method name in callable form
578 function APIError($new = null
)
580 static $caller, $prev;
586 else if ($new !== null
)
595 /*=====================================================================*\
596 || ###################################################################
599 || ###################################################################
600 \*=====================================================================*/