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