2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]issoversion[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
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
84 * @author Iris Studios, Inc.
85 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
100 * Fields: used for verification and sanitization
101 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
105 var $fields = array();
108 * Values array: sanitized and verified field values
112 var $values = array();
115 * Fields that were manually set with set(), not by using set_existing()
119 var $setfields = array();
122 * An array of all of the processed relations on an object
126 var $relations = array();
136 * The object table row; a fetched row that represents this instance
140 var $objdata = array();
143 * Insert ID from the insert() command
150 * Pre- and post-action method stoppers
154 var $norunners = array();
157 * The relations to execute on
161 var $dorelations = array('fetch');
164 * Error list that has been generated
168 var $errors = array();
170 // ###################################################################
172 * Constructor: cannot instantiate class directly
174 function __construct(&$registry)
176 if (!is_subclass_of($this, 'API'))
178 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR
);
181 if (!is_object($registry))
183 trigger_error('The passed registry is not an object', E_USER_ERROR
);
186 $this->registry
=& $registry;
189 // ###################################################################
191 * (PHP 4) Constructor
193 function API(&$registry)
195 $this->__construct($registry);
198 // ###################################################################
200 * Constructs an error for the error handler to receive
204 * @param string Error message
206 function error($message)
208 $this->errors
[] = $message;
210 // we want to explicitly specify silence
211 if (APIError() == 'silent')
216 if (!is_callable(APIError()))
218 trigger_error('No APIError() handler has been set', E_USER_WARNING
);
221 call_user_func(APIError(), $message);
224 // ###################################################################
226 * Returns the error list. This is because we don't want people mucking
227 * with the error system. It will return an empty array if there are
232 * @return array Array of errors
234 function check_errors()
236 if (sizeof($this->errors
) < 1)
241 return $this->errors
;
244 // ###################################################################
246 * Sets a value, sanitizes it, and verifies it
250 * @param string Field name
252 * @param bool Do clean?
253 * @param bool Do verify?
255 function set($field, $value, $doclean = true
, $doverify = true
)
257 if (!isset($this->fields
["$field"]))
259 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING
);
263 $this->values
["$field"] = ($doclean ?
$this->registry
->clean($value, $this->fields
["$field"][F_TYPE
]) : $value);
265 $this->setfields
["$field"] = $field;
267 if (isset($this->fields
["$field"][F_VERIFY
]) AND $doverify)
269 if ($this->fields
["$field"][F_VERIFY
] == ':self')
271 $verify = $this->{"verify_$field"}($field);
275 $verify = $this->{$this->fields
["$field"][F_VERIFY
]}($field);
278 if ($verify !== true
)
280 if ($verify === false
)
282 $this->error(sprintf($this->registry
->modules
['localize']->string('Validation of %1$s failed'), $field));
286 $this->error($verify);
292 // ###################################################################
294 * Sets the condition to use in the WHERE clause; if not passed, then
295 * it calculates it from the REQ_AUTO field
299 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
301 function set_condition($condition = '')
303 if (is_array($condition) AND sizeof($condition) > 0)
305 $this->condition
= '';
307 foreach ($condition AS $field)
309 if (!$this->values
["$field"])
311 trigger_error('The specified field `' . $field . '` for the condition could not be found as it is not set', E_USER_WARNING
);
315 $condbits[] = "$field = " . $this->prepare_field_for_sql($field);
317 $this->condition
= implode(' AND ', $condbits);
319 else if ($condition != '')
321 $this->condition
= $condition;
325 foreach ($this->fields
AS $name => $options)
327 if ($options[F_REQ
] == REQ_AUTO
)
329 if (!$this->values
["$name"])
331 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING
);
335 $this->condition
= "$name = " . $this->prepare_field_for_sql($name);
339 if ($this->condition
== '')
341 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING
);
346 // ###################################################################
348 * Sets existing data into $values where it's not already present
352 function set_existing()
362 foreach ($this->objdata
AS $field => $value)
364 if (!isset($this->values
["$field"]))
366 $this->values
["$field"] = $value;
373 // ###################################################################
375 * Fetches a record based on the condition
381 if ($this->condition
== '')
383 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR
);
386 $this->run_action_method('pre_fetch');
388 $result = $this->registry
->modules
[ISSO_DB_LAYER
]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
391 $this->error($this->registry
->modules
['localize']->string('No records were returned'));
395 $this->run_action_method('post_fetch');
397 $this->objdata
= $result;
399 foreach ($this->objdata
AS $key => $value)
401 if (!isset($this->values
["$key"]))
403 $this->values
["$key"] = $value;
407 $this->call_relations('fetch');
410 // ###################################################################
412 * Inserts a record in the database
420 $this->run_action_method('pre_insert');
422 foreach ($this->setfields
AS $field)
425 $values[] = $this->prepare_field_for_sql($field);
428 $this->registry
->modules
[ISSO_DB_LAYER
]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
430 if (strcasecmp(ISSO_DB_LAYER
, 'DB_PostgreSQL') == 0)
432 foreach ($this->fields
AS $field => $info)
434 if ($info[F_REQ
] == REQ_AUTO
)
441 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id($this->prefix
. $this->table
, $autofield);
445 $this->insertid
= $this->registry
->modules
[ISSO_DB_LAYER
]->insert_id();
448 $this->run_action_method('post_insert');
451 // ###################################################################
453 * Updates a record in the database using the data in $vaues
459 if ($this->condition
== '')
461 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR
);
464 $this->run_action_method('pre_update');
466 foreach ($this->setfields
AS $field)
468 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
470 $updates = implode(', ', $updates);
472 $this->registry
->modules
[ISSO_DB_LAYER
]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
474 $this->run_action_method('post_update');
477 // ###################################################################
485 if ($this->condition
== '')
487 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR
);
490 $this->set_existing();
492 $this->run_action_method('pre_delete');
494 $this->registry
->modules
[ISSO_DB_LAYER
]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
496 $this->run_action_method('post_delete');
499 // ###################################################################
501 * Verifies that all required fields are set
507 foreach ($this->fields
AS $name => $options)
509 if ($options[F_REQ
] == REQ_YES
)
511 if (!isset($this->values
["$name"]))
513 $this->error(sprintf($this->registry
->modules
['localize']->string('Required field %1$s was not set'), $name));
516 else if ($options[F_REQ
] == REQ_SET
)
518 $this->{"set_$name"}();
523 // ###################################################################
525 * Runs a pre- or post-action method for database commands
529 * @param string Action to run
531 function run_action_method($method)
533 if (in_array($method, $this->norunners
))
538 $actmethod = (method_exists($this, $method) ?
$this->$method() : '');
541 // ###################################################################
543 * Determines if it's safe to run a relation; if so, it will return
544 * the WHERE SQL clause
548 * @param string Operation to run
550 function call_relations($method)
552 if (!is_array($this->dorelations
) OR !in_array($method, $this->dorelations
))
557 foreach ($this->fields
AS $field => $info)
559 $value = (isset($this->values
["$field"]) ?
$this->values
["$field"] : $this->objdata
["$field"]);
560 if ($value == null
OR !is_array($info[F_RELATION
]))
565 if (!file_exists($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]))
567 trigger_error("Could not load the relation file for field '$field'");
570 require_once($this->registry
->get('apppath') . $info[F_RELATION
][F_RELATION_FILE
]);
572 $this->relations
["$field"] = new $info[F_RELATION
][F_RELATION_CLASS
]($this->registry
);
573 $this->relations
["$field"]->set(($info[F_RELATION
][F_RELATION_ALTFIELD
] ?
$info[F_RELATION
][F_RELATION_ALTFIELD
] : $field), $value);
574 $this->relations
["$field"]->set_condition();
575 $this->relations
["$field"]->$method();
579 // ###################################################################
581 * Prepares a value for use in a SQL query; it encases and escapes
582 * strings and string-like values
586 * @param string Field name
588 * @return string Prepared value entry
590 function prepare_field_for_sql($name)
592 $type = $this->fields
["$name"][F_TYPE
];
594 if ($type == TYPE_NOCLEAN
OR $type == TYPE_STR
OR $type == TYPE_STRUN
)
596 return "'" . $this->registry
->escape($this->values
["$name"]) . "'";
598 else if ($type == TYPE_BOOL
)
600 return ($this->values
["$name"] == true ?
"'1'" : "'0'");
604 return $this->values
["$name"];
608 // ###################################################################
610 * Verify field: not a zero value
614 function verify_nozero($field)
616 if ($this->values
["$field"] == 0)
618 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be zero'), $field);
624 // ###################################################################
626 * Verify field: not empty
630 function verify_noempty($field)
632 if (empty($this->values
["$field"]))
634 return sprintf($this->registry
->modules
['localize']->string('The field "%1$s" cannot be empty'), $field);
641 // ###################################################################
643 * Setter and getter method for the API error reporting system. Passing
644 * a name will cause the set, no arguments will cause the get.
648 * @param mixed Method name in callable form
650 * @return mixed Method name in callable form
652 function APIError($new = null
)
654 static $caller, $prev;
660 else if ($new !== null
)
669 /*=====================================================================*\
670 || ###################################################################
673 || ###################################################################
674 \*=====================================================================*/