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