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);
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 * Pre- and post-action method stoppers
122 public $norunners = array();
125 * Error list that has been generated
128 private $errors = array();
130 // ###################################################################
132 * Constructor: cannot instantiate class directly
134 public function __construct()
136 BSRegister
::RequiredModules(array('Db', 'Input'));
139 // ###################################################################
141 * Constructs an error for the error handler to receive
143 * @param string Error message
145 protected function error($message)
147 $this->errors
[] = $message;
149 // we want to explicitly specify silence
150 if (APIError() == 'silent')
155 if (!is_callable(APIError()))
157 trigger_error('No APIError() handler has been set');
160 call_user_func(APIError(), $message);
163 // ###################################################################
165 * Returns the error list. This is because we don't want people mucking
166 * with the error system. It will return an empty array if there are
169 * @return array Array of errors
171 public function checkErrors()
173 if (sizeof($this->errors
) < 1)
178 return $this->errors
;
181 // ###################################################################
183 * Sets a value, sanitizes it, and verifies it
185 * @param string Field name
187 * @param bool Do clean?
188 * @param bool Do verify?
190 public function set($field, $value, $doclean = true
, $doverify = true
)
192 if (!isset($this->fields
["$field"]))
194 trigger_error('Field `' . $field . '` is not valid');
198 $this->values
["$field"] = ($doclean ? BSRegister
::GetType('Input')->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
200 $this->setfields
["$field"] = $field;
202 if (isset($this->fields
["$field"][F_VERIFY
]) AND $doverify)
204 if ($this->fields
["$field"][F_VERIFY
] == ':self')
206 $verify = $this->{"verify_$field"}($field);
210 $verify = $this->{$this->fields
["$field"][F_VERIFY
]}($field);
213 if ($verify !== true
)
215 if ($verify === false
)
217 $this->error(sprintf(_('Validation of "%1$s" failed'), $field));
221 $this->error($verify);
227 // ###################################################################
229 * Sets the condition to use in the WHERE clause; if not passed, then
230 * it calculates it from the REQ_AUTO field
232 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
234 public function setCondition($condition = '')
236 if (is_array($condition) AND sizeof($condition) > 0)
238 $this->condition
= '';
240 foreach ($condition AS $field)
242 if (!$this->values
["$field"])
244 trigger_error('The specified field "' . $field . '" for the condition could not be found as it is not set');
248 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
250 $this->condition
= implode(' AND ', $condbits);
252 else if ($condition != '')
254 $this->condition
= $condition;
258 foreach ($this->fields
AS $name => $options)
260 if ($options[F_REQ
] == REQ_AUTO
)
262 if (!$this->values
["$name"])
264 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
268 $this->condition
= "$name = " . $this->_prepareFieldForSql($name);
272 if ($this->condition
== '')
274 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
279 // ###################################################################
281 * Sets existing data into $values where it's not already present
283 public function setExisting()
293 foreach ($this->objdata
AS $field => $value)
295 if (!isset($this->values
["$field"]))
297 $this->values
["$field"] = $value;
304 // ###################################################################
306 * Fetches a record based on the condition
308 * @param bool Populate $this->values[] with data, along with $this->objdata[] ?
310 public function fetch($populate = false
)
312 if ($this->condition
== '')
314 trigger_error('Condition is empty: cannot fetch');
317 $this->_runActionMethod('pre_fetch');
319 $result = BSRegister
::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
322 $this->error(_('No records were returned'));
326 $this->_runActionMethod('post_fetch');
328 $this->objdata
= $result;
332 foreach ($this->objdata
AS $key => $value)
334 if (!isset($this->values
["$key"]))
336 $this->values
["$key"] = $value;
341 $this->callRelations('fetch');
344 // ###################################################################
346 * Inserts a record in the database
348 public function insert()
352 $this->_runActionMethod('pre_insert');
354 foreach ($this->setfields
AS $field)
357 $values[] = $this->_prepareFieldForSql($field);
360 BSRegister
::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
362 if (BSRegister
::GetType('DbPostgreSql'))
364 foreach ($this->fields
AS $field => $info)
366 if ($info[F_REQ
] == REQ_AUTO
)
373 $this->insertid
= BSRegister
::GetType('Db')->insertId($this->prefix
. $this->table
, $autofield);
377 $this->insertid
= BSRegister
::GetType('Db')->insertId();
380 $this->_runActionMethod('post_insert');
383 // ###################################################################
385 * Updates a record in the database using the data in $vaues
387 public function update()
389 if ($this->condition
== '')
391 trigger_error('Condition is empty: cannot update');
394 $this->_runActionMethod('pre_update');
396 foreach ($this->setfields
AS $field)
398 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
400 $updates = implode(', ', $updates);
402 BSRegister
::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
404 $this->_runActionMethod('post_update');
407 // ###################################################################
411 * @param bool Run API->setExisting()?
413 public function remove($runset = true
)
415 if ($this->condition
== '')
417 trigger_error('Condition is empty: cannot remove');
422 $this->setExisting();
425 $this->_runActionMethod('pre_remove');
427 BSRegister
::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
429 $this->_runActionMethod('post_remove');
432 // ###################################################################
434 * Verifies that all required fields are set
436 private function verify()
438 foreach ($this->fields
AS $name => $options)
440 if ($options[F_REQ
] == REQ_YES
)
442 if (!isset($this->values
["$name"]))
444 $this->error(sprintf(_('The required field "%1$s" was not set'), $name));
447 else if ($options[F_REQ
] == REQ_SET
)
449 $this->{"set_$name"}();
454 // ###################################################################
456 * Runs a pre- or post-action method for database commands
458 * @param string Action to run
460 private function _runActionMethod($method)
462 if (in_array($method, $this->norunners
))
467 $actmethod = (method_exists($this, $method) ?
$this->$method() : '');
470 // ###################################################################
472 * Prepares a value for use in a SQL query; it encases and escapes
473 * strings and string-like values
475 * @param string Field name
477 * @return string Prepared value entry
479 private function _prepareFieldForSql($name)
481 $type = $this->fields
["$name"][F_TYPE
];
483 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
485 return "'" . BSRegister
::GetType('Db')->escapeString($this->values
["$name"]) . "'";
487 else if ($type == TYPE_BOOL
)
489 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
491 else if ($type == TYPE_BIN
)
493 return "'" . BSRegister
::GetType('Db')->escapeBinary($this->values
["$name"]) . "'";
497 return $this->values
["$name"];
501 // ###################################################################
503 * Verify field: not a zero value
505 protected function verify_nozero($field)
507 if ($this->values
["$field"] == 0)
509 return sprintf(_('The field "%1$s" cannot be zero'), $field);
515 // ###################################################################
517 * Verify field: not empty
519 protected function verify_noempty($field)
521 if (empty($this->values
["$field"]))
523 return sprintf(_('The field "%1$s" cannot be empty'), $field);
530 // ###################################################################
532 * Setter and getter method for the API error reporting system. Passing
533 * a name will cause the set, no arguments will cause the get.
537 * @param mixed Method name in callable form
539 * @return mixed Method name in callable form
541 function APIError($new = null
)
543 static $caller, $prev;
549 else if ($new !== null
)
558 /*=====================================================================*\
559 || ###################################################################
562 || ###################################################################
563 \*=====================================================================*/