]>
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'))
32 * Auto-increasing value
34 define('REQ_AUTO', -1);
37 * Set by a cusotm set_*() function
42 * Index for cleaning type
47 * Index for requirement type
52 * Index for verification type
54 define('F_VERIFY', 2);
59 define('F_RELATION', 3);
62 * Relation index for file name, relative to ISSO->apppath
64 define('F_RELATION_FILE', 0);
67 * Relation index for class name
69 define('F_RELATION_CLASS', 1);
72 * Relation index for field-link alternate name
74 define('F_RELATION_ALTFIELD', 2);
80 * Abstract class that is used as an API base for most common database interaction
81 * schemes. Creates a simple structure that holds data and can update, delete, and
85 * @copyright Copyright ©2002 - [#]year[#], Blue Static
96 protected $registry = null;
99 * Fields: used for verification and sanitization
100 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
103 protected $fields = array();
106 * Values array: sanitized and verified field values
109 public $values = array();
112 * Fields that were manually set with set(), not by using set_existing()
115 private $setfields = array();
118 * An array of all of the processed relations on an object
121 public $relations = array();
127 private $condition = '';
130 * The object table row; a fetched row that represents this instance
133 public $objdata = array();
136 * Insert ID from the insert() command
139 public $insertid = 0;
142 * Pre- and post-action method stoppers
145 public $norunners = array();
148 * The relations to execute on
151 public $dorelations = array('fetch');
154 * Error list that has been generated
157 private $errors = array();
159 // ###################################################################
161 * Constructor: cannot instantiate class directly
163 public function __construct(&$registry)
165 if (!is_subclass_of($this, 'API'))
167 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR
);
170 if (!is_object($registry))
172 trigger_error('The passed registry is not an object', E_USER_ERROR
);
175 $this->registry
=& $registry;
178 // ###################################################################
180 * Constructs an error for the error handler to receive
182 * @param string Error message
184 protected function error($message)
186 $this->errors
[] = $message;
188 // we want to explicitly specify silence
189 if (APIError() == 'silent')
194 if (!is_callable(APIError()))
196 trigger_error('No APIError() handler has been set', E_USER_WARNING
);
199 call_user_func(APIError(), $message);
202 // ###################################################################
204 * Returns the error list. This is because we don't want people mucking
205 * with the error system. It will return an empty array if there are
208 * @return array Array of errors
210 public function check_errors()
212 if (sizeof($this->errors
) < 1)
217 return $this->errors
;
220 // ###################################################################
222 * Sets a value, sanitizes it, and verifies it
224 * @param string Field name
226 * @param bool Do clean?
227 * @param bool Do verify?
229 public function set($field, $value, $doclean = true, $doverify = true)
231 if (!isset($this->fields
["$field"]))
233 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
237 $this->values["$field"] = ($doclean ? $this->registry
->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
239 $this->setfields["$field"] = $field;
241 if (isset($this->fields
["$field"][F_VERIFY]) AND $doverify)
243 if ($this->fields["$field"][F_VERIFY
] == ':self')
245 $verify = $this->{"verify_$field"}($field);
249 $verify = $this->{$this
->fields
["$field"][F_VERIFY
]}($field);
252 if ($verify !== true)
254 if ($verify === false)
256 $this->error(sprintf($this->registry
->modules
['localize']->string('Validation of %1$s failed'), $field));
260 $this->error($verify);
266 // ###################################################################
268 * Sets the condition to use in the WHERE clause; if not passed, then
269 * it calculates it from the REQ_AUTO field
271 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
273 public function set_condition($condition = '')
275 if (is_array($condition) AND sizeof($condition) > 0)
277 $this->condition
= '';
279 foreach ($condition AS $field)
281 if (!$this->values
["$field"])
283 trigger_error('The specified field `' . $field . '` for the condition could not be found as it is not set', E_USER_WARNING);
287 $condbits[] = "$field = " . $this->prepare_field_for_sql($field);
289 $this->condition = implode(' AND ', $condbits);
291 else if ($condition != '')
293 $this->condition = $condition;
297 foreach ($this->fields AS $name => $options)
299 if ($options[F_REQ] == REQ_AUTO)
301 if (!$this->values["$name"])
303 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING
);
307 $this->condition
= "$name = " . $this->prepare_field_for_sql($name);
311 if ($this->condition
== '')
313 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING
);
318 // ###################################################################
320 * Sets existing data into $values where it's not already present
322 public function set_existing()
332 foreach ($this->objdata
AS $field => $value)
334 if (!isset($this->values
["$field"]))
336 $this->values["$field"] = $value;
343 // ###################################################################
345 * Fetches a record based on the condition
347 * @param bool Populate $this->values[] with data, along with $this->objdata[] ?
349 public function fetch($populate = false)
351 if ($this->condition
== '')
353 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR
);
356 $this->run_action_method('pre_fetch');
358 $result = $this->registry
->modules
[ISSO_DB_LAYER
]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
361 $this->error($this->registry
->modules
['localize']->string('No records were returned'));
365 $this->run_action_method('post_fetch');
367 $this->objdata
= $result;
371 foreach ($this->objdata
AS $key => $value)
373 if (!isset($this->values
["$key"]))
375 $this->values["$key"] = $value;
380 $this->call_relations('fetch');
383 // ###################################################################
385 * Inserts a record in the database
387 public function insert()
391 $this->run_action_method('pre_insert');
393 foreach ($this->setfields
AS $field)
396 $values[] = $this->prepare_field_for_sql($field);
399 $this->registry
->modules
[ISSO_DB_LAYER
]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
401 if (strcasecmp(ISSO_DB_LAYER
, 'DB_PostgreSQL') == 0)
403 foreach ($this->fields
AS $field => $info)
405 if ($info[F_REQ
] == REQ_AUTO
)
412 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id($this->prefix
. $this->table
, $autofield);
416 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id();
419 $this->run_action_method('post_insert');
422 // ###################################################################
424 * Updates a record in the database using the data in $vaues
426 public function update()
428 if ($this->condition
== '')
430 trigger_error('Condition is empty: cannot update', E_USER_ERROR
);
433 $this->run_action_method('pre_update');
435 foreach ($this->setfields
AS $field)
437 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
439 $updates = implode(', ', $updates);
441 $this->registry
->modules
[ISSO_DB_LAYER
]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
443 $this->run_action_method('post_update');
446 // ###################################################################
450 * @param bool Run API->set_existing()?
452 public function delete($runset = true)
454 if ($this->condition
== '')
456 trigger_error('Condition is empty: cannot delete', E_USER_ERROR
);
461 $this->set_existing();
464 $this->run_action_method('pre_delete');
466 $this->registry
->modules
[ISSO_DB_LAYER
]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
468 $this->run_action_method('post_delete');
471 // ###################################################################
473 * Verifies that all required fields are set
475 private function verify()
477 foreach ($this->fields
AS $name => $options)
479 if ($options[F_REQ
] == REQ_YES
)
481 if (!isset($this->values
["$name"]))
483 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
486 else if ($options[F_REQ] == REQ_SET)
488 $this->{"set_$name"}();
493 // ###################################################################
495 * Runs a pre- or post-action method for database commands
497 * @param string Action to run
499 private function run_action_method($method)
501 if (in_array($method, $this->norunners))
506 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
509 // ###################################################################
511 * Determines if it's safe to run a relation; if so, it will return
512 * the WHERE SQL clause
514 * @param string Operation to run
516 public function call_relations($method)
518 if (!is_array($this->dorelations) OR !in_array($method, $this->dorelations))
523 foreach ($this->fields AS $field => $info)
525 $value = (isset($this->values["$field"]) ? $this->values
["$field"] : $this->objdata["$field"]);
526 if ($value == null OR !is_array($info[F_RELATION
]))
531 if (!file_exists($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]))
533 trigger_error("Could not load the relation file for field '$field'");
536 require_once($this->registry->get('apppath') . $info[F_RELATION][F_RELATION_FILE]);
538 $this->relations["$field"] = new $info[F_RELATION
][F_RELATION_CLASS
]($this->registry
);
539 $this->relations
["$field"]->set(($info[F_RELATION][F_RELATION_ALTFIELD] ? $info[F_RELATION][F_RELATION_ALTFIELD] : $field), $value);
540 $this->relations["$field"]->set_condition();
541 $this->relations
["$field"]->$method();
545 // ###################################################################
547 * Prepares a value for use in a SQL query; it encases and escapes
548 * strings and string-like values
550 * @param string Field name
552 * @return string Prepared value entry
554 private function prepare_field_for_sql($name)
556 $type = $this->fields["$name"][F_TYPE
];
558 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
560 return "'" . $this->registry
->db
->escape_string($this->values
["$name"]) . "'";
562 else if ($type == TYPE_BOOL)
564 return ($this->values["$name"] == true ? "'1'" : "'0'");
566 else if ($type == TYPE_BIN)
568 return "'" . $this->registry->db->escape_binary($this->values["$name"]) . "'";
572 return $this->values
["$name"];
576 // ###################################################################
578 * Verify field: not a zero value
580 protected function verify_nozero($field)
582 if ($this->values["$field"] == 0)
584 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be zero'), $field);
590 // ###################################################################
592 * Verify field: not empty
594 protected function verify_noempty($field)
596 if (empty($this->values
["$field"]))
598 return sprintf($this->registry->modules['localize']->string('The field "%
1$s" cannot be
empty'), $field);
605 // ###################################################################
607 * Setter and getter method for the API error reporting system. Passing
608 * a name will cause the set, no arguments will cause the get.
612 * @param mixed Method name in callable form
614 * @return mixed Method name in callable form
616 function APIError($new = null)
618 static $caller, $prev;
624 else if ($new !== null)
633 /*=====================================================================*\
634 || ###################################################################
637 || ###################################################################
638 \*=====================================================================*/