2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework [#]issoversion[#]
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);
68 define('F_RELATION', 3);
71 * Relation index for file name, relative to ISSO->apppath
73 define('F_RELATION_FILE', 0);
76 * Relation index for class name
78 define('F_RELATION_CLASS', 1);
81 * Relation index for field-link alternate name
83 define('F_RELATION_ALTFIELD', 2);
89 * Abstract class that is used as an API base for most common database interaction
90 * schemes. Creates a simple structure that holds data and can update, remove, and
94 * @copyright Copyright ©2002 - [#]year[#], Blue Static
102 * Fields: used for verification and sanitization
103 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
106 protected $fields = array();
109 * Values array: sanitized and verified field values
112 public $values = array();
115 * Fields that were manually set with set(), not by using setExisting()
118 private $setfields = array();
121 * An array of all of the processed relations on an object
124 public $relations = array();
130 private $condition = '';
133 * The object table row; a fetched row that represents this instance
136 public $objdata = array();
139 * Insert ID from the insert() command
142 public $insertid = 0;
145 * Pre- and post-action method stoppers
148 public $norunners = array();
151 * The relations to execute on
154 public $dorelations = array('fetch');
157 * Error list that has been generated
160 private $errors = array();
162 // ###################################################################
164 * Constructor: cannot instantiate class directly
166 public function __construct()
168 BSRegister
::RequiredModules(array('Db', 'Input'));
171 // ###################################################################
173 * Constructs an error for the error handler to receive
175 * @param string Error message
177 protected function error($message)
179 $this->errors
[] = $message;
181 // we want to explicitly specify silence
182 if (APIError() == 'silent')
187 if (!is_callable(APIError()))
189 trigger_error('No APIError() handler has been set');
192 call_user_func(APIError(), $message);
195 // ###################################################################
197 * Returns the error list. This is because we don't want people mucking
198 * with the error system. It will return an empty array if there are
201 * @return array Array of errors
203 public function checkErrors()
205 if (sizeof($this->errors
) < 1)
210 return $this->errors
;
213 // ###################################################################
215 * Sets a value, sanitizes it, and verifies it
217 * @param string Field name
219 * @param bool Do clean?
220 * @param bool Do verify?
222 public function set($field, $value, $doclean = true, $doverify = true)
224 if (!isset($this->fields
["$field"]))
226 trigger_error('Field `' . $field . '` is not valid');
230 $this->values["$field"] = ($doclean ? BSRegister
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
232 $this->setfields["$field"] = $field;
234 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
236 if ($this->fields["$field"][F_VERIFY
] == ':self')
238 $verify = $this->{"verify_$field"}($field);
242 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
245 if ($verify !== true)
247 if ($verify === false)
249 $this->error(sprintf(_('Validation of "%1$s" failed'), $field));
253 $this->error($verify);
259 // ###################################################################
261 * Sets the condition to use in the WHERE clause; if not passed, then
262 * it calculates it from the REQ_AUTO field
264 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
266 public function setCondition($condition = '')
268 if (is_array($condition) AND sizeof($condition) > 0)
270 $this->condition
= '';
272 foreach ($condition AS $field)
274 if (!$this->values
["$field"])
276 trigger_error('The specified field "' . $field . '" for the condition could not be found as it is not set');
280 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
282 $this->condition = implode(' AND ', $condbits);
284 else if ($condition != '')
286 $this->condition = $condition;
290 foreach ($this->fields AS $name => $options)
292 if ($options[F_REQ] == REQ_AUTO)
294 if (!$this->values["$name"])
296 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
300 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
304 if ($this->condition
== '')
306 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
311 // ###################################################################
313 * Sets existing data into $values where it's not already present
315 public function setExisting()
325 foreach ($this->objdata
AS $field => $value)
327 if (!isset($this->values
["$field"]))
329 $this->values["$field"] = $value;
336 // ###################################################################
338 * Fetches a record based on the condition
340 * @param bool Populate $this->values[] with data, along with $this->objdata[] ?
342 public function fetch($populate = false)
344 if ($this->condition
== '')
346 trigger_error('Condition is empty: cannot fetch');
349 $this->_runActionMethod('pre_fetch');
351 $result = BSRegister
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
354 $this->error(_('No records were returned'));
358 $this->_runActionMethod('post_fetch');
360 $this->objdata
= $result;
364 foreach ($this->objdata
AS $key => $value)
366 if (!isset($this->values
["$key"]))
368 $this->values["$key"] = $value;
373 $this->callRelations('fetch');
376 // ###################################################################
378 * Inserts a record in the database
380 public function insert()
384 $this->_runActionMethod('pre_insert');
386 foreach ($this->setfields
AS $field)
389 $values[] = $this->_prepareFieldForSql($field);
392 BSRegister
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
394 if (BSRegister
::GetType('DbPostgreSql'))
396 foreach ($this->fields
AS $field => $info)
398 if ($info[F_REQ
] == REQ_AUTO
)
405 $this->insertid
= BSRegister
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
409 $this->insertid
= BSRegister
::GetType('Db')->insertId();
412 $this->_runActionMethod('post_insert');
415 // ###################################################################
417 * Updates a record in the database using the data in $vaues
419 public function update()
421 if ($this->condition
== '')
423 trigger_error('Condition is empty: cannot update');
426 $this->_runActionMethod('pre_update');
428 foreach ($this->setfields
AS $field)
430 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
432 $updates = implode(', ', $updates);
434 BSRegister
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
436 $this->_runActionMethod('post_update');
439 // ###################################################################
443 * @param bool Run API->setExisting()?
445 public function remove($runset = true)
447 if ($this->condition
== '')
449 trigger_error('Condition is empty: cannot remove');
454 $this->setExisting();
457 $this->_runActionMethod('pre_remove');
459 BSRegister
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
461 $this->_runActionMethod('post_remove');
464 // ###################################################################
466 * Verifies that all required fields are set
468 private function verify()
470 foreach ($this->fields
AS $name => $options)
472 if ($options[F_REQ
] == REQ_YES
)
474 if (!isset($this->values
["$name"]))
476 $this->error(sprintf(_('The required field "%
1$s" was not set
'), $name));
479 else if ($options[F_REQ] == REQ_SET)
481 $this->{"set_$name"}();
486 // ###################################################################
488 * Runs a pre- or post-action method for database commands
490 * @param string Action to run
492 private function _runActionMethod($method)
494 if (in_array($method, $this->norunners))
499 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
502 // ###################################################################
504 * Determines if it's safe to run a relation
; if so
, it will
return
505 * the WHERE SQL clause
507 * @param
string Operation to run
509 public function callRelations($method)
511 if (!is_array($this->dorelations
) OR !in_array($method, $this->dorelations
))
516 foreach ($this->fields
AS $field => $info)
518 $value = (isset($this->values
["$field"]) ? $this->values["$field"] : $this->objdata
["$field"]);
519 if ($value == null OR !is_array($info[F_RELATION]))
524 if (!file_exists(BSRegister::GetApplicationPath() . $info[F_RELATION][F_RELATION_FILE]))
526 trigger_error("Could not load the relation file
for field
'$field'");
529 require_once(BSRegister::GetApplicationPath() . $info[F_RELATION][F_RELATION_FILE]);
531 $this->relations["$field"] = new $info[F_RELATION][F_RELATION_CLASS]($this->registry);
532 $this->relations["$field"]->set(($info[F_RELATION][F_RELATION_ALTFIELD] ? $info[F_RELATION][F_RELATION_ALTFIELD] : $field), $value);
533 $this->relations["$field"]->setCondition();
534 $this->relations["$field"]->$method();
538 // ###################################################################
540 * Prepares a value for use in a SQL query; it encases and escapes
541 * strings and string-like values
543 * @param string Field name
545 * @return string Prepared value entry
547 private function _prepareFieldForSql($name)
549 $type = $this->fields["$name"][F_TYPE];
551 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
553 return "'" . BSRegister::GetType('Db')->escapeString($this->values["$name"]) . "'";
555 else if ($type == TYPE_BOOL
)
557 return ($this->values
["$name"] == true ? "'1'" : "'0'");
559 else if ($type == TYPE_BIN)
561 return "'" . BSRegister::GetType('Db
')->escapeBinary($this->values["$name"]) . "'";
565 return $this->values["$name"];
569 // ###################################################################
571 * Verify field: not a zero value
573 protected function verify_nozero($field)
575 if ($this->values
["$field"] == 0)
577 return sprintf(_('The field "%
1$s" cannot be zero
'), $field);
583 // ###################################################################
585 * Verify field: not empty
587 protected function verify_noempty($field)
589 if (empty($this->values["$field"]))
591 return sprintf(_('The field
"%1$s" cannot be empty'), $field);
598 // ###################################################################
600 * Setter and getter method for the API error reporting system. Passing
601 * a name will cause the set, no arguments will cause the get.
605 * @param mixed Method name in callable form
607 * @return mixed Method name in callable form
609 function APIError($new = null)
611 static $caller, $prev;
617 else if ($new !== null)
626 /*=====================================================================*\
627 || ###################################################################
630 || ###################################################################
631 \*=====================================================================*/