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 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
184 * @param string Error message
186 function error($message)
188 $this->errors
[] = $message;
190 // we want to explicitly specify silence
191 if (APIError() == 'silent')
196 if (!is_callable(APIError()))
198 trigger_error('No APIError() handler has been set', E_USER_WARNING
);
201 call_user_func(APIError(), $message);
204 // ###################################################################
206 * Returns the error list. This is because we don't want people mucking
207 * with the error system. It will return an empty array if there are
212 * @return array Array of errors
214 function check_errors()
216 if (sizeof($this->errors
) < 1)
221 return $this->errors
;
224 // ###################################################################
226 * Sets a value, sanitizes it, and verifies it
230 * @param string Field name
232 * @param bool Do clean?
233 * @param bool Do verify?
235 function set($field, $value, $doclean = true
, $doverify = true
)
237 if (!isset($this->fields
["$field"]))
239 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING
);
243 $this->values
["$field"] = ($doclean ?
$this->registry
->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
245 $this->setfields
["$field"] = $field;
247 if (isset($this->fields
["$field"][F_VERIFY
]) AND $doverify)
249 if ($this->fields
["$field"][F_VERIFY
] == ':self')
251 $verify = $this->{"verify_$field"}($field);
255 $verify = $this->{$this->fields
["$field"][F_VERIFY
]}($field);
258 if ($verify !== true
)
260 if ($verify === false
)
262 $this->error(sprintf($this->registry
->modules
['localize']->string('Validation of %1$s failed'), $field));
266 $this->error($verify);
272 // ###################################################################
274 * Sets the condition to use in the WHERE clause; if not passed, then
275 * it calculates it from the REQ_AUTO field
279 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
281 function set_condition($condition = '')
283 if (is_array($condition) AND sizeof($condition) > 0)
285 $this->condition
= '';
287 foreach ($condition AS $field)
289 if (!$this->values
["$field"])
291 trigger_error('The specified field `' . $field . '` for the condition could not be found as it is not set', E_USER_WARNING
);
295 $condbits[] = "$field = " . $this->prepare_field_for_sql($field);
297 $this->condition
= implode(' AND ', $condbits);
299 else if ($condition != '')
301 $this->condition
= $condition;
305 foreach ($this->fields
AS $name => $options)
307 if ($options[F_REQ
] == REQ_AUTO
)
309 if (!$this->values
["$name"])
311 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING
);
315 $this->condition
= "$name = " . $this->prepare_field_for_sql($name);
319 if ($this->condition
== '')
321 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING
);
326 // ###################################################################
328 * Sets existing data into $values where it's not already present
332 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[] ?
361 function fetch($populate = false
)
363 if ($this->condition
== '')
365 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR
);
368 $this->run_action_method('pre_fetch');
370 $result = $this->registry
->modules
[ISSO_DB_LAYER
]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
373 $this->error($this->registry
->modules
['localize']->string('No records were returned'));
377 $this->run_action_method('post_fetch');
379 $this->objdata
= $result;
383 foreach ($this->objdata
AS $key => $value)
385 if (!isset($this->values
["$key"]))
387 $this->values
["$key"] = $value;
392 $this->call_relations('fetch');
395 // ###################################################################
397 * Inserts a record in the database
405 $this->run_action_method('pre_insert');
407 foreach ($this->setfields
AS $field)
410 $values[] = $this->prepare_field_for_sql($field);
413 $this->registry
->modules
[ISSO_DB_LAYER
]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
415 if (strcasecmp(ISSO_DB_LAYER
, 'DB_PostgreSQL') == 0)
417 foreach ($this->fields
AS $field => $info)
419 if ($info[F_REQ
] == REQ_AUTO
)
426 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id($this->prefix
. $this->table
, $autofield);
430 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id();
433 $this->run_action_method('post_insert');
436 // ###################################################################
438 * Updates a record in the database using the data in $vaues
444 if ($this->condition
== '')
446 trigger_error('Condition is empty: cannot update', E_USER_ERROR
);
449 $this->run_action_method('pre_update');
451 foreach ($this->setfields
AS $field)
453 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
455 $updates = implode(', ', $updates);
457 $this->registry
->modules
[ISSO_DB_LAYER
]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
459 $this->run_action_method('post_update');
462 // ###################################################################
468 * @param bool Run API->set_existing()?
470 function delete($runset = true
)
472 if ($this->condition
== '')
474 trigger_error('Condition is empty: cannot delete', E_USER_ERROR
);
479 $this->set_existing();
482 $this->run_action_method('pre_delete');
484 $this->registry
->modules
[ISSO_DB_LAYER
]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
486 $this->run_action_method('post_delete');
489 // ###################################################################
491 * Verifies that all required fields are set
497 foreach ($this->fields
AS $name => $options)
499 if ($options[F_REQ
] == REQ_YES
)
501 if (!isset($this->values
["$name"]))
503 $this->error(sprintf($this->registry
->modules
['localize']->string('Required field %1$s was not set'), $name));
506 else if ($options[F_REQ
] == REQ_SET
)
508 $this->{"set_$name"}();
513 // ###################################################################
515 * Runs a pre- or post-action method for database commands
519 * @param string Action to run
521 function run_action_method($method)
523 if (in_array($method, $this->norunners
))
528 $actmethod = (method_exists($this, $method) ?
$this->$method() : '');
531 // ###################################################################
533 * Determines if it's safe to run a relation; if so, it will return
534 * the WHERE SQL clause
538 * @param string Operation to run
540 function call_relations($method)
542 if (!is_array($this->dorelations
) OR !in_array($method, $this->dorelations
))
547 foreach ($this->fields
AS $field => $info)
549 $value = (isset($this->values
["$field"]) ?
$this->values
["$field"] : $this->objdata
["$field"]);
550 if ($value == null
OR !is_array($info[F_RELATION
]))
555 if (!file_exists($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]))
557 trigger_error("Could not load the relation file for field '$field'");
560 require_once($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]);
562 $this->relations
["$field"] = new $info[F_RELATION
][F_RELATION_CLASS
]($this->registry
);
563 $this->relations
["$field"]->set(($info[F_RELATION
][F_RELATION_ALTFIELD
] ?
$info[F_RELATION
][F_RELATION_ALTFIELD
] : $field), $value);
564 $this->relations
["$field"]->set_condition();
565 $this->relations
["$field"]->$method();
569 // ###################################################################
571 * Prepares a value for use in a SQL query; it encases and escapes
572 * strings and string-like values
576 * @param string Field name
578 * @return string Prepared value entry
580 function prepare_field_for_sql($name)
582 $type = $this->fields
["$name"][F_TYPE
];
584 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
586 return "'" . $this->registry
->db
->escape_string($this->values
["$name"]) . "'";
588 else if ($type == TYPE_BOOL
)
590 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
592 else if ($type == TYPE_BIN
)
594 return "'" . $this->registry
->db
->escape_binary($this->values
["$name"]) . "'";
598 return $this->values
["$name"];
602 // ###################################################################
604 * Verify field: not a zero value
608 function verify_nozero($field)
610 if ($this->values
["$field"] == 0)
612 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be zero'), $field);
618 // ###################################################################
620 * Verify field: not empty
624 function verify_noempty($field)
626 if (empty($this->values
["$field"]))
628 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be empty'), $field);
635 // ###################################################################
637 * Setter and getter method for the API error reporting system. Passing
638 * a name will cause the set, no arguments will cause the get.
642 * @param mixed Method name in callable form
644 * @return mixed Method name in callable form
646 function APIError($new = null
)
648 static $caller, $prev;
654 else if ($new !== null
)
663 /*=====================================================================*\
664 || ###################################################################
667 || ###################################################################
668 \*=====================================================================*/