Added insert() and delete() actions
[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('TYPE_INT'))
30 {
31 /**
32 * Integer type
33 */
34 define('TYPE_INT', 1);
35
36 /**
37 * Unsigned integer
38 */
39 define('TYPE_UINT', 2);
40
41 /**
42 * Float type
43 */
44 define('TYPE_FLOAT', 4);
45
46 /**
47 * Boolean type
48 */
49 define('TYPE_BOOL', 8);
50
51 /**
52 * String - cleaned
53 */
54 define('TYPE_STR', 16);
55
56 /**
57 * String - deliberate unclean
58 */
59 define('TYPE_STRUN', 32);
60
61 /**
62 * No cleaning
63 */
64 define('TYPE_NOCLEAN', 64);
65
66 /**
67 * Yes, required
68 */
69 define('REQ_YES', 1);
70
71 /**
72 * No, not required
73 */
74 define('REQ_NO', 0);
75
76 /**
77 * Auto-increasing value
78 */
79 define('REQ_AUTO', -1);
80
81 /**
82 * Returns an unsigned integer
83 *
84 * @param mixed Original data
85 *
86 * @return integer Unsigned integegral value
87 */
88 function uintval($data)
89 {
90 return abs(intval($data));
91 }
92
93 /**
94 * Returns the same value
95 *
96 * @param mixed Original
97 *
98 * @return mixed Same original value
99 */
100 function sameval($data)
101 {
102 return $data;
103 }
104 }
105
106 /**
107 * Abstract API
108 *
109 * Abstract class that is used as an API base for most common database interaction
110 * schemes. Creates a simple structure that holds data and can update, delete, and
111 * insert.
112 *
113 * @author Iris Studios, Inc.
114 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
115 * @version $Revision$
116 * @package ISSO
117 *
118 */
119 class API
120 {
121 /**
122 * Registry object
123 * @var object
124 */
125 var $registry = null;
126
127 /**
128 * Fields: used for verification and sanitization
129 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method))
130 * @var array
131 */
132 var $fields = array();
133
134 /**
135 * Values array: sanitized and verified field values
136 * @var array
137 */
138 var $values = array();
139
140 /**
141 * Fields that were manually set with set(), not by using set_existing()
142 * @var array
143 */
144 var $setfields = array();
145
146 /**
147 * WHERE condition
148 * @var string
149 */
150 var $condition = '';
151
152 /**
153 * The object table row; a fetched row that represents this instance
154 * @var array
155 */
156 var $objdata = array();
157
158 /**
159 * Insert ID from the insert() command
160 * @var integer
161 */
162 var $insertid = 0;
163
164 /**
165 * Constructor: cannot instantiate class directly
166 */
167 function API(&$registry)
168 {
169 if (!is_subclass_of($this, 'API'))
170 {
171 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR);
172 }
173
174 if (!is_object($registry))
175 {
176 trigger_error('The passed registry is not an object', E_USER_ERROR);
177 }
178
179 $this->registry =& $registry;
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 function set($field, $value, $doclean = true, $doverify = true)
191 {
192 if (!isset($this->fields["$field"]))
193 {
194 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
195 return;
196 }
197
198 $this->values["$field"] = ($doclean ? $this->do_clean($value, $this->fields["$field"][0]) : $value);
199
200 $this->setfields[] = $field;
201
202 if (isset($this->fields["$field"][2]) AND $doverify)
203 {
204 if ($this->fields["$field"][2] == ':self')
205 {
206 $verify = $this->{$this->{"verify_$field"}}($field);
207 }
208 else
209 {
210 $verify = $this->{$this->fields["$field"][2]}($field);
211 }
212
213 if (!$verify)
214 {
215 // <ERR:CVT>
216 trigger_error('Validation of `' . $field . '` failed', E_USER_ERROR);
217 }
218 }
219 }
220
221 /**
222 * Sets the condition to use in the WHERE clause; if not passed, then it calculates it
223 * from the REQ_AUTO field
224 *
225 * @param string WHERE conditional bit
226 */
227 function set_condition($condition = '')
228 {
229 if ($condition != '')
230 {
231 $this->condition = $condition;
232 }
233 else
234 {
235 foreach ($this->fields AS $name => $options)
236 {
237 if ($options[1] == REQ_AUTO)
238 {
239 if (!$this->values["$name"])
240 {
241 trigger_error('Cannot determine condition from the REQ_AUTO field because it is not set', E_USER_WARNING);
242 continue;
243 }
244
245 $this->condition = "$name = " . (($options[0] == TYPE_NOCLEAN OR $options[0] == TYPE_STR) ? "'" . $this->values["$name"] . "'" : $this->values["$name"]);
246 }
247 }
248
249 if ($this->condition == '')
250 {
251 trigger_error('No REQ_AUTO fields are present and therefore the condition cannot be created', E_USER_WARNING);
252 }
253 }
254 }
255
256 /**
257 * Sets existing data into $values where it's not already present
258 */
259 function set_existing()
260 {
261 static $run;
262 if ($run)
263 {
264 return;
265 }
266
267 $this->fetch();
268
269 foreach ($this->objdata AS $field => $value)
270 {
271 if (!isset($this->values["$field"]))
272 {
273 $this->values["$field"] = $value;
274 }
275 }
276
277 $run = true;
278 }
279
280 /**
281 * Fetches a record based on the condition
282 */
283 function fetch()
284 {
285 if ($this->condition == '')
286 {
287 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
288 }
289
290 $actmethod = (method_exists($this, 'pre_fetch') ? $this->pre_fetch() : '');
291
292 $result = $this->registry->modules['db_mysql']->query_first("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
293 if (!$result)
294 {
295 // <ERR:CVT>
296 trigger_error('No record was returned', E_USER_ERROR);
297 return;
298 }
299
300 $actmethod = (method_exists($this, 'post_fetch') ? $this->post_fetch() : '');
301
302 $this->objdata = $result;
303 }
304
305 /**
306 * Inserts a record in the database
307 */
308 function insert()
309 {
310 $this->verify();
311
312 $actmethod = (method_exists($this, 'pre_insert') ? $this->pre_insert() : '');
313
314 foreach ($this->setfields AS $field)
315 {
316 $fields[] = $field;
317 $values[] (($this->fields["$field"][0] == TYPE_NOCLEAN OR $this->fields["$field"][0] == TYPE_STR) ? "'" . $this->values["$field"] . "'" : $this->values["$field"]);
318 }
319
320 $this->registry->modules['db_mysql']->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
321 $this->insertid = $this->registry->modules['db_mysql']->insert_id();
322
323 $actmethod = (method_exists($this, 'post_insert') ? $this->post_insert() : '');
324 }
325
326 /**
327 * Updates a record in the database using the data in $vaues
328 */
329 function update()
330 {
331 if ($this->condition == '')
332 {
333 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
334 }
335
336 $this->set_existing();
337 $this->verify();
338
339 $actmethod = (method_exists($this, 'pre_update') ? $this->pre_update() : '');
340
341 foreach ($this->setfields AS $field)
342 {
343 $updates[] = "$field = " . (($this->fields["$field"][0] == TYPE_NOCLEAN OR $this->fields["$field"][0] == TYPE_STR) ? "'" . $this->values["$field"] . "'" : $this->values["$field"]);
344 }
345 $updates = implode(', ', $updates);
346
347 $this->registry->modules['db_mysql']->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
348
349 $actmethod = (method_exists($this, 'post_update') ? $this->post_update() : '');
350 }
351
352 /**
353 * Deletes a record
354 */
355 function delete()
356 {
357 if ($this->condition == '')
358 {
359 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
360 }
361
362 $this->set_existing();
363
364 $actmethod = (method_exists($this, 'pre_delete') ? $this->pre_delete() : '');
365
366 $this->registry->modules['db_mysql']->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
367
368 $actmethod = (method_exists($this, 'post_delete') ? $this->post_delete() : '');
369 }
370
371 /**
372 * Verifies that all required fields are set
373 */
374 function verify()
375 {
376 foreach ($this->fields AS $name => $options)
377 {
378 if ($options[1] == REQ_YES)
379 {
380 if (!isset($this->values["$name"]))
381 {
382 // <ERR:CVT>
383 trigger_error('Field `' . $name . '` was not set', E_USER_ERROR);
384 }
385 }
386 }
387 }
388
389 /**
390 * Verify field: not a zero value
391 */
392 function verify_nozero($field)
393 {
394 if ($this->values["$field"] == 0)
395 {
396 return false;
397 }
398
399 return true;
400 }
401
402 /**
403 * Cleans a value based on the field option
404 *
405 * @param mixed Uncleaned data
406 * @param integer Cleaning type
407 *
408 * @return mixed Cleaned data
409 */
410 function do_clean($value, $type)
411 {
412 if ($type == TYPE_INT)
413 {
414 $value = intval($value);
415 }
416 else if ($type == TYPE_UINT)
417 {
418 $value = abs(intval($value));
419 }
420 else if ($type == TYPE_FLOAT)
421 {
422 $value = floatval($value);
423 }
424 else if ($type == TYPE_BOOL)
425 {
426 $value = (bool)$value;
427 }
428 else if ($type == TYPE_STR)
429 {
430 if (!$this->registry->escapestrings)
431 {
432 $value = $this->registry->escape($value);
433 }
434 }
435 else if ($type == TYPE_STRUN)
436 {
437 $value = $this->registry->unsanitize($value);
438 }
439 else if ($type == TYPE_NOCLEAN)
440 {
441 }
442 else
443 {
444 trigger_error('Invalid clean type specified', E_USER_ERROR);
445 }
446
447 return $value;
448 }
449 }
450
451 /*=====================================================================*\
452 || ###################################################################
453 || # $HeadURL$
454 || # $Id$
455 || ###################################################################
456 \*=====================================================================*/
457 ?>