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