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