If set() is run more than twice, we get a duplicate in setfields[] so make sure we...
[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 * Constructor: cannot instantiate class directly
133 */
134 function API(&$registry)
135 {
136 if (!is_subclass_of($this, 'API'))
137 {
138 trigger_error('Cannot instantiate the API module directly', E_USER_ERROR);
139 }
140
141 if (!is_object($registry))
142 {
143 trigger_error('The passed registry is not an object', E_USER_ERROR);
144 }
145
146 $this->registry =& $registry;
147 }
148
149 /**
150 * Constructs an error for the error handler to receive
151 *
152 * @param string Error message
153 */
154 function error($message)
155 {
156 call_user_func(APIError(), $message);
157 }
158
159 /**
160 * Sets a value, sanitizes it, and verifies it
161 *
162 * @param string Field name
163 * @param mixed Value
164 * @param bool Do clean?
165 * @param bool Do verify?
166 */
167 function set($field, $value, $doclean = true, $doverify = true)
168 {
169 if (!isset($this->fields["$field"]))
170 {
171 trigger_error('Field `' . $field . '` is not valid', E_USER_WARNING);
172 return;
173 }
174
175 $this->values["$field"] = ($doclean ? $this->registry->clean($value, $this->fields["$field"][F_TYPE]) : $value);
176
177 $this->setfields["$field"] = $field;
178
179 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
180 {
181 if ($this->fields["$field"][F_VERIFY] == ':self')
182 {
183 $verify = $this->{"verify_$field"}($field);
184 }
185 else
186 {
187 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
188 }
189
190 if (!$verify)
191 {
192 $this->error(sprintf($this->registry->modules['localize']->string('Validation of %1$s failed'), $field));
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[F_REQ] == 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[F_TYPE] == TYPE_NOCLEAN OR $options[F_TYPE] == TYPE_STR OR $options[F_TYPE] == TYPE_STRUN) ? "'" . $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 $this->run_action_method('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 $this->error($this->registry->modules['localize']->string('No records were returned'));
272 return;
273 }
274
275 $this->run_action_method('post_fetch');
276
277 $this->objdata = $result;
278 }
279
280 /**
281 * Inserts a record in the database
282 */
283 function insert()
284 {
285 $this->verify();
286
287 $this->run_action_method('pre_insert');
288
289 foreach ($this->setfields AS $field)
290 {
291 $fields[] = $field;
292 $values[] = (($this->fields["$field"][F_TYPE] == TYPE_NOCLEAN OR $this->fields["$field"][F_TYPE] == TYPE_STR OR $this->fields["$field"][F_TYPE] == TYPE_STRUN) ? "'" . $this->values["$field"] . "'" : $this->values["$field"]);
293 }
294
295 $this->registry->modules['db_mysql']->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
296 $this->insertid = $this->registry->modules['db_mysql']->insert_id();
297
298 $this->run_action_method('post_insert');
299 }
300
301 /**
302 * Updates a record in the database using the data in $vaues
303 */
304 function update()
305 {
306 if ($this->condition == '')
307 {
308 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
309 }
310
311 $this->run_action_method('pre_update');
312
313 foreach ($this->setfields AS $field)
314 {
315 $updates[] = "$field = " . (($this->fields["$field"][F_TYPE] == TYPE_NOCLEAN OR $this->fields["$field"][F_TYPE] == TYPE_STR OR $this->fields["$field"][F_TYPE] == TYPE_STRUN) ? "'" . $this->values["$field"] . "'" : $this->values["$field"]);
316 }
317 $updates = implode(', ', $updates);
318
319 $this->registry->modules['db_mysql']->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
320
321 $this->run_action_method('post_update');
322 }
323
324 /**
325 * Deletes a record
326 */
327 function delete()
328 {
329 if ($this->condition == '')
330 {
331 trigger_error('Condition is empty: cannot fetch', E_USER_ERROR);
332 }
333
334 $this->set_existing();
335
336 $this->run_action_method('pre_delete');
337
338 $this->registry->modules['db_mysql']->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
339
340 $this->run_action_method('post_delete');
341 }
342
343 /**
344 * Verifies that all required fields are set
345 */
346 function verify()
347 {
348 foreach ($this->fields AS $name => $options)
349 {
350 if ($options[F_REQ] == REQ_YES)
351 {
352 if (!isset($this->values["$name"]))
353 {
354 $this->error(sprintf($this->registry->modules['localize']->string('Required field %1$s was not set'), $name));
355 }
356 }
357 else if ($options[F_REQ] == REQ_SET)
358 {
359 $this->{"set_$name"}();
360 }
361 }
362 }
363
364 /**
365 * Runs a pre- or post-action method for database commands
366 *
367 * @param string Action to run
368 */
369 function run_action_method($method)
370 {
371 if (in_array($method, $this->norunners))
372 {
373 return;
374 }
375
376 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
377 }
378
379 /**
380 * Verify field: not a zero value
381 */
382 function verify_nozero($field)
383 {
384 if ($this->values["$field"] == 0)
385 {
386 return false;
387 }
388
389 return true;
390 }
391
392 /**
393 * Verify field: not empty
394 */
395 function verify_noempty($field)
396 {
397 if (empty($this->values["$field"]))
398 {
399 return false;
400 }
401
402 return true;
403 }
404 }
405
406 /**
407 * Setter and getter method for the API error reporting
408 * system. Passing a name will cause the set, no arguments
409 * will cause the get.
410 *
411 * @param mixed Method name in callable form
412 *
413 * @return mixed Method name in callable form
414 */
415 function APIError($new = null)
416 {
417 static $caller;
418
419 if ($new !== null)
420 {
421 $caller = $new;
422 }
423
424 return $caller;
425 }
426
427 /*=====================================================================*\
428 || ###################################################################
429 || # $HeadURL$
430 || # $Id$
431 || ###################################################################
432 \*=====================================================================*/
433 ?>