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