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