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 BSApp
::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 ? BSApp
::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 = BSApp
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
341 $this->_runActionMethod('post_fetch', $doPost);
343 $this->objdata
= $result;
348 // ###################################################################
350 * Inserts a record in the database
352 * @param bool Run pre_insert()?
353 * @param bool Run post_insert()?
355 public function insert($doPre = true, $doPost = true)
358 $this->_processErrorQueue();
360 $this->_runActionMethod('pre_insert', $doPre);
362 foreach ($this->setfields
AS $field)
365 $values[] = $this->_prepareFieldForSql($field);
368 BSApp
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
370 if (BSApp
::GetType('DbPostgreSql'))
372 foreach ($this->fields
AS $field => $info)
374 if ($info[F_REQ
] == REQ_AUTO
)
381 $this->insertid
= BSApp
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
385 $this->insertid
= BSApp
::GetType('Db')->insertId();
388 $this->_runActionMethod('post_insert', $doPost);
391 // ###################################################################
393 * Updates a record in the database using the data in $vaues
395 * @param bool Run pre_update()?
396 * @param bool Run post_update()?
398 public function update($doPre = true, $doPost = true)
400 if ($this->condition
== '')
402 $this->setCondition();
405 $this->_processErrorQueue();
407 $this->_runActionMethod('pre_update', $doPre);
409 foreach ($this->setfields
AS $field)
411 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
413 $updates = implode(', ', $updates);
415 BSApp
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
417 $this->_runActionMethod('post_update', $doPost);
420 // ###################################################################
424 * @param bool Run pre_remove()?
425 * @param bool Run post_remove()?
427 public function remove($doPre = true, $doPost = true)
429 if ($this->condition
== '')
431 $this->setCondition();
436 $this->_runActionMethod('pre_remove', $doPre);
438 BSApp
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
440 $this->_runActionMethod('post_remove', $doPost);
443 // ###################################################################
445 * Verifies that all required fields are set
447 private function verify()
449 foreach ($this->fields
AS $name => $options)
451 if ($options[F_REQ
] == REQ_YES
)
453 if (!isset($this->values
["$name"]))
455 $this->_error(sprintf(_('The required field "%
1$s" was not set
'), $name));
458 else if ($options[F_REQ] == REQ_SET)
460 $this->{"set_$name"}();
465 // ###################################################################
467 * Runs a pre- or post-action method for database commands
469 * @param string Action to run
470 * @param bool Actually run it?
472 private function _runActionMethod($method, $doRun)
479 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
482 // ###################################################################
484 * Prepares a value for use in a SQL query; it encases and escapes
485 * strings and string-like values
487 * @param string Field name
489 * @return string Prepared value entry
491 private function _prepareFieldForSql($name)
493 $type = $this->fields["$name"][F_TYPE];
495 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
497 return "'" . BSApp::GetType('Db')->escapeString($this->values["$name"]) . "'";
499 else if ($type == TYPE_BOOL
)
501 return ($this->values
["$name"] == true ? "'1'" : "'0'");
503 else if ($type == TYPE_BIN)
505 return "'" . BSApp::GetType('Db
')->escapeBinary($this->values["$name"]) . "'";
509 return $this->values["$name"];
513 // ###################################################################
515 * Verify field: not a zero value
517 protected function verify_nozero($field)
519 if ($this->values
["$field"] == 0)
521 return sprintf(_('The field "%
1$s" cannot be zero
'), $field);
527 // ###################################################################
529 * Verify field: not empty
531 protected function verify_noempty($field)
533 if (empty($this->values["$field"]))
535 return sprintf(_('The field
"%1$s" cannot be empty'), $field);
541 // ###################################################################
543 * Verify field: unique
545 protected function verify_unique($field)
547 $res = BSApp::GetType('Db')->queryFirst("SELECT
$field FROM {$this
->prefix
}{$this
->table
} WHERE
$field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this
->condition
})"));
550 return sprintf(_('The "%
1$s" field must contain a unique value
'), $field);
557 // ###################################################################
559 * Setter and getter method for the API error reporting system. Passing
560 * a name will cause the set, no arguments will cause the get.
562 * @param mixed Method name in callable form
564 * @return mixed Method name in callable form
566 function APIError($new = null)
568 static $caller, $prev;
574 else if ($new !== null)
583 /*=====================================================================*\
584 || ###################################################################
587 || ###################################################################
588 \*=====================================================================*/