Renaming BSRegister to BSApp and moving Register.php to App.php
[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 BSApp::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 ? BSApp::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 = BSApp::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 return true;
346 }
347
348 // ###################################################################
349 /**
350 * Inserts a record in the database
351 *
352 * @param bool Run pre_insert()?
353 * @param bool Run post_insert()?
354 */
355 public function insert($doPre = true, $doPost = true)
356 {
357 $this->verify();
358 $this->_processErrorQueue();
359
360 $this->_runActionMethod('pre_insert', $doPre);
361
362 foreach ($this->setfields AS $field)
363 {
364 $fields[] = $field;
365 $values[] = $this->_prepareFieldForSql($field);
366 }
367
368 BSApp::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
369
370 if (BSApp::GetType('DbPostgreSql'))
371 {
372 foreach ($this->fields AS $field => $info)
373 {
374 if ($info[F_REQ] == REQ_AUTO)
375 {
376 $autofield = $field;
377 break;
378 }
379 }
380
381 $this->insertid = BSApp::GetType('Db')->insertId($this->prefix . $this->table, $autofield);
382 }
383 else
384 {
385 $this->insertid = BSApp::GetType('Db')->insertId();
386 }
387
388 $this->_runActionMethod('post_insert', $doPost);
389 }
390
391 // ###################################################################
392 /**
393 * Updates a record in the database using the data in $vaues
394 *
395 * @param bool Run pre_update()?
396 * @param bool Run post_update()?
397 */
398 public function update($doPre = true, $doPost = true)
399 {
400 if ($this->condition == '')
401 {
402 $this->setCondition();
403 }
404
405 $this->_processErrorQueue();
406
407 $this->_runActionMethod('pre_update', $doPre);
408
409 foreach ($this->setfields AS $field)
410 {
411 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
412 }
413 $updates = implode(', ', $updates);
414
415 BSApp::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
416
417 $this->_runActionMethod('post_update', $doPost);
418 }
419
420 // ###################################################################
421 /**
422 * Deletes a record
423 *
424 * @param bool Run pre_remove()?
425 * @param bool Run post_remove()?
426 */
427 public function remove($doPre = true, $doPost = true)
428 {
429 if ($this->condition == '')
430 {
431 $this->setCondition();
432 }
433
434 $this->fetch();
435
436 $this->_runActionMethod('pre_remove', $doPre);
437
438 BSApp::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
439
440 $this->_runActionMethod('post_remove', $doPost);
441 }
442
443 // ###################################################################
444 /**
445 * Verifies that all required fields are set
446 */
447 private function verify()
448 {
449 foreach ($this->fields AS $name => $options)
450 {
451 if ($options[F_REQ] == REQ_YES)
452 {
453 if (!isset($this->values["$name"]))
454 {
455 $this->_error(sprintf(_('The required field "%1$s" was not set'), $name));
456 }
457 }
458 else if ($options[F_REQ] == REQ_SET)
459 {
460 $this->{"set_$name"}();
461 }
462 }
463 }
464
465 // ###################################################################
466 /**
467 * Runs a pre- or post-action method for database commands
468 *
469 * @param string Action to run
470 * @param bool Actually run it?
471 */
472 private function _runActionMethod($method, $doRun)
473 {
474 if (!$doRun)
475 {
476 return;
477 }
478
479 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
480 }
481
482 // ###################################################################
483 /**
484 * Prepares a value for use in a SQL query; it encases and escapes
485 * strings and string-like values
486 *
487 * @param string Field name
488 *
489 * @return string Prepared value entry
490 */
491 private function _prepareFieldForSql($name)
492 {
493 $type = $this->fields["$name"][F_TYPE];
494
495 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
496 {
497 return "'" . BSApp::GetType('Db')->escapeString($this->values["$name"]) . "'";
498 }
499 else if ($type == TYPE_BOOL)
500 {
501 return ($this->values["$name"] == true ? "'1'" : "'0'");
502 }
503 else if ($type == TYPE_BIN)
504 {
505 return "'" . BSApp::GetType('Db')->escapeBinary($this->values["$name"]) . "'";
506 }
507 else
508 {
509 return $this->values["$name"];
510 }
511 }
512
513 // ###################################################################
514 /**
515 * Verify field: not a zero value
516 */
517 protected function verify_nozero($field)
518 {
519 if ($this->values["$field"] == 0)
520 {
521 return sprintf(_('The field "%1$s" cannot be zero'), $field);
522 }
523
524 return true;
525 }
526
527 // ###################################################################
528 /**
529 * Verify field: not empty
530 */
531 protected function verify_noempty($field)
532 {
533 if (empty($this->values["$field"]))
534 {
535 return sprintf(_('The field "%1$s" cannot be empty'), $field);
536 }
537
538 return true;
539 }
540
541 // ###################################################################
542 /**
543 * Verify field: unique
544 */
545 protected function verify_unique($field)
546 {
547 $res = BSApp::GetType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
548 if ($res)
549 {
550 return sprintf(_('The "%1$s" field must contain a unique value'), $field);
551 }
552
553 return true;
554 }
555 }
556
557 // ###################################################################
558 /**
559 * Setter and getter method for the API error reporting system. Passing
560 * a name will cause the set, no arguments will cause the get.
561 *
562 * @param mixed Method name in callable form
563 *
564 * @return mixed Method name in callable form
565 */
566 function APIError($new = null)
567 {
568 static $caller, $prev;
569
570 if ($new === -1)
571 {
572 $caller = $prev;
573 }
574 else if ($new !== null)
575 {
576 $prev = $caller;
577 $caller = $new;
578 }
579
580 return $caller;
581 }
582
583 /*=====================================================================*\
584 || ###################################################################
585 || # $HeadURL$
586 || # $Id$
587 || ###################################################################
588 \*=====================================================================*/
589 ?>