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 * (PHP 4) Constructor
182 function API(&$registry)
184 $this->__construct($registry);
187 // ###################################################################
189 * Constructs an error for the error handler to receive
193 * @param string Error message
195 function error($message)
197 $this->errors
[] = $message;
199 // we want to explicitly specify silence
200 if (APIError() == 'silent')
205 if (!is_callable(APIError()))
207 trigger_error('No APIError() handler has been set', E_USER_WARNING
);
210 call_user_func(APIError(), $message);
213 // ###################################################################
215 * Returns the error list. This is because we don't want people mucking
216 * with the error system. It will return an empty array if there are
221 * @return array Array of errors
223 function check_errors()
225 if (sizeof($this->errors
) < 1)
230 return $this->errors
;
233 // ###################################################################
235 * Sets a value, sanitizes it, and verifies it
239 * @param string Field name
241 * @param bool Do clean?
242 * @param bool Do verify?
244 function set($field, $value, $doclean = true
, $doverify = true
)
246 if (!isset($this->fields
["$field"]))
248 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING
);
252 $this->values
["$field"] = ($doclean ?
$this->registry
->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
254 $this->setfields
["$field"] = $field;
256 if (isset($this->fields
["$field"][F_VERIFY
]) AND $doverify)
258 if ($this->fields
["$field"][F_VERIFY
] == ':self')
260 $verify = $this->{"verify_$field"}($field);
264 $verify = $this->{$this->fields
["$field"][F_VERIFY
]}($field);
267 if ($verify !== true
)
269 if ($verify === false
)
271 $this->error(sprintf($this->registry
->modules
['localize']->string('Validation of %1$s failed'), $field));
275 $this->error($verify);
281 // ###################################################################
283 * Sets the condition to use in the WHERE clause; if not passed, then
284 * it calculates it from the REQ_AUTO field
288 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
290 function set_condition($condition = '')
292 if (is_array($condition) AND sizeof($condition) > 0)
294 $this->condition
= '';
296 foreach ($condition AS $field)
298 if (!$this->values
["$field"])
300 trigger_error('The specified field `' . $field . '` for the condition could not be found as it is not set', E_USER_WARNING
);
304 $condbits[] = "$field = " . $this->prepare_field_for_sql($field);
306 $this->condition
= implode(' AND ', $condbits);
308 else if ($condition != '')
310 $this->condition
= $condition;
314 foreach ($this->fields
AS $name => $options)
316 if ($options[F_REQ
] == REQ_AUTO
)
318 if (!$this->values
["$name"])
320 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING
);
324 $this->condition
= "$name = " . $this->prepare_field_for_sql($name);
328 if ($this->condition
== '')
330 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING
);
335 // ###################################################################
337 * Sets existing data into $values where it's not already present
341 function set_existing()
351 foreach ($this->objdata
AS $field => $value)
353 if (!isset($this->values
["$field"]))
355 $this->values
["$field"] = $value;
362 // ###################################################################
364 * Fetches a record based on the condition
366 * @param bool Populate $this->values[] with data, along with $this->objdata[] ?
370 function fetch($populate = false
)
372 if ($this->condition
== '')
374 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR
);
377 $this->run_action_method('pre_fetch');
379 $result = $this->registry
->modules
[ISSO_DB_LAYER
]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
382 $this->error($this->registry
->modules
['localize']->string('No records were returned'));
386 $this->run_action_method('post_fetch');
388 $this->objdata
= $result;
392 foreach ($this->objdata
AS $key => $value)
394 if (!isset($this->values
["$key"]))
396 $this->values
["$key"] = $value;
401 $this->call_relations('fetch');
404 // ###################################################################
406 * Inserts a record in the database
414 $this->run_action_method('pre_insert');
416 foreach ($this->setfields
AS $field)
419 $values[] = $this->prepare_field_for_sql($field);
422 $this->registry
->modules
[ISSO_DB_LAYER
]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
424 if (strcasecmp(ISSO_DB_LAYER
, 'DB_PostgreSQL') == 0)
426 foreach ($this->fields
AS $field => $info)
428 if ($info[F_REQ
] == REQ_AUTO
)
435 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id($this->prefix
. $this->table
, $autofield);
439 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id();
442 $this->run_action_method('post_insert');
445 // ###################################################################
447 * Updates a record in the database using the data in $vaues
453 if ($this->condition
== '')
455 trigger_error('Condition is empty: cannot update', E_USER_ERROR
);
458 $this->run_action_method('pre_update');
460 foreach ($this->setfields
AS $field)
462 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
464 $updates = implode(', ', $updates);
466 $this->registry
->modules
[ISSO_DB_LAYER
]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
468 $this->run_action_method('post_update');
471 // ###################################################################
477 * @param bool Run API->set_existing()?
479 function delete($runset = true
)
481 if ($this->condition
== '')
483 trigger_error('Condition is empty: cannot delete', E_USER_ERROR
);
488 $this->set_existing();
491 $this->run_action_method('pre_delete');
493 $this->registry
->modules
[ISSO_DB_LAYER
]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
495 $this->run_action_method('post_delete');
498 // ###################################################################
500 * Verifies that all required fields are set
506 foreach ($this->fields
AS $name => $options)
508 if ($options[F_REQ
] == REQ_YES
)
510 if (!isset($this->values
["$name"]))
512 $this->error(sprintf($this->registry
->modules
['localize']->string('Required field %1$s was not set'), $name));
515 else if ($options[F_REQ
] == REQ_SET
)
517 $this->{"set_$name"}();
522 // ###################################################################
524 * Runs a pre- or post-action method for database commands
528 * @param string Action to run
530 function run_action_method($method)
532 if (in_array($method, $this->norunners
))
537 $actmethod = (method_exists($this, $method) ?
$this->$method() : '');
540 // ###################################################################
542 * Determines if it's safe to run a relation; if so, it will return
543 * the WHERE SQL clause
547 * @param string Operation to run
549 function call_relations($method)
551 if (!is_array($this->dorelations
) OR !in_array($method, $this->dorelations
))
556 foreach ($this->fields
AS $field => $info)
558 $value = (isset($this->values
["$field"]) ?
$this->values
["$field"] : $this->objdata
["$field"]);
559 if ($value == null
OR !is_array($info[F_RELATION
]))
564 if (!file_exists($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]))
566 trigger_error("Could not load the relation file for field '$field'");
569 require_once($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]);
571 $this->relations
["$field"] = new $info[F_RELATION
][F_RELATION_CLASS
]($this->registry
);
572 $this->relations
["$field"]->set(($info[F_RELATION
][F_RELATION_ALTFIELD
] ?
$info[F_RELATION
][F_RELATION_ALTFIELD
] : $field), $value);
573 $this->relations
["$field"]->set_condition();
574 $this->relations
["$field"]->$method();
578 // ###################################################################
580 * Prepares a value for use in a SQL query; it encases and escapes
581 * strings and string-like values
585 * @param string Field name
587 * @return string Prepared value entry
589 function prepare_field_for_sql($name)
591 $type = $this->fields
["$name"][F_TYPE
];
593 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
595 return "'" . $this->registry
->db
->escape_string($this->values
["$name"]) . "'";
597 else if ($type == TYPE_BOOL
)
599 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
601 else if ($type == TYPE_BIN
)
603 return "'" . $this->registry
->db
->escape_binary($this->values
["$name"]) . "'";
607 return $this->values
["$name"];
611 // ###################################################################
613 * Verify field: not a zero value
617 function verify_nozero($field)
619 if ($this->values
["$field"] == 0)
621 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be zero'), $field);
627 // ###################################################################
629 * Verify field: not empty
633 function verify_noempty($field)
635 if (empty($this->values
["$field"]))
637 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be empty'), $field);
644 // ###################################################################
646 * Setter and getter method for the API error reporting system. Passing
647 * a name will cause the set, no arguments will cause the get.
651 * @param mixed Method name in callable form
653 * @return mixed Method name in callable form
655 function APIError($new = null
)
657 static $caller, $prev;
663 else if ($new !== null
)
672 /*=====================================================================*\
673 || ###################################################################
676 || ###################################################################
677 \*=====================================================================*/