]> src.bluestatic.org Git - isso.git/blob - Api.php
Create BSPrinter to handle CSS stylesheet linking and language information so individ...
[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 list that has been generated
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 * Constructs an error for the error handler to receive
136 *
137 * @param string Error message
138 */
139 protected function _error($message)
140 {
141 $this->errors[] = $message;
142
143 // we want to explicitly specify silence
144 if (APIError() == 'silent')
145 {
146 return;
147 }
148
149 if (!is_callable(APIError()))
150 {
151 trigger_error('No APIError() handler has been set');
152 }
153
154 call_user_func(APIError(), $message);
155 }
156
157 // ###################################################################
158 /**
159 * Returns the error list. This is because we don't want people mucking
160 * with the error system. It will return an empty array if there are
161 * no errors.
162 *
163 * @return array Array of errors
164 */
165 public function checkErrors()
166 {
167 if (sizeof($this->errors) < 1)
168 {
169 return array();
170 }
171
172 return $this->errors;
173 }
174
175 // ###################################################################
176 /**
177 * Sets a value, sanitizes it, and verifies it
178 *
179 * @param string Field name
180 * @param mixed Value
181 * @param bool Do clean?
182 * @param bool Do verify?
183 */
184 public function set($field, $value, $doclean = true, $doverify = true)
185 {
186 if (!isset($this->fields["$field"]))
187 {
188 trigger_error('Field "' . $field . '" is not valid');
189 return;
190 }
191
192 $this->values["$field"] = ($doclean ? BSRegister::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(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 trigger_error('The specified field "' . $field . '" for the condition could not be found as it is not set');
239 continue;
240 }
241
242 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
243 }
244 $this->condition = implode(' AND ', $condbits);
245 }
246 else if ($condition != '')
247 {
248 $this->condition = $condition;
249 }
250 else
251 {
252 foreach ($this->fields AS $name => $options)
253 {
254 if ($options[F_REQ] == REQ_AUTO)
255 {
256 if (!$this->values["$name"])
257 {
258 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set');
259 continue;
260 }
261
262 $this->condition = "$name = " . $this->_prepareFieldForSql($name);
263 }
264 }
265
266 if ($this->condition == '')
267 {
268 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created');
269 }
270 }
271 }
272
273 // ###################################################################
274 /**
275 * Sets existing data into $values where it's not already present
276 */
277 public function setExisting()
278 {
279 static $run;
280 if ($run)
281 {
282 return;
283 }
284
285 $this->fetch();
286
287 foreach ($this->objdata AS $field => $value)
288 {
289 if (!isset($this->values["$field"]))
290 {
291 $this->values["$field"] = $value;
292 }
293 }
294
295 $run = true;
296 }
297
298 // ###################################################################
299 /**
300 * Fetches a record based on the condition
301 *
302 * @param bool Run pre_fetch()?
303 * @param bool Run post_fetch()?
304 */
305 public function fetch($doPre = true, $doPost = true)
306 {
307 if ($this->condition == '')
308 {
309 $this->setCondition();
310 }
311
312 $this->_runActionMethod('pre_fetch', $doPre);
313
314 $result = BSRegister::GetType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
315 if (!$result)
316 {
317 $this->error(_('No records were returned'));
318 return;
319 }
320
321 $this->_runActionMethod('post_fetch', $doPost);
322
323 $this->objdata = $result;
324
325 if ($populate)
326 {
327 foreach ($this->objdata AS $key => $value)
328 {
329 if (!isset($this->values["$key"]))
330 {
331 $this->values["$key"] = $value;
332 }
333 }
334 }
335 }
336
337 // ###################################################################
338 /**
339 * Inserts a record in the database
340 *
341 * @param bool Run pre_insert()?
342 * @param bool Run post_insert()?
343 */
344 public function insert($doPre = true, $doPost = true)
345 {
346 $this->verify();
347
348 $this->_runActionMethod('pre_insert', $doPre);
349
350 foreach ($this->setfields AS $field)
351 {
352 $fields[] = $field;
353 $values[] = $this->_prepareFieldForSql($field);
354 }
355
356 BSRegister::GetType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
357
358 if (BSRegister::GetType('DbPostgreSql'))
359 {
360 foreach ($this->fields AS $field => $info)
361 {
362 if ($info[F_REQ] == REQ_AUTO)
363 {
364 $autofield = $field;
365 break;
366 }
367 }
368
369 $this->insertid = BSRegister::GetType('Db')->insertId($this->prefix . $this->table, $autofield);
370 }
371 else
372 {
373 $this->insertid = BSRegister::GetType('Db')->insertId();
374 }
375
376 $this->_runActionMethod('post_insert', $doPost);
377 }
378
379 // ###################################################################
380 /**
381 * Updates a record in the database using the data in $vaues
382 *
383 * @param bool Run pre_update()?
384 * @param bool Run post_update()?
385 */
386 public function update($doPre = true, $doPost = true)
387 {
388 if ($this->condition == '')
389 {
390 $this->setCondition();
391 }
392
393 $this->_runActionMethod('pre_update', $doPre);
394
395 foreach ($this->setfields AS $field)
396 {
397 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
398 }
399 $updates = implode(', ', $updates);
400
401 BSRegister::GetType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
402
403 $this->_runActionMethod('post_update', $doPost);
404 }
405
406 // ###################################################################
407 /**
408 * Deletes a record
409 *
410 * @param bool Run pre_remove()?
411 * @param bool Run post_remove()?
412 */
413 public function remove($doPre = true, $doPost = true)
414 {
415 if ($this->condition == '')
416 {
417 $this->setCondition();
418 }
419
420 $this->fetch();
421
422 $this->_runActionMethod('pre_remove', $doPre);
423
424 BSRegister::GetType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
425
426 $this->_runActionMethod('post_remove', $doPost);
427 }
428
429 // ###################################################################
430 /**
431 * Verifies that all required fields are set
432 */
433 private function verify()
434 {
435 foreach ($this->fields AS $name => $options)
436 {
437 if ($options[F_REQ] == REQ_YES)
438 {
439 if (!isset($this->values["$name"]))
440 {
441 $this->error(sprintf(_('The required field "%1$s" was not set'), $name));
442 }
443 }
444 else if ($options[F_REQ] == REQ_SET)
445 {
446 $this->{"set_$name"}();
447 }
448 }
449 }
450
451 // ###################################################################
452 /**
453 * Runs a pre- or post-action method for database commands
454 *
455 * @param string Action to run
456 * @param bool Actually run it?
457 */
458 private function _runActionMethod($method, $doRun)
459 {
460 if (!$doRun)
461 {
462 return;
463 }
464
465 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
466 }
467
468 // ###################################################################
469 /**
470 * Prepares a value for use in a SQL query; it encases and escapes
471 * strings and string-like values
472 *
473 * @param string Field name
474 *
475 * @return string Prepared value entry
476 */
477 private function _prepareFieldForSql($name)
478 {
479 $type = $this->fields["$name"][F_TYPE];
480
481 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
482 {
483 return "'" . BSRegister::GetType('Db')->escapeString($this->values["$name"]) . "'";
484 }
485 else if ($type == TYPE_BOOL)
486 {
487 return ($this->values["$name"] == true ? "'1'" : "'0'");
488 }
489 else if ($type == TYPE_BIN)
490 {
491 return "'" . BSRegister::GetType('Db')->escapeBinary($this->values["$name"]) . "'";
492 }
493 else
494 {
495 return $this->values["$name"];
496 }
497 }
498
499 // ###################################################################
500 /**
501 * Verify field: not a zero value
502 */
503 protected function verify_nozero($field)
504 {
505 if ($this->values["$field"] == 0)
506 {
507 return sprintf(_('The field "%1$s" cannot be zero'), $field);
508 }
509
510 return true;
511 }
512
513 // ###################################################################
514 /**
515 * Verify field: not empty
516 */
517 protected function verify_noempty($field)
518 {
519 if (empty($this->values["$field"]))
520 {
521 return sprintf(_('The field "%1$s" cannot be empty'), $field);
522 }
523
524 return true;
525 }
526 }
527
528 // ###################################################################
529 /**
530 * Setter and getter method for the API error reporting system. Passing
531 * a name will cause the set, no arguments will cause the get.
532 *
533 * @access public
534 *
535 * @param mixed Method name in callable form
536 *
537 * @return mixed Method name in callable form
538 */
539 function APIError($new = null)
540 {
541 static $caller, $prev;
542
543 if ($new === -1)
544 {
545 $caller = $prev;
546 }
547 else if ($new !== null)
548 {
549 $prev = $caller;
550 $caller = $new;
551 }
552
553 return $caller;
554 }
555
556 /*=====================================================================*\
557 || ###################################################################
558 || # $HeadURL$
559 || # $Id$
560 || ###################################################################
561 \*=====================================================================*/
562 ?>