Make sure we throw a warning if we can't call the APIError() function
[isso.git] / api.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
6 || #
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.
10 || #
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
14 || # more details.
15 || #
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 \*=====================================================================*/
21
22 /**
23 * Abstract Datamanger API
24 * api.php
25 *
26 * @package ISSO
27 */
28
29 if (!defined('REQ_AUTO'))
30 {
31 /**
32 * Auto-increasing value
33 */
34 define('REQ_AUTO', -1);
35
36 /**
37 * Set by a cusotm set_*() function
38 */
39 define('REQ_SET', 2);
40
41 /**
42 * Index for cleaning type
43 */
44 define('F_TYPE', 0);
45
46 /**
47 * Index for requirement type
48 */
49 define('F_REQ', 1);
50
51 /**
52 * Index for verification type
53 */
54 define('F_VERIFY', 2);
55 }
56
57 /**
58 * Abstract API
59 *
60 * Abstract class that is used as an API base for most common database interaction
61 * schemes. Creates a simple structure that holds data and can update, delete, and
62 * insert.
63 *
64 * @author Iris Studios, Inc.
65 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
66 * @version $Revision$
67 * @package ISSO
68 *
69 */
70 class API
71 {
72 /**
73 * Registry object
74 * @var object
75 * @access protected
76 */
77 var $registry = null;
78
79 /**
80 * Fields: used for verification and sanitization
81 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method))
82 * @var array
83 * @access protected
84 */
85 var $fields = array();
86
87 /**
88 * Values array: sanitized and verified field values
89 * @var array
90 * @access public
91 */
92 var $values = array();
93
94 /**
95 * Fields that were manually set with set(), not by using set_existing()
96 * @var array
97 * @access private
98 */
99 var $setfields = array();
100
101 /**
102 * WHERE condition
103 * @var string
104 * @access private
105 */
106 var $condition = '';
107
108 /**
109 * The object table row; a fetched row that represents this instance
110 * @var array
111 * @access public
112 */
113 var $objdata = array();
114
115 /**
116 * Insert ID from the insert() command
117 * @var integer
118 * @access public
119 */
120 var $insertid = 0;
121
122 /**
123 * Pre- and post-action method stoppers
124 * @var array
125 * @access public
126 */
127 var $norunners = array();
128
129 // ###################################################################
130 /**
131 * Constructor: cannot instantiate class directly
132 */
133 function __construct(&$registry)
134 {
135 if (!is_subclass_of($this, 'API'))
136 {
137 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR);
138 }
139
140 if (!is_object($registry))
141 {
142 trigger_error('The passed registry is not an object', E_USER_ERROR);
143 }
144
145 $this->registry =& $registry;
146 }
147
148 // ###################################################################
149 /**
150 * (PHP 4) Constructor
151 */
152 function API(&$registry)
153 {
154 $this->__construct($registry);
155 }
156
157 // ###################################################################
158 /**
159 * Constructs an error for the error handler to receive
160 *
161 * @access protected
162 *
163 * @param string Error message
164 */
165 function error($message)
166 {
167 if (!is_callable(APIError()))
168 {
169 trigger_error('No APIError() handler has been set', E_USER_WARNING);
170 }
171
172 call_user_func(APIError(), $message);
173 }
174
175 // ###################################################################
176 /**
177 * Sets a value, sanitizes it, and verifies it
178 *
179 * @access public
180 *
181 * @param string Field name
182 * @param mixed Value
183 * @param bool Do clean?
184 * @param bool Do verify?
185 */
186 function set($field, $value, $doclean = true, $doverify = true)
187 {
188 if (!isset($this->fields["$field"]))
189 {
190 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
191 return;
192 }
193
194 $this->values["$field"] = ($doclean ? $this->registry->clean($value, $this->fields["$field"][F_TYPE]) : $value);
195
196 $this->setfields["$field"] = $field;
197
198 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
199 {
200 if ($this->fields["$field"][F_VERIFY] == ':self')
201 {
202 $verify = $this->{"verify_$field"}($field);
203 }
204 else
205 {
206 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
207 }
208
209 if (!$verify)
210 {
211 $this->error(sprintf($this->registry->modules['localize']->string('Validation of %1$s failed'), $field));
212 }
213 }
214 }
215
216 // ###################################################################
217 /**
218 * Sets the condition to use in the WHERE clause; if not passed, then
219 * it calculates it from the REQ_AUTO field
220 *
221 * @access public
222 *
223 * @param string WHERE conditional bit
224 */
225 function set_condition($condition = '')
226 {
227 if ($condition != '')
228 {
229 $this->condition = $condition;
230 }
231 else
232 {
233 foreach ($this->fields AS $name => $options)
234 {
235 if ($options[F_REQ] == REQ_AUTO)
236 {
237 if (!$this->values["$name"])
238 {
239 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING);
240 continue;
241 }
242
243 $this->condition = "$name = " . $this->prepare_field_for_sql($name);
244 }
245 }
246
247 if ($this->condition == '')
248 {
249 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING);
250 }
251 }
252 }
253
254 // ###################################################################
255 /**
256 * Sets existing data into $values where it's not already present
257 *
258 * @access public
259 */
260 function set_existing()
261 {
262 static $run;
263 if ($run)
264 {
265 return;
266 }
267
268 $this->fetch();
269
270 foreach ($this->objdata AS $field => $value)
271 {
272 if (!isset($this->values["$field"]))
273 {
274 $this->values["$field"] = $value;
275 }
276 }
277
278 $run = true;
279 }
280
281 // ###################################################################
282 /**
283 * Fetches a record based on the condition
284 *
285 * @access public
286 */
287 function fetch()
288 {
289 if ($this->condition == '')
290 {
291 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
292 }
293
294 $this->run_action_method('pre_fetch');
295
296 $result = $this->registry->modules[ISSO_DB_LAYER]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
297 if (!$result)
298 {
299 $this->error($this->registry->modules['localize']->string('No records were returned'));
300 return;
301 }
302
303 $this->run_action_method('post_fetch');
304
305 $this->objdata = $result;
306 }
307
308 // ###################################################################
309 /**
310 * Inserts a record in the database
311 *
312 * @access public
313 */
314 function insert()
315 {
316 $this->verify();
317
318 $this->run_action_method('pre_insert');
319
320 foreach ($this->setfields AS $field)
321 {
322 $fields[] = $field;
323 $values[] = $this->prepare_field_for_sql($field);
324 }
325
326 $this->registry->modules[ISSO_DB_LAYER]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
327 $this->insertid = $this->registry->modules[ISSO_DB_LAYER]->insert_id();
328
329 $this->run_action_method('post_insert');
330 }
331
332 // ###################################################################
333 /**
334 * Updates a record in the database using the data in $vaues
335 *
336 * @access public
337 */
338 function update()
339 {
340 if ($this->condition == '')
341 {
342 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
343 }
344
345 $this->run_action_method('pre_update');
346
347 foreach ($this->setfields AS $field)
348 {
349 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
350 }
351 $updates = implode(', ', $updates);
352
353 $this->registry->modules[ISSO_DB_LAYER]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
354
355 $this->run_action_method('post_update');
356 }
357
358 // ###################################################################
359 /**
360 * Deletes a record
361 *
362 * @access public
363 */
364 function delete()
365 {
366 if ($this->condition == '')
367 {
368 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
369 }
370
371 $this->set_existing();
372
373 $this->run_action_method('pre_delete');
374
375 $this->registry->modules[ISSO_DB_LAYER]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
376
377 $this->run_action_method('post_delete');
378 }
379
380 // ###################################################################
381 /**
382 * Verifies that all required fields are set
383 *
384 * @access private
385 */
386 function verify()
387 {
388 foreach ($this->fields AS $name => $options)
389 {
390 if ($options[F_REQ] == REQ_YES)
391 {
392 if (!isset($this->values["$name"]))
393 {
394 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
395 }
396 }
397 else if ($options[F_REQ] == REQ_SET)
398 {
399 $this->{"set_$name"}();
400 }
401 }
402 }
403
404 // ###################################################################
405 /**
406 * Runs a pre- or post-action method for database commands
407 *
408 * @access private
409 *
410 * @param string Action to run
411 */
412 function run_action_method($method)
413 {
414 if (in_array($method, $this->norunners))
415 {
416 return;
417 }
418
419 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
420 }
421
422 // ###################################################################
423 /**
424 * Prepares a value for use in a SQL query; it encases and escapes
425 * strings and string-like values
426 *
427 * @access private
428 *
429 * @param string Field name
430 *
431 * @return string Prepared value entry
432 */
433 function prepare_field_for_sql($name)
434 {
435 $type = $this->fields["$name"][F_TYPE];
436
437 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
438 {
439 return "'" . $this->registry->escape($this->values["$name"]) . "'";
440 }
441 else if ($type == TYPE_BOOL)
442 {
443 return (int)$this->values["$name"];
444 }
445 else
446 {
447 return $this->values["$name"];
448 }
449 }
450
451 // ###################################################################
452 /**
453 * Verify field: not a zero value
454 *
455 * @access protected
456 */
457 function verify_nozero($field)
458 {
459 if ($this->values["$field"] == 0)
460 {
461 return false;
462 }
463
464 return true;
465 }
466
467 // ###################################################################
468 /**
469 * Verify field: not empty
470 *
471 * @access protected
472 */
473 function verify_noempty($field)
474 {
475 if (empty($this->values["$field"]))
476 {
477 return false;
478 }
479
480 return true;
481 }
482 }
483
484 // ###################################################################
485 /**
486 * Setter and getter method for the API error reporting system. Passing
487 * a name will cause the set, no arguments will cause the get.
488 *
489 * @access public
490 *
491 * @param mixed Method name in callable form
492 *
493 * @return mixed Method name in callable form
494 */
495 function APIError($new = null)
496 {
497 static $caller;
498
499 if ($new !== null)
500 {
501 $caller = $new;
502 }
503
504 return $caller;
505 }
506
507 /*=====================================================================*\
508 || ###################################################################
509 || # $HeadURL$
510 || # $Id$
511 || ###################################################################
512 \*=====================================================================*/
513 ?>