Give all the instance variables visibility tags
[isso.git] / api.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
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
24 * api.php
25 *
26 * @package ISSO
27 */
28
29 if (!defined('REQ_AUTO'))
30 {
31 /**
32 * Auto-increasing value
33 */
34 define('REQ_AUTO', -1);
35
36 /**
37 * Set by a cusotm set_*() function
38 */
39 define('REQ_SET', 2);
40
41 /**
42 * Index for cleaning type
43 */
44 define('F_TYPE', 0);
45
46 /**
47 * Index for requirement type
48 */
49 define('F_REQ', 1);
50
51 /**
52 * Index for verification type
53 */
54 define('F_VERIFY', 2);
55 }
56
57 /**
58 * Abstract API
59 *
60 * Abstract class that is used as an API base for most common database interaction
61 * schemes. Creates a simple structure that holds data and can update, delete, and
62 * insert.
63 *
64 * @author Iris Studios, Inc.
65 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
66 * @version $Revision$
67 * @package ISSO
68 *
69 */
70 class API
71 {
72 /**
73 * Registry object
74 * @var object
75 * @access protected
76 */
77 var $registry = null;
78
79 /**
80 * Fields: used for verification and sanitization
81 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method))
82 * @var array
83 * @access protected
84 */
85 var $fields = array();
86
87 /**
88 * Values array: sanitized and verified field values
89 * @var array
90 * @access public
91 */
92 var $values = array();
93
94 /**
95 * Fields that were manually set with set(), not by using set_existing()
96 * @var array
97 * @access private
98 */
99 var $setfields = array();
100
101 /**
102 * WHERE condition
103 * @var string
104 * @access private
105 */
106 var $condition = '';
107
108 /**
109 * The object table row; a fetched row that represents this instance
110 * @var array
111 * @access public
112 */
113 var $objdata = array();
114
115 /**
116 * Insert ID from the insert() command
117 * @var integer
118 * @access public
119 */
120 var $insertid = 0;
121
122 /**
123 * Pre- and post-action method stoppers
124 * @var array
125 * @access public
126 */
127 var $norunners = array();
128
129 // ###################################################################
130 /**
131 * Constructor: cannot instantiate class directly
132 */
133 function __construct(&$registry)
134 {
135 if (!is_subclass_of($this, 'API'))
136 {
137 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR);
138 }
139
140 if (!is_object($registry))
141 {
142 trigger_error('The passed registry is not an object', E_USER_ERROR);
143 }
144
145 $this->registry =& $registry;
146 }
147
148 // ###################################################################
149 /**
150 * (PHP 4) Constructor
151 */
152 function API(&$registry)
153 {
154 $this->__construct($registry);
155 }
156
157 // ###################################################################
158 /**
159 * Constructs an error for the error handler to receive
160 *
161 * @access protected
162 *
163 * @param string Error message
164 */
165 function error($message)
166 {
167 call_user_func(APIError(), $message);
168 }
169
170 // ###################################################################
171 /**
172 * Sets a value, sanitizes it, and verifies it
173 *
174 * @access public
175 *
176 * @param string Field name
177 * @param mixed Value
178 * @param bool Do clean?
179 * @param bool Do verify?
180 */
181 function set($field, $value, $doclean = true, $doverify = true)
182 {
183 if (!isset($this->fields["$field"]))
184 {
185 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
186 return;
187 }
188
189 $this->values["$field"] = ($doclean ? $this->registry->clean($value, $this->fields["$field"][F_TYPE]) : $value);
190
191 $this->setfields["$field"] = $field;
192
193 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
194 {
195 if ($this->fields["$field"][F_VERIFY] == ':self')
196 {
197 $verify = $this->{"verify_$field"}($field);
198 }
199 else
200 {
201 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
202 }
203
204 if (!$verify)
205 {
206 $this->error(sprintf($this->registry->modules['localize']->string('Validation of %1$s failed'), $field));
207 }
208 }
209 }
210
211 // ###################################################################
212 /**
213 * Sets the condition to use in the WHERE clause; if not passed, then
214 * it calculates it from the REQ_AUTO field
215 *
216 * @access public
217 *
218 * @param string WHERE conditional bit
219 */
220 function set_condition($condition = '')
221 {
222 if ($condition != '')
223 {
224 $this->condition = $condition;
225 }
226 else
227 {
228 foreach ($this->fields AS $name => $options)
229 {
230 if ($options[F_REQ] == REQ_AUTO)
231 {
232 if (!$this->values["$name"])
233 {
234 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING);
235 continue;
236 }
237
238 $this->condition = "$name = " . $this->prepare_field_for_sql($name);
239 }
240 }
241
242 if ($this->condition == '')
243 {
244 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING);
245 }
246 }
247 }
248
249 // ###################################################################
250 /**
251 * Sets existing data into $values where it's not already present
252 *
253 * @access public
254 */
255 function set_existing()
256 {
257 static $run;
258 if ($run)
259 {
260 return;
261 }
262
263 $this->fetch();
264
265 foreach ($this->objdata AS $field => $value)
266 {
267 if (!isset($this->values["$field"]))
268 {
269 $this->values["$field"] = $value;
270 }
271 }
272
273 $run = true;
274 }
275
276 // ###################################################################
277 /**
278 * Fetches a record based on the condition
279 *
280 * @access public
281 */
282 function fetch()
283 {
284 if ($this->condition == '')
285 {
286 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
287 }
288
289 $this->run_action_method('pre_fetch');
290
291 $result = $this->registry->modules[ISSO_DB_LAYER]->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
292 if (!$result)
293 {
294 $this->error($this->registry->modules['localize']->string('No records were returned'));
295 return;
296 }
297
298 $this->run_action_method('post_fetch');
299
300 $this->objdata = $result;
301 }
302
303 // ###################################################################
304 /**
305 * Inserts a record in the database
306 *
307 * @access public
308 */
309 function insert()
310 {
311 $this->verify();
312
313 $this->run_action_method('pre_insert');
314
315 foreach ($this->setfields AS $field)
316 {
317 $fields[] = $field;
318 $values[] = $this->prepare_field_for_sql($field);
319 }
320
321 $this->registry->modules[ISSO_DB_LAYER]->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
322 $this->insertid = $this->registry->modules[ISSO_DB_LAYER]->insert_id();
323
324 $this->run_action_method('post_insert');
325 }
326
327 // ###################################################################
328 /**
329 * Updates a record in the database using the data in $vaues
330 *
331 * @access public
332 */
333 function update()
334 {
335 if ($this->condition == '')
336 {
337 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
338 }
339
340 $this->run_action_method('pre_update');
341
342 foreach ($this->setfields AS $field)
343 {
344 $updates[] = "$field = " . $this->prepare_field_for_sql($field);
345 }
346 $updates = implode(', ', $updates);
347
348 $this->registry->modules[ISSO_DB_LAYER]->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
349
350 $this->run_action_method('post_update');
351 }
352
353 // ###################################################################
354 /**
355 * Deletes a record
356 *
357 * @access public
358 */
359 function delete()
360 {
361 if ($this->condition == '')
362 {
363 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
364 }
365
366 $this->set_existing();
367
368 $this->run_action_method('pre_delete');
369
370 $this->registry->modules[ISSO_DB_LAYER]->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
371
372 $this->run_action_method('post_delete');
373 }
374
375 // ###################################################################
376 /**
377 * Verifies that all required fields are set
378 *
379 * @access private
380 */
381 function verify()
382 {
383 foreach ($this->fields AS $name => $options)
384 {
385 if ($options[F_REQ] == REQ_YES)
386 {
387 if (!isset($this->values["$name"]))
388 {
389 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
390 }
391 }
392 else if ($options[F_REQ] == REQ_SET)
393 {
394 $this->{"set_$name"}();
395 }
396 }
397 }
398
399 // ###################################################################
400 /**
401 * Runs a pre- or post-action method for database commands
402 *
403 * @access private
404 *
405 * @param string Action to run
406 */
407 function run_action_method($method)
408 {
409 if (in_array($method, $this->norunners))
410 {
411 return;
412 }
413
414 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
415 }
416
417 // ###################################################################
418 /**
419 * Prepares a value for use in a SQL query; it encases and escapes
420 * strings and string-like values
421 *
422 * @access private
423 *
424 * @param string Field name
425 *
426 * @return string Prepared value entry
427 */
428 function prepare_field_for_sql($name)
429 {
430 $type = $this->fields["$name"][F_TYPE];
431
432 if ($type == TYPE_NOCLEAN OR $type == TYPE_STR OR $type == TYPE_STRUN)
433 {
434 return "'" . $this->registry->escape($this->values["$name"]) . "'";
435 }
436 else if ($type == TYPE_BOOL)
437 {
438 return (int)$this->values["$name"];
439 }
440 else
441 {
442 return $this->values["$name"];
443 }
444 }
445
446 // ###################################################################
447 /**
448 * Verify field: not a zero value
449 *
450 * @access protected
451 */
452 function verify_nozero($field)
453 {
454 if ($this->values["$field"] == 0)
455 {
456 return false;
457 }
458
459 return true;
460 }
461
462 // ###################################################################
463 /**
464 * Verify field: not empty
465 *
466 * @access protected
467 */
468 function verify_noempty($field)
469 {
470 if (empty($this->values["$field"]))
471 {
472 return false;
473 }
474
475 return true;
476 }
477 }
478
479 // ###################################################################
480 /**
481 * Setter and getter method for the API error reporting system. Passing
482 * a name will cause the set, no arguments will cause the get.
483 *
484 * @access public
485 *
486 * @param mixed Method name in callable form
487 *
488 * @return mixed Method name in callable form
489 */
490 function APIError($new = null)
491 {
492 static $caller;
493
494 if ($new !== null)
495 {
496 $caller = $new;
497 }
498
499 return $caller;
500 }
501
502 /*=====================================================================*\
503 || ###################################################################
504 || # $HeadURL$
505 || # $Id$
506 || ###################################################################
507 \*=====================================================================*/
508 ?>