No longer populate API->values[] in fetch()
[isso.git] / api.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]issoversion[#]
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 * Error list that has been generated
165 * @var array
166 * @access private
167 */
168 var $errors = array();
169
170 // ###################################################################
171 /**
172 * Constructor: cannot instantiate class directly
173 */
174 function __construct(&$registry)
175 {
176 if (!is_subclass_of($this, 'API'))
177 {
178 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR);
179 }
180
181 if (!is_object($registry))
182 {
183 trigger_error('The passed registry is not an object', E_USER_ERROR);
184 }
185
186 $this->registry =& $registry;
187 }
188
189 // ###################################################################
190 /**
191 * (PHP 4) Constructor
192 */
193 function API(&$registry)
194 {
195 $this->__construct($registry);
196 }
197
198 // ###################################################################
199 /**
200 * Constructs an error for the error handler to receive
201 *
202 * @access protected
203 *
204 * @param string Error message
205 */
206 function error($message)
207 {
208 $this->errors[] = $message;
209
210 // we want to explicitly specify silence
211 if (APIError() == 'silent')
212 {
213 return;
214 }
215
216 if (!is_callable(APIError()))
217 {
218 trigger_error('No APIError() handler has been set', E_USER_WARNING);
219 }
220
221 call_user_func(APIError(), $message);
222 }
223
224 // ###################################################################
225 /**
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
228 * no errors.
229 *
230 * @access public
231 *
232 * @return array Array of errors
233 */
234 function check_errors()
235 {
236 if (sizeof($this->errors) < 1)
237 {
238 return array();
239 }
240
241 return $this->errors;
242 }
243
244 // ###################################################################
245 /**
246 * Sets a value, sanitizes it, and verifies it
247 *
248 * @access public
249 *
250 * @param string Field name
251 * @param mixed Value
252 * @param bool Do clean?
253 * @param bool Do verify?
254 */
255 function set($field, $value, $doclean = true, $doverify = true)
256 {
257 if (!isset($this->fields["$field"]))
258 {
259 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
260 return;
261 }
262
263 $this->values["$field"] = ($doclean ? $this->registry->clean($value, $this->fields["$field"][F_TYPE]) : $value);
264
265 $this->setfields["$field"] = $field;
266
267 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
268 {
269 if ($this->fields["$field"][F_VERIFY] == ':self')
270 {
271 $verify = $this->{"verify_$field"}($field);
272 }
273 else
274 {
275 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
276 }
277
278 if ($verify !== true)
279 {
280 if ($verify === false)
281 {
282 $this->error(sprintf($this->registry->modules['localize']->string('Validation of %1$s failed'), $field));
283 }
284 else
285 {
286 $this->error($verify);
287 }
288 }
289 }
290 }
291
292 // ###################################################################
293 /**
294 * Sets the condition to use in the WHERE clause; if not passed, then
295 * it calculates it from the REQ_AUTO field
296 *
297 * @access public
298 *
299 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
300 */
301 function set_condition($condition = '')
302 {
303 if (is_array($condition) AND sizeof($condition) > 0)
304 {
305 $this->condition = '';
306
307 foreach ($condition AS $field)
308 {
309 if (!$this->values["$field"])
310 {
311 trigger_error('The specified field `' . $field . '` for the condition could not be found as it is not set', E_USER_WARNING);
312 continue;
313 }
314
315 $condbits[] = "$field = " . $this->prepare_field_for_sql($field);
316 }
317 $this->condition = implode(' AND ', $condbits);
318 }
319 else if ($condition != '')
320 {
321 $this->condition = $condition;
322 }
323 else
324 {
325 foreach ($this->fields AS $name => $options)
326 {
327 if ($options[F_REQ] == REQ_AUTO)
328 {
329 if (!$this->values["$name"])
330 {
331 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING);
332 continue;
333 }
334
335 $this->condition = "$name = " . $this->prepare_field_for_sql($name);
336 }
337 }
338
339 if ($this->condition == '')
340 {
341 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING);
342 }
343 }
344 }
345
346 // ###################################################################
347 /**
348 * Sets existing data into $values where it's not already present
349 *
350 * @access public
351 */
352 function set_existing()
353 {
354 static $run;
355 if ($run)
356 {
357 return;
358 }
359
360 $this->fetch();
361
362 foreach ($this->objdata AS $field => $value)
363 {
364 if (!isset($this->values["$field"]))
365 {
366 $this->values["$field"] = $value;
367 }
368 }
369
370 $run = true;
371 }
372
373 // ###################################################################
374 /**
375 * Fetches a record based on the condition
376 *
377 * @param bool Populate $this->values[] with data, along with $this->objdata[] ?
378 *
379 * @access public
380 */
381 function fetch($populate = false)
382 {
383 if ($this->condition == '')
384 {
385 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
386 }
387
388 $this->run_action_method('pre_fetch');
389
390 $result = $this->registry->modules[ISSO_DB_LAYER]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
391 if (!$result)
392 {
393 $this->error($this->registry->modules['localize']->string('No records were returned'));
394 return;
395 }
396
397 $this->run_action_method('post_fetch');
398
399 $this->objdata = $result;
400
401 if ($populate)
402 {
403 foreach ($this->objdata AS $key => $value)
404 {
405 if (!isset($this->values["$key"]))
406 {
407 $this->values["$key"] = $value;
408 }
409 }
410 }
411
412 $this->call_relations('fetch');
413 }
414
415 // ###################################################################
416 /**
417 * Inserts a record in the database
418 *
419 * @access public
420 */
421 function insert()
422 {
423 $this->verify();
424
425 $this->run_action_method('pre_insert');
426
427 foreach ($this->setfields AS $field)
428 {
429 $fields[] = $field;
430 $values[] = $this->prepare_field_for_sql($field);
431 }
432
433 $this->registry->modules[ISSO_DB_LAYER]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
434
435 if (strcasecmp(ISSO_DB_LAYER, 'DB_PostgreSQL') == 0)
436 {
437 foreach ($this->fields AS $field => $info)
438 {
439 if ($info[F_REQ] == REQ_AUTO)
440 {
441 $autofield = $field;
442 break;
443 }
444 }
445
446 $this->insertid = $this->registry->modules[ISSO_DB_LAYER]->insert_id($this->prefix . $this->table, $autofield);
447 }
448 else
449 {
450 $this->insertid = $this->registry->modules[ISSO_DB_LAYER]->insert_id();
451 }
452
453 $this->run_action_method('post_insert');
454 }
455
456 // ###################################################################
457 /**
458 * Updates a record in the database using the data in $vaues
459 *
460 * @access public
461 */
462 function update()
463 {
464 if ($this->condition == '')
465 {
466 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
467 }
468
469 $this->run_action_method('pre_update');
470
471 foreach ($this->setfields AS $field)
472 {
473 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
474 }
475 $updates = implode(', ', $updates);
476
477 $this->registry->modules[ISSO_DB_LAYER]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
478
479 $this->run_action_method('post_update');
480 }
481
482 // ###################################################################
483 /**
484 * Deletes a record
485 *
486 * @access public
487 */
488 function delete()
489 {
490 if ($this->condition == '')
491 {
492 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
493 }
494
495 $this->set_existing();
496
497 $this->run_action_method('pre_delete');
498
499 $this->registry->modules[ISSO_DB_LAYER]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
500
501 $this->run_action_method('post_delete');
502 }
503
504 // ###################################################################
505 /**
506 * Verifies that all required fields are set
507 *
508 * @access private
509 */
510 function verify()
511 {
512 foreach ($this->fields AS $name => $options)
513 {
514 if ($options[F_REQ] == REQ_YES)
515 {
516 if (!isset($this->values["$name"]))
517 {
518 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
519 }
520 }
521 else if ($options[F_REQ] == REQ_SET)
522 {
523 $this->{"set_$name"}();
524 }
525 }
526 }
527
528 // ###################################################################
529 /**
530 * Runs a pre- or post-action method for database commands
531 *
532 * @access private
533 *
534 * @param string Action to run
535 */
536 function run_action_method($method)
537 {
538 if (in_array($method, $this->norunners))
539 {
540 return;
541 }
542
543 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
544 }
545
546 // ###################################################################
547 /**
548 * Determines if it's safe to run a relation; if so, it will return
549 * the WHERE SQL clause
550 *
551 * @access public
552 *
553 * @param string Operation to run
554 */
555 function call_relations($method)
556 {
557 if (!is_array($this->dorelations) OR !in_array($method, $this->dorelations))
558 {
559 return;
560 }
561
562 foreach ($this->fields AS $field => $info)
563 {
564 $value = (isset($this->values["$field"]) ? $this->values["$field"] : $this->objdata["$field"]);
565 if ($value == null OR !is_array($info[F_RELATION]))
566 {
567 continue;
568 }
569
570 if (!file_exists($this->registry->get('apppath') . $info[F_RELATION][F_RELATION_FILE]))
571 {
572 trigger_error("Could not load the relation file for field '$field'");
573 }
574
575 require_once($this->registry->get('apppath') . $info[F_RELATION][F_RELATION_FILE]);
576
577 $this->relations["$field"] = new $info[F_RELATION][F_RELATION_CLASS]($this->registry);
578 $this->relations["$field"]->set(($info[F_RELATION][F_RELATION_ALTFIELD] ? $info[F_RELATION][F_RELATION_ALTFIELD] : $field), $value);
579 $this->relations["$field"]->set_condition();
580 $this->relations["$field"]->$method();
581 }
582 }
583
584 // ###################################################################
585 /**
586 * Prepares a value for use in a SQL query; it encases and escapes
587 * strings and string-like values
588 *
589 * @access private
590 *
591 * @param string Field name
592 *
593 * @return string Prepared value entry
594 */
595 function prepare_field_for_sql($name)
596 {
597 $type = $this->fields["$name"][F_TYPE];
598
599 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
600 {
601 return "'" . $this->registry->db->escape_string($this->values["$name"]) . "'";
602 }
603 else if ($type == TYPE_BOOL)
604 {
605 return ($this->values["$name"] == true ? "'1'" : "'0'");
606 }
607 else if ($type == TYPE_BIN)
608 {
609 return "'" . $this->registry->db->escape_binary($this->values["$name"]) . "'";
610 }
611 else
612 {
613 return $this->values["$name"];
614 }
615 }
616
617 // ###################################################################
618 /**
619 * Verify field: not a zero value
620 *
621 * @access protected
622 */
623 function verify_nozero($field)
624 {
625 if ($this->values["$field"] == 0)
626 {
627 return sprintf($this->registry->modules['localize']->string('The field "%1$s" cannot be zero'), $field);
628 }
629
630 return true;
631 }
632
633 // ###################################################################
634 /**
635 * Verify field: not empty
636 *
637 * @access protected
638 */
639 function verify_noempty($field)
640 {
641 if (empty($this->values["$field"]))
642 {
643 return sprintf($this->registry->modules['localize']->string('The field "%1$s" cannot be empty'), $field);
644 }
645
646 return true;
647 }
648 }
649
650 // ###################################################################
651 /**
652 * Setter and getter method for the API error reporting system. Passing
653 * a name will cause the set, no arguments will cause the get.
654 *
655 * @access public
656 *
657 * @param mixed Method name in callable form
658 *
659 * @return mixed Method name in callable form
660 */
661 function APIError($new = null)
662 {
663 static $caller, $prev;
664
665 if ($new === -1)
666 {
667 $caller = $prev;
668 }
669 else if ($new !== null)
670 {
671 $prev = $caller;
672 $caller = $new;
673 }
674
675 return $caller;
676 }
677
678 /*=====================================================================*\
679 || ###################################################################
680 || # $HeadURL$
681 || # $Id$
682 || ###################################################################
683 \*=====================================================================*/
684 ?>