]>
src.bluestatic.org Git - isso.git/blob - api.php
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
29 if (!defined('REQ_AUTO'))
42 * Auto-increasing value
44 define('REQ_AUTO', -1);
47 * Set by a cusotm set_*() function
52 * Index for cleaning type
57 * Index for requirement type
62 * Index for verification type
64 define('F_VERIFY', 2);
69 define('F_RELATION', 3);
72 * Relation index for file name, relative to ISSO->apppath
74 define('F_RELATION_FILE', 0);
77 * Relation index for class name
79 define('F_RELATION_CLASS', 1);
82 * Relation index for field-link alternate name
84 define('F_RELATION_ALTFIELD', 2);
90 * Abstract class that is used as an API base for most common database interaction
91 * schemes. Creates a simple structure that holds data and can update, delete, and
95 * @copyright Copyright ©2002 - [#]year[#], Blue Static
106 protected $registry = null;
109 * Fields: used for verification and sanitization
110 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
113 protected $fields = array();
116 * Values array: sanitized and verified field values
119 public $values = array();
122 * Fields that were manually set with set(), not by using set_existing()
125 private $setfields = array();
128 * An array of all of the processed relations on an object
131 public $relations = array();
137 private $condition = '';
140 * The object table row; a fetched row that represents this instance
143 public $objdata = array();
146 * Insert ID from the insert() command
149 public $insertid = 0;
152 * Pre- and post-action method stoppers
155 public $norunners = array();
158 * The relations to execute on
161 public $dorelations = array('fetch');
164 * Error list that has been generated
167 private $errors = array();
169 // ###################################################################
171 * Constructor: cannot instantiate class directly
173 public function __construct(&$registry)
175 if (!is_subclass_of($this, 'API'))
177 trigger_error('Cannot instantiate the API module directly');
180 if (!is_object($registry))
182 trigger_error('The passed registry is not an object');
185 $this->registry
=& $registry;
188 // ###################################################################
190 * Constructs an error for the error handler to receive
192 * @param string Error message
194 protected function error($message)
196 $this->errors
[] = $message;
198 // we want to explicitly specify silence
199 if (APIError() == 'silent')
204 if (!is_callable(APIError()))
206 trigger_error('No APIError() handler has been set');
209 call_user_func(APIError(), $message);
212 // ###################################################################
214 * Returns the error list. This is because we don't want people mucking
215 * with the error system. It will return an empty array if there are
218 * @return array Array of errors
220 public function check_errors()
222 if (sizeof($this->errors
) < 1)
227 return $this->errors
;
230 // ###################################################################
232 * Sets a value, sanitizes it, and verifies it
234 * @param string Field name
236 * @param bool Do clean?
237 * @param bool Do verify?
239 public function set($field, $value, $doclean = true, $doverify = true)
241 if (!isset($this->fields
["$field"]))
243 trigger_error('Field `' . $field . '` is not valid');
247 $this->values["$field"] = ($doclean ? $this->registry
->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
249 $this->setfields["$field"] = $field;
251 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
253 if ($this->fields["$field"][F_VERIFY
] == ':self')
255 $verify = $this->{"verify_$field"}($field);
259 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
262 if ($verify !== true)
264 if ($verify === false)
266 $this->error(sprintf($this->registry
->modules
['localize']->string('Validation of %1$s failed'), $field));
270 $this->error($verify);
276 // ###################################################################
278 * Sets the condition to use in the WHERE clause; if not passed, then
279 * it calculates it from the REQ_AUTO field
281 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
283 public function set_condition($condition = '')
285 if (is_array($condition) AND sizeof($condition) > 0)
287 $this->condition
= '';
289 foreach ($condition AS $field)
291 if (!$this->values
["$field"])
293 trigger_error('The specified field `' . $field . '` for the condition could not be found as it is not set');
297 $condbits[] = "$field = " . $this->prepare_field_for_sql($field);
299 $this->condition = implode(' AND ', $condbits);
301 else if ($condition != '')
303 $this->condition = $condition;
307 foreach ($this->fields AS $name => $options)
309 if ($options[F_REQ] == REQ_AUTO)
311 if (!$this->values["$name"])
313 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
317 $this->condition
= "$name = " . $this->prepare_field_for_sql($name);
321 if ($this->condition
== '')
323 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
328 // ###################################################################
330 * Sets existing data into $values where it's not already present
332 public function set_existing()
342 foreach ($this->objdata
AS $field => $value)
344 if (!isset($this->values
["$field"]))
346 $this->values["$field"] = $value;
353 // ###################################################################
355 * Fetches a record based on the condition
357 * @param bool Populate $this->values[] with data, along with $this->objdata[] ?
359 public function fetch($populate = false)
361 if ($this->condition
== '')
363 trigger_error('Condition is empty: cannot fetch');
366 $this->run_action_method('pre_fetch');
368 $result = $this->registry
->modules
[ISSO_DB_LAYER
]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
371 $this->error($this->registry
->modules
['localize']->string('No records were returned'));
375 $this->run_action_method('post_fetch');
377 $this->objdata
= $result;
381 foreach ($this->objdata
AS $key => $value)
383 if (!isset($this->values
["$key"]))
385 $this->values["$key"] = $value;
390 $this->call_relations('fetch');
393 // ###################################################################
395 * Inserts a record in the database
397 public function insert()
401 $this->run_action_method('pre_insert');
403 foreach ($this->setfields
AS $field)
406 $values[] = $this->prepare_field_for_sql($field);
409 $this->registry
->modules
[ISSO_DB_LAYER
]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
411 if (strcasecmp(ISSO_DB_LAYER
, 'DB_PostgreSQL') == 0)
413 foreach ($this->fields
AS $field => $info)
415 if ($info[F_REQ
] == REQ_AUTO
)
422 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id($this->prefix
. $this->table
, $autofield);
426 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id();
429 $this->run_action_method('post_insert');
432 // ###################################################################
434 * Updates a record in the database using the data in $vaues
436 public function update()
438 if ($this->condition
== '')
440 trigger_error('Condition is empty: cannot update');
443 $this->run_action_method('pre_update');
445 foreach ($this->setfields
AS $field)
447 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
449 $updates = implode(', ', $updates);
451 $this->registry
->modules
[ISSO_DB_LAYER
]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
453 $this->run_action_method('post_update');
456 // ###################################################################
460 * @param bool Run API->set_existing()?
462 public function delete($runset = true)
464 if ($this->condition
== '')
466 trigger_error('Condition is empty: cannot delete');
471 $this->set_existing();
474 $this->run_action_method('pre_delete');
476 $this->registry
->modules
[ISSO_DB_LAYER
]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
478 $this->run_action_method('post_delete');
481 // ###################################################################
483 * Verifies that all required fields are set
485 private function verify()
487 foreach ($this->fields
AS $name => $options)
489 if ($options[F_REQ
] == REQ_YES
)
491 if (!isset($this->values
["$name"]))
493 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
496 else if ($options[F_REQ] == REQ_SET)
498 $this->{"set_$name"}();
503 // ###################################################################
505 * Runs a pre- or post-action method for database commands
507 * @param string Action to run
509 private function run_action_method($method)
511 if (in_array($method, $this->norunners))
516 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
519 // ###################################################################
521 * Determines if it's safe to run a relation; if so, it will return
522 * the WHERE SQL clause
524 * @param string Operation to run
526 public function call_relations($method)
528 if (!is_array($this->dorelations) OR !in_array($method, $this->dorelations))
533 foreach ($this->fields AS $field => $info)
535 $value = (isset($this->values["$field"]) ? $this->values
["$field"] : $this->objdata["$field"]);
536 if ($value == null OR !is_array($info[F_RELATION
]))
541 if (!file_exists($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]))
543 trigger_error("Could not load the relation file for field '$field'");
546 require_once($this->registry->get('apppath') . $info[F_RELATION][F_RELATION_FILE]);
548 $this->relations["$field"] = new $info[F_RELATION
][F_RELATION_CLASS
]($this->registry
);
549 $this->relations
["$field"]->set(($info[F_RELATION][F_RELATION_ALTFIELD] ? $info[F_RELATION][F_RELATION_ALTFIELD] : $field), $value);
550 $this->relations["$field"]->set_condition();
551 $this->relations
["$field"]->$method();
555 // ###################################################################
557 * Prepares a value for use in a SQL query; it encases and escapes
558 * strings and string-like values
560 * @param string Field name
562 * @return string Prepared value entry
564 private function prepare_field_for_sql($name)
566 $type = $this->fields["$name"][F_TYPE
];
568 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
570 return "'" . $this->registry
->db
->escape_string($this->values
["$name"]) . "'";
572 else if ($type == TYPE_BOOL)
574 return ($this->values["$name"] == true ? "'1'" : "'0'");
576 else if ($type == TYPE_BIN)
578 return "'" . $this->registry->db->escape_binary($this->values["$name"]) . "'";
582 return $this->values
["$name"];
586 // ###################################################################
588 * Verify field: not a zero value
590 protected function verify_nozero($field)
592 if ($this->values["$field"] == 0)
594 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be zero'), $field);
600 // ###################################################################
602 * Verify field: not empty
604 protected function verify_noempty($field)
606 if (empty($this->values
["$field"]))
608 return sprintf($this->registry->modules['localize']->string('The field "%
1$s" cannot be
empty'), $field);
615 // ###################################################################
617 * Setter and getter method for the API error reporting system. Passing
618 * a name will cause the set, no arguments will cause the get.
622 * @param mixed Method name in callable form
624 * @return mixed Method name in callable form
626 function APIError($new = null)
628 static $caller, $prev;
634 else if ($new !== null)
643 /*=====================================================================*\
644 || ###################################################################
647 || ###################################################################
648 \*=====================================================================*/