Cleaing up error reporting and error triggering in Api.php
[isso.git] / Api.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2002-2007 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 2 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 /**
67 * Abstract API
68 *
69 * Abstract class that is used as an API base for most common database interaction
70 * schemes. Creates a simple structure that holds data and can update, remove, and
71 * insert.
72 *
73 * @author Blue Static
74 * @copyright Copyright (c)2002 - 2007, Blue Static
75 * @package ISSO
76 *
77 */
78 abstract class BSApi
79 {
80 /**
81 * The callback function for the error handler
82 * @var string
83 */
84 public static $errorHandler;
85
86 /**
87 * Fields: used for verification and sanitization
88 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
89 * @var array
90 */
91 protected $fields = array();
92
93 /**
94 * Values array: sanitized and verified field values
95 * @var array
96 */
97 public $values = array();
98
99 /**
100 * Fields that were manually set with set(), not by using setExisting()
101 * @var array
102 */
103 private $setfields = array();
104
105 /**
106 * WHERE condition
107 * @var string
108 */
109 private $condition = '';
110
111 /**
112 * The object table row; a fetched row that represents this instance
113 * @var array
114 */
115 public $objdata = array();
116
117 /**
118 * Insert ID from the insert() command
119 * @var integer
120 */
121 public $insertid = 0;
122
123 /**
124 * Error queue that builds up errors
125 * @var array
126 */
127 private $errors = array();
128
129 // ###################################################################
130 /**
131 * Constructor: cannot instantiate class directly
132 */
133 public function __construct()
134 {
135 BSApp::RequiredModules(array('Db', 'Input'));
136 }
137
138 // ###################################################################
139 /**
140 * Adds an error into the error queue that is then hit
141 *
142 * @param string Error message
143 */
144 protected function _error($message)
145 {
146 $this->errors[] = $message;
147 }
148
149 // ###################################################################
150 /**
151 * This runs through all the errors in the error queue and processes
152 * them all at once. Error builders then get a list of all the errors,
153 * and die-by-hit callbacks stop at the first one
154 *
155 * @param string A string param
156 *
157 * @return integer Return value
158 */
159 private function _processErrorQueue()
160 {
161 // we want to explicitly specify silence
162 if (self::$errorHandler == 'silent')
163 {
164 return;
165 }
166
167 if (!is_callable(self::$errorHandler))
168 {
169 throw new Exception('No BSApi::$errorHandler handler has been set');
170 }
171
172 foreach ($this->errors AS $e)
173 {
174 call_user_func(BSApi::$errorHandler, $e);
175 }
176 }
177
178 // ###################################################################
179 /**
180 * Returns the error list. This is because we don't want people mucking
181 * with the error system. It will return an empty array if there are
182 * no errors.
183 *
184 * @return array Array of errors
185 */
186 public function checkErrors()
187 {
188 if (sizeof($this->errors) < 1)
189 {
190 return array();
191 }
192
193 return $this->errors;
194 }
195
196 // ###################################################################
197 /**
198 * Sets a value, sanitizes it, and verifies it
199 *
200 * @param string Field name
201 * @param mixed Value
202 * @param bool Do clean?
203 * @param bool Do verify?
204 */
205 public function set($field, $value, $doclean = true, $doverify = true)
206 {
207 if (!isset($this->fields["$field"]))
208 {
209 throw new Exception('Field "' . $field . '" is not valid');
210 return;
211 }
212
213 $this->values["$field"] = ($doclean ? BSApp::GetType('Input')->clean($value, $this->fields["$field"][F_TYPE]) : $value);
214
215 $this->setfields["$field"] = $field;
216
217 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
218 {
219 if ($this->fields["$field"][F_VERIFY] == ':self')
220 {
221 $verify = $this->{"verify_$field"}($field);
222 }
223 else
224 {
225 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
226 }
227
228 if ($verify !== true)
229 {
230 if ($verify === false)
231 {
232 $this->_error(sprintf(_('Validation of "%1$s" failed'), $field));
233 }
234 else
235 {
236 $this->_error($verify);
237 }
238 }
239 }
240 }
241
242 // ###################################################################
243 /**
244 * Sets the condition to use in the WHERE clause; if not passed, then
245 * it calculates it from the REQ_AUTO field
246 *
247 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
248 */
249 public function setCondition($condition = '')
250 {
251 if (is_array($condition) AND sizeof($condition) > 0)
252 {
253 $this->condition = '';
254
255 foreach ($condition AS $field)
256 {
257 if (!$this->values["$field"])
258 {
259 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
260 continue;
261 }
262
263 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
264 }
265 $this->condition = implode(' AND ', $condbits);
266 }
267 else if ($condition != '')
268 {
269 $this->condition = $condition;
270 }
271 else
272 {
273 foreach ($this->fields AS $name => $options)
274 {
275 if ($options[F_REQ] == REQ_AUTO)
276 {
277 if (!$this->values["$name"])
278 {
279 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
280 continue;
281 }
282
283 $this->condition = "$name = " . $this->_prepareFieldForSql($name);
284 }
285 }
286
287 if ($this->condition == '')
288 {
289 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
290 }
291 }
292 }
293
294 // ###################################################################
295 /**
296 * Sets existing data into $values where it's not already present
297 */
298 public function setExisting()
299 {
300 static $run;
301 if ($run)
302 {
303 return;
304 }
305
306 $this->fetch();
307
308 foreach ($this->objdata AS $field => $value)
309 {
310 if (!isset($this->values["$field"]))
311 {
312 $this->values["$field"] = $value;
313 }
314 }
315
316 $run = true;
317 }
318
319 // ###################################################################
320 /**
321 * Fetches a record based on the condition
322 *
323 * @param bool Run pre_fetch()?
324 * @param bool Run post_fetch()?
325 *
326 * @return boolean Whether or not the row was successfully fetched
327 */
328 public function fetch($doPre = true, $doPost = true)
329 {
330 if ($this->condition == '')
331 {
332 $this->setCondition();
333 }
334
335 // reset the error queue due to any validation errors caused by fetchable fields
336 $this->errors = array();
337
338 $this->_runActionMethod('pre_fetch', $doPre);
339
340 $result = BSApp::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
341 if (!$result)
342 {
343 return false;
344 }
345
346 $this->_runActionMethod('post_fetch', $doPost);
347
348 $this->objdata = $result;
349
350 return true;
351 }
352
353 // ###################################################################
354 /**
355 * Inserts a record in the database
356 *
357 * @param bool Run pre_insert()?
358 * @param bool Run post_insert()?
359 */
360 public function insert($doPre = true, $doPost = true)
361 {
362 $this->verify();
363 $this->_processErrorQueue();
364
365 $this->_runActionMethod('pre_insert', $doPre);
366
367 foreach ($this->setfields AS $field)
368 {
369 $fields[] = $field;
370 $values[] = $this->_prepareFieldForSql($field);
371 }
372
373 BSApp::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
374
375 if (BSApp::GetType('DbPostgreSql'))
376 {
377 foreach ($this->fields AS $field => $info)
378 {
379 if ($info[F_REQ] == REQ_AUTO)
380 {
381 $autofield = $field;
382 break;
383 }
384 }
385
386 $this->insertid = BSApp::GetType('Db')->insertId($this->prefix . $this->table, $autofield);
387 }
388 else
389 {
390 $this->insertid = BSApp::GetType('Db')->insertId();
391 }
392
393 $this->_runActionMethod('post_insert', $doPost);
394 }
395
396 // ###################################################################
397 /**
398 * Updates a record in the database using the data in $vaues
399 *
400 * @param bool Run pre_update()?
401 * @param bool Run post_update()?
402 */
403 public function update($doPre = true, $doPost = true)
404 {
405 if ($this->condition == '')
406 {
407 $this->setCondition();
408 }
409
410 $this->_processErrorQueue();
411
412 $this->_runActionMethod('pre_update', $doPre);
413
414 foreach ($this->setfields AS $field)
415 {
416 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
417 }
418 $updates = implode(', ', $updates);
419
420 BSApp::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
421
422 $this->_runActionMethod('post_update', $doPost);
423 }
424
425 // ###################################################################
426 /**
427 * Deletes a record
428 *
429 * @param bool Run pre_remove()?
430 * @param bool Run post_remove()?
431 */
432 public function remove($doPre = true, $doPost = true)
433 {
434 if ($this->condition == '')
435 {
436 $this->setCondition();
437 }
438
439 $this->fetch();
440
441 $this->_runActionMethod('pre_remove', $doPre);
442
443 BSApp::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
444
445 $this->_runActionMethod('post_remove', $doPost);
446 }
447
448 // ###################################################################
449 /**
450 * Verifies that all required fields are set
451 */
452 private function verify()
453 {
454 foreach ($this->fields AS $name => $options)
455 {
456 if ($options[F_REQ] == REQ_YES)
457 {
458 if (!isset($this->values["$name"]))
459 {
460 $this->_error(sprintf(_('The required field "%1$s" was not set'), $name));
461 }
462 }
463 else if ($options[F_REQ] == REQ_SET)
464 {
465 $this->{"set_$name"}();
466 }
467 }
468 }
469
470 // ###################################################################
471 /**
472 * Runs a pre- or post-action method for database commands
473 *
474 * @param string Action to run
475 * @param bool Actually run it?
476 */
477 private function _runActionMethod($method, $doRun)
478 {
479 if (!$doRun)
480 {
481 return;
482 }
483
484 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
485 }
486
487 // ###################################################################
488 /**
489 * Prepares a value for use in a SQL query; it encases and escapes
490 * strings and string-like values
491 *
492 * @param string Field name
493 *
494 * @return string Prepared value entry
495 */
496 private function _prepareFieldForSql($name)
497 {
498 $type = $this->fields["$name"][F_TYPE];
499
500 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
501 {
502 return "'" . BSApp::GetType('Db')->escapeString($this->values["$name"]) . "'";
503 }
504 else if ($type == TYPE_BOOL)
505 {
506 return ($this->values["$name"] == true ? "'1'" : "'0'");
507 }
508 else if ($type == TYPE_BIN)
509 {
510 return "'" . BSApp::GetType('Db')->escapeBinary($this->values["$name"]) . "'";
511 }
512 else
513 {
514 return $this->values["$name"];
515 }
516 }
517
518 // ###################################################################
519 /**
520 * Verify field: not a zero value
521 */
522 protected function verify_nozero($field)
523 {
524 if ($this->values["$field"] == 0)
525 {
526 return sprintf(_('The field "%1$s" cannot be zero'), $field);
527 }
528
529 return true;
530 }
531
532 // ###################################################################
533 /**
534 * Verify field: not empty
535 */
536 protected function verify_noempty($field)
537 {
538 if (empty($this->values["$field"]))
539 {
540 return sprintf(_('The field "%1$s" cannot be empty'), $field);
541 }
542
543 return true;
544 }
545
546 // ###################################################################
547 /**
548 * Verify field: unique
549 */
550 protected function verify_unique($field)
551 {
552 $res = BSApp::GetType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
553 if ($res)
554 {
555 return sprintf(_('The "%1$s" field must contain a unique value'), $field);
556 }
557
558 return true;
559 }
560 }
561
562 ?>