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