Change API->norelations to API->dorelations so we have to explictly choose the ones
[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 * Index for relation
58 */
59 define('F_RELATION', 3);
60
61 /**
62 * Relation index for file name, relative to ISSO->apppath
63 */
64 define('F_RELATION_FILE', 0);
65
66 /**
67 * Relation index for class name
68 */
69 define('F_RELATION_CLASS', 1);
70
71 /**
72 * Relation index for field-link alternate name
73 */
74 define('F_RELATION_ALTFIELD', 2);
75 }
76
77 /**
78 * Abstract API
79 *
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
82 * insert.
83 *
84 * @author Iris Studios, Inc.
85 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
86 * @version $Revision$
87 * @package ISSO
88 *
89 */
90 class API
91 {
92 /**
93 * Registry object
94 * @var object
95 * @access protected
96 */
97 var $registry = null;
98
99 /**
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))
102 * @var array
103 * @access protected
104 */
105 var $fields = array();
106
107 /**
108 * Values array: sanitized and verified field values
109 * @var array
110 * @access public
111 */
112 var $values = array();
113
114 /**
115 * Fields that were manually set with set(), not by using set_existing()
116 * @var array
117 * @access private
118 */
119 var $setfields = array();
120
121 /**
122 * An array of all of the processed relations on an object
123 * @var array
124 * @access public
125 */
126 var $relations = array();
127
128 /**
129 * WHERE condition
130 * @var string
131 * @access private
132 */
133 var $condition = '';
134
135 /**
136 * The object table row; a fetched row that represents this instance
137 * @var array
138 * @access public
139 */
140 var $objdata = array();
141
142 /**
143 * Insert ID from the insert() command
144 * @var integer
145 * @access public
146 */
147 var $insertid = 0;
148
149 /**
150 * Pre- and post-action method stoppers
151 * @var array
152 * @access public
153 */
154 var $norunners = array();
155
156 /**
157 * The relations to execute on
158 * @var array
159 * @access public
160 */
161 var $dorelations = array('fetch');
162
163 // ###################################################################
164 /**
165 * Constructor: cannot instantiate class directly
166 */
167 function __construct(&$registry)
168 {
169 if (!is_subclass_of($this, 'API'))
170 {
171 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR);
172 }
173
174 if (!is_object($registry))
175 {
176 trigger_error('The passed registry is not an object', E_USER_ERROR);
177 }
178
179 $this->registry =& $registry;
180 }
181
182 // ###################################################################
183 /**
184 * (PHP 4) Constructor
185 */
186 function API(&$registry)
187 {
188 $this->__construct($registry);
189 }
190
191 // ###################################################################
192 /**
193 * Constructs an error for the error handler to receive
194 *
195 * @access protected
196 *
197 * @param string Error message
198 */
199 function error($message)
200 {
201 if (!is_callable(APIError()))
202 {
203 trigger_error('No APIError() handler has been set', E_USER_WARNING);
204 }
205
206 call_user_func(APIError(), $message);
207 }
208
209 // ###################################################################
210 /**
211 * Sets a value, sanitizes it, and verifies it
212 *
213 * @access public
214 *
215 * @param string Field name
216 * @param mixed Value
217 * @param bool Do clean?
218 * @param bool Do verify?
219 */
220 function set($field, $value, $doclean = true, $doverify = true)
221 {
222 if (!isset($this->fields["$field"]))
223 {
224 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
225 return;
226 }
227
228 $this->values["$field"] = ($doclean ? $this->registry->clean($value, $this->fields["$field"][F_TYPE]) : $value);
229
230 $this->setfields["$field"] = $field;
231
232 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
233 {
234 if ($this->fields["$field"][F_VERIFY] == ':self')
235 {
236 $verify = $this->{"verify_$field"}($field);
237 }
238 else
239 {
240 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
241 }
242
243 if (!$verify)
244 {
245 $this->error(sprintf($this->registry->modules['localize']->string('Validation of %1$s failed'), $field));
246 }
247 }
248 }
249
250 // ###################################################################
251 /**
252 * Sets the condition to use in the WHERE clause; if not passed, then
253 * it calculates it from the REQ_AUTO field
254 *
255 * @access public
256 *
257 * @param string WHERE conditional bit
258 */
259 function set_condition($condition = '')
260 {
261 if ($condition != '')
262 {
263 $this->condition = $condition;
264 }
265 else
266 {
267 foreach ($this->fields AS $name => $options)
268 {
269 if ($options[F_REQ] == REQ_AUTO)
270 {
271 if (!$this->values["$name"])
272 {
273 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING);
274 continue;
275 }
276
277 $this->condition = "$name = " . $this->prepare_field_for_sql($name);
278 }
279 }
280
281 if ($this->condition == '')
282 {
283 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING);
284 }
285 }
286 }
287
288 // ###################################################################
289 /**
290 * Sets existing data into $values where it's not already present
291 *
292 * @access public
293 */
294 function set_existing()
295 {
296 static $run;
297 if ($run)
298 {
299 return;
300 }
301
302 $this->fetch();
303
304 foreach ($this->objdata AS $field => $value)
305 {
306 if (!isset($this->values["$field"]))
307 {
308 $this->values["$field"] = $value;
309 }
310 }
311
312 $run = true;
313 }
314
315 // ###################################################################
316 /**
317 * Fetches a record based on the condition
318 *
319 * @access public
320 */
321 function fetch()
322 {
323 if ($this->condition == '')
324 {
325 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
326 }
327
328 $this->run_action_method('pre_fetch');
329
330 $result = $this->registry->modules[ISSO_DB_LAYER]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
331 if (!$result)
332 {
333 $this->error($this->registry->modules['localize']->string('No records were returned'));
334 return;
335 }
336
337 $this->run_action_method('post_fetch');
338
339 $this->objdata = $result;
340
341 $this->call_relations('fetch');
342 }
343
344 // ###################################################################
345 /**
346 * Inserts a record in the database
347 *
348 * @access public
349 */
350 function insert()
351 {
352 $this->verify();
353
354 $this->run_action_method('pre_insert');
355
356 foreach ($this->setfields AS $field)
357 {
358 $fields[] = $field;
359 $values[] = $this->prepare_field_for_sql($field);
360 }
361
362 $this->registry->modules[ISSO_DB_LAYER]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
363 $this->insertid = $this->registry->modules[ISSO_DB_LAYER]->insert_id();
364
365 $this->run_action_method('post_insert');
366 }
367
368 // ###################################################################
369 /**
370 * Updates a record in the database using the data in $vaues
371 *
372 * @access public
373 */
374 function update()
375 {
376 if ($this->condition == '')
377 {
378 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
379 }
380
381 $this->run_action_method('pre_update');
382
383 foreach ($this->setfields AS $field)
384 {
385 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
386 }
387 $updates = implode(', ', $updates);
388
389 $this->registry->modules[ISSO_DB_LAYER]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
390
391 $this->run_action_method('post_update');
392 }
393
394 // ###################################################################
395 /**
396 * Deletes a record
397 *
398 * @access public
399 */
400 function delete()
401 {
402 if ($this->condition == '')
403 {
404 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
405 }
406
407 $this->set_existing();
408
409 $this->run_action_method('pre_delete');
410
411 $this->registry->modules[ISSO_DB_LAYER]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
412
413 $this->run_action_method('post_delete');
414 }
415
416 // ###################################################################
417 /**
418 * Verifies that all required fields are set
419 *
420 * @access private
421 */
422 function verify()
423 {
424 foreach ($this->fields AS $name => $options)
425 {
426 if ($options[F_REQ] == REQ_YES)
427 {
428 if (!isset($this->values["$name"]))
429 {
430 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
431 }
432 }
433 else if ($options[F_REQ] == REQ_SET)
434 {
435 $this->{"set_$name"}();
436 }
437 }
438 }
439
440 // ###################################################################
441 /**
442 * Runs a pre- or post-action method for database commands
443 *
444 * @access private
445 *
446 * @param string Action to run
447 */
448 function run_action_method($method)
449 {
450 if (in_array($method, $this->norunners))
451 {
452 return;
453 }
454
455 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
456 }
457
458 // ###################################################################
459 /**
460 * Determines if it's safe to run a relation; if so, it will return
461 * the WHERE SQL clause
462 *
463 * @access public
464 *
465 * @param string Field name
466 * @param string Operation to run
467 */
468 function call_relations($method)
469 {
470 if (!in_array($method, $this->dorelations))
471 {
472 return;
473 }
474
475 foreach ($this->fields AS $field => $info)
476 {
477 $value = (isset($this->values["$field"]) ? $this->values["$field"] : $this->objdata["$field"]);
478 if ($value == null OR !is_array($info[F_RELATION]))
479 {
480 continue;
481 }
482
483 if (!file_exists($this->registry->get('apppath') . $info[F_RELATION][F_RELATION_FILE]))
484 {
485 trigger_error("Could not load the relation file for field '$field'");
486 }
487
488 require_once($this->registry->get('apppath') . $info[F_RELATION][F_RELATION_FILE]);
489
490 $this->relations["$field"] = new $info[F_RELATION][F_RELATION_CLASS]($this->registry);
491 $this->relations["$field"]->set(($info[F_RELATION][F_RELATION_ALTFIELD] ? $info[F_RELATION][F_RELATION_ALTFIELD] : $field), $value);
492 $this->relations["$field"]->set_condition();
493 $this->relations["$field"]->$method();
494 }
495 }
496
497 // ###################################################################
498 /**
499 * Prepares a value for use in a SQL query; it encases and escapes
500 * strings and string-like values
501 *
502 * @access private
503 *
504 * @param string Field name
505 *
506 * @return string Prepared value entry
507 */
508 function prepare_field_for_sql($name)
509 {
510 $type = $this->fields["$name"][F_TYPE];
511
512 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
513 {
514 return "'" . $this->registry->escape($this->values["$name"]) . "'";
515 }
516 else if ($type == TYPE_BOOL)
517 {
518 return (int)$this->values["$name"];
519 }
520 else
521 {
522 return $this->values["$name"];
523 }
524 }
525
526 // ###################################################################
527 /**
528 * Verify field: not a zero value
529 *
530 * @access protected
531 */
532 function verify_nozero($field)
533 {
534 if ($this->values["$field"] == 0)
535 {
536 return false;
537 }
538
539 return true;
540 }
541
542 // ###################################################################
543 /**
544 * Verify field: not empty
545 *
546 * @access protected
547 */
548 function verify_noempty($field)
549 {
550 if (empty($this->values["$field"]))
551 {
552 return false;
553 }
554
555 return true;
556 }
557 }
558
559 // ###################################################################
560 /**
561 * Setter and getter method for the API error reporting system. Passing
562 * a name will cause the set, no arguments will cause the get.
563 *
564 * @access public
565 *
566 * @param mixed Method name in callable form
567 *
568 * @return mixed Method name in callable form
569 */
570 function APIError($new = null)
571 {
572 static $caller;
573
574 if ($new !== null)
575 {
576 $caller = $new;
577 }
578
579 return $caller;
580 }
581
582 /*=====================================================================*\
583 || ###################################################################
584 || # $HeadURL$
585 || # $Id$
586 || ###################################################################
587 \*=====================================================================*/
588 ?>