]>
src.bluestatic.org Git - isso.git/blob - Api.php
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 list that has been generated
122 private $errors = array();
124 // ###################################################################
126 * Constructor: cannot instantiate class directly
128 public function __construct()
130 BSRegister
::RequiredModules(array('Db', 'Input'));
133 // ###################################################################
135 * Constructs an error for the error handler to receive
137 * @param string Error message
139 protected function _error($message)
141 $this->errors
[] = $message;
143 // we want to explicitly specify silence
144 if (APIError() == 'silent')
149 if (!is_callable(APIError()))
151 trigger_error('No APIError() handler has been set');
154 call_user_func(APIError(), $message);
157 // ###################################################################
159 * Returns the error list. This is because we don't want people mucking
160 * with the error system. It will return an empty array if there are
163 * @return array Array of errors
165 public function checkErrors()
167 if (sizeof($this->errors
) < 1)
172 return $this->errors
;
175 // ###################################################################
177 * Sets a value, sanitizes it, and verifies it
179 * @param string Field name
181 * @param bool Do clean?
182 * @param bool Do verify?
184 public function set($field, $value, $doclean = true, $doverify = true)
186 if (!isset($this->fields
["$field"]))
188 trigger_error('Field "' . $field . '" is not valid');
192 $this->values["$field"] = ($doclean ? BSRegister
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
194 $this->setfields["$field"] = $field;
196 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
198 if ($this->fields["$field"][F_VERIFY
] == ':self')
200 $verify = $this->{"verify_$field"}($field);
204 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
207 if ($verify !== true)
209 if ($verify === false)
211 $this->error(sprintf(_('Validation of "%1$s" failed'), $field));
215 $this->error($verify);
221 // ###################################################################
223 * Sets the condition to use in the WHERE clause; if not passed, then
224 * it calculates it from the REQ_AUTO field
226 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
228 public function setCondition($condition = '')
230 if (is_array($condition) AND sizeof($condition) > 0)
232 $this->condition
= '';
234 foreach ($condition AS $field)
236 if (!$this->values
["$field"])
238 trigger_error('The specified field "' . $field . '" for the condition could not be found as it is not set');
242 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
244 $this->condition = implode(' AND ', $condbits);
246 else if ($condition != '')
248 $this->condition = $condition;
252 foreach ($this->fields AS $name => $options)
254 if ($options[F_REQ] == REQ_AUTO)
256 if (!$this->values["$name"])
258 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
262 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
266 if ($this->condition
== '')
268 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
273 // ###################################################################
275 * Sets existing data into $values where it's not already present
277 public function setExisting()
287 foreach ($this->objdata
AS $field => $value)
289 if (!isset($this->values
["$field"]))
291 $this->values["$field"] = $value;
298 // ###################################################################
300 * Fetches a record based on the condition
302 * @param bool Run pre_fetch()?
303 * @param bool Run post_fetch()?
305 public function fetch($doPre = true, $doPost = true)
307 if ($this->condition
== '')
309 $this->setCondition();
312 $this->_runActionMethod('pre_fetch', $doPre);
314 $result = BSRegister
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
317 $this->error(_('No records were returned'));
321 $this->_runActionMethod('post_fetch', $doPost);
323 $this->objdata
= $result;
327 foreach ($this->objdata
AS $key => $value)
329 if (!isset($this->values
["$key"]))
331 $this->values["$key"] = $value;
337 // ###################################################################
339 * Inserts a record in the database
341 * @param bool Run pre_insert()?
342 * @param bool Run post_insert()?
344 public function insert($doPre = true, $doPost = true)
348 $this->_runActionMethod('pre_insert', $doPre);
350 foreach ($this->setfields
AS $field)
353 $values[] = $this->_prepareFieldForSql($field);
356 BSRegister
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
358 if (BSRegister
::GetType('DbPostgreSql'))
360 foreach ($this->fields
AS $field => $info)
362 if ($info[F_REQ
] == REQ_AUTO
)
369 $this->insertid
= BSRegister
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
373 $this->insertid
= BSRegister
::GetType('Db')->insertId();
376 $this->_runActionMethod('post_insert', $doPost);
379 // ###################################################################
381 * Updates a record in the database using the data in $vaues
383 * @param bool Run pre_update()?
384 * @param bool Run post_update()?
386 public function update($doPre = true, $doPost = true)
388 if ($this->condition
== '')
390 $this->setCondition();
393 $this->_runActionMethod('pre_update', $doPre);
395 foreach ($this->setfields
AS $field)
397 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
399 $updates = implode(', ', $updates);
401 BSRegister
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
403 $this->_runActionMethod('post_update', $doPost);
406 // ###################################################################
410 * @param bool Run pre_remove()?
411 * @param bool Run post_remove()?
413 public function remove($doPre = true, $doPost = true)
415 if ($this->condition
== '')
417 $this->setCondition();
422 $this->_runActionMethod('pre_remove', $doPre);
424 BSRegister
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
426 $this->_runActionMethod('post_remove', $doPost);
429 // ###################################################################
431 * Verifies that all required fields are set
433 private function verify()
435 foreach ($this->fields
AS $name => $options)
437 if ($options[F_REQ
] == REQ_YES
)
439 if (!isset($this->values
["$name"]))
441 $this->error(sprintf(_('The required field "%
1$s" was not set
'), $name));
444 else if ($options[F_REQ] == REQ_SET)
446 $this->{"set_$name"}();
451 // ###################################################################
453 * Runs a pre- or post-action method for database commands
455 * @param string Action to run
456 * @param bool Actually run it?
458 private function _runActionMethod($method, $doRun)
465 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
468 // ###################################################################
470 * Prepares a value for use in a SQL query; it encases and escapes
471 * strings and string-like values
473 * @param string Field name
475 * @return string Prepared value entry
477 private function _prepareFieldForSql($name)
479 $type = $this->fields["$name"][F_TYPE];
481 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
483 return "'" . BSRegister::GetType('Db')->escapeString($this->values["$name"]) . "'";
485 else if ($type == TYPE_BOOL
)
487 return ($this->values
["$name"] == true ? "'1'" : "'0'");
489 else if ($type == TYPE_BIN)
491 return "'" . BSRegister::GetType('Db
')->escapeBinary($this->values["$name"]) . "'";
495 return $this->values["$name"];
499 // ###################################################################
501 * Verify field: not a zero value
503 protected function verify_nozero($field)
505 if ($this->values
["$field"] == 0)
507 return sprintf(_('The field "%
1$s" cannot be zero
'), $field);
513 // ###################################################################
515 * Verify field: not empty
517 protected function verify_noempty($field)
519 if (empty($this->values["$field"]))
521 return sprintf(_('The field
"%1$s" cannot be empty'), $field);
528 // ###################################################################
530 * Setter and getter method for the API error reporting system. Passing
531 * a name will cause the set, no arguments will cause the get.
535 * @param mixed Method name in callable form
537 * @return mixed Method name in callable form
539 function APIError($new = null)
541 static $caller, $prev;
547 else if ($new !== null)
556 /*=====================================================================*\
557 || ###################################################################
560 || ###################################################################
561 \*=====================================================================*/