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