Updates in User-module
[AOOS.git] / AOOSStorageDevice.php
blob72bd35439531b803d5884925c1421fa00995e0f4
1 <?php
2 require_once("AOOSException.php");
3 require_once("AOOSModule.php");
5 /**
6 * AOOSStorageDevice
7 * Provides an interface for handling data on database or file basis.
8 * @author Sebastian Skejø
9 */
10 class AOOSStorageDevice extends AOOSModule
12 private $_storageObject = null;
13 private $_table = null;
14 private $_sort = null;
16 /**
17 * Check wether $storageObject() is set
19 private function _checkDevice()
21 if ($this->storageObject() == null)
23 throw new AOOSException($this->core(), $this->tr("storage_type_not_set"));
24 return false;
26 return true;
29 /**
30 * Check if we can use $array as an array
32 private function _checkArray($array)
34 // Is it actually an array?
35 if (!is_array($array))
37 throw new AOOSException($this->core(), $this->tr("not_array"));
38 return false;
41 // Check if length of array keys and array values match
42 if (count(array_keys($array)) != count(array_values($array)))
44 throw new AOOSException($this->core(), $this->tr("array_keys_value_different_length"));
45 return false;
47 return true;
50 /**
51 * Check both $key and $value to see if we can use them as a value pair
53 private function _checkValue($key, $value)
55 // Are we dealing with strings?
56 if ((!is_string($key) && !is_int($key)) || (!is_string($key) && !is_int($value)))
58 throw new AOOSException($this->core(), $this->tr("not_string_or_int"), "<strong>Key:</strong>".$key."<br /><strong>Value:</strong> ".$value);
59 return false;
62 // Are the strings empty?
63 if (empty($key) || empty($value))
65 throw new AOOSException($this->core(), $this->tr("strings_empty"));
66 return false;
69 // Ok, we completed the tests - let's return true!
70 return true;
73 /**
74 * Check if we have a valid model
76 private function _checkModel(&$model)
78 if (!$model instanceof AOOSModel)
80 throw new AOOSException($this->core(), $this->tr("not_AOOSModel"));
81 return false;
83 return true;
86 /**
87 * Check if the given where-clause can be used as a where clause
89 private function _checkWhere(&$where)
91 if (is_array($where))
93 $tmp = array();
94 foreach ($where as $key => $value)
96 $tmp[] = sprintf("%s = %s", $key, $value);
98 $where = implode(" AND ", $tmp);
99 return true;
102 // Is it a string? We know it isn't an array
103 if (!is_string($where))
105 throw new AOOSException($this->core(), $this->tr("not_string_or_array"));
106 return false;
109 // Does it match a pattern?
110 if (!preg_match("/[[:alnum:]]+\s*=\s*[[:alnum:]]+/", $where))
112 throw new AOOSException($this->core(), $this->tr("where_not_valid"));
113 return false;
116 return true;
120 * Check if the given limit-clause is valid
122 private function _checkLimit($limit)
124 if (!is_string($limit))
126 throw new AOOSException($this->core(), $this->tr("not_string"));
127 return false;
130 // Does it match a limit-pattern?
131 if (!preg_match("/[0-9]+\s*,\s*[0-9]+/", $limit))
133 throw new AOOSException($this->core(), $this->tr("limit_not_valid"));
134 return false;
137 return true;
141 * Sets the table in which data should be added, updated or deleted from
142 * @param string $table Table name
143 * @return bool
145 public function setTable($table)
147 if (!$this->_checkDevice())
149 return false;
152 if (!is_string($table))
154 throw new AOOSException($this->core(), $this->tr("not_string"));
155 return false;
158 $this->_table = $table;
159 $this->storageObject()->setTable($table);
160 return true;
164 * Sets type of storage device
165 * @param string $type Type of storage device
166 * @return bool
168 public function setStorageType($type)
170 if (!is_string($type))
172 throw new AOOSException($this->core(), $this->tr("not_string"));
173 return false;
176 $type = strtolower($type);
177 switch ($type)
179 case ("mysql"):
180 require_once("lib/AOOSStorageDeviceMySQL.php");
181 $this->_storageObject = new AOOSStorageDeviceMySQL($this->core());
182 break;
183 default:
184 throw new AOOSException($this->core(), $this->tr("storage_type_not_supported"));
185 return false;
190 * Returns the storage object
191 * @return AOOSStorageDevice
193 public function storageObject()
195 return $this->_storageObject;
199 * Inserts a model to $this->_table
200 * @param AOOSModel $model Model
201 * @return bool
203 public function insertModel(&$model)
205 if (!$this->_checkDevice() || !$this->_checkModel($model))
207 return false;
210 $data = $model->data(true);
211 $result = false;
212 $escape = $model->escape() ? null : true;
213 foreach ($data as $row)
215 $result = $this->insertArray($row, $escape);
218 return $result;
222 * Inserts an array to $this->_table
223 * @param array $a Array
224 * @return bool
226 public function insertArray($array, $escape = null)
228 if (!$this->_checkDevice() || !$this->_checkArray($array))
230 return false;
233 $result = false;
234 $result = $this->storageObject()->insert(array_keys($array), array_values($array), $escape);
236 return $result;
240 * Inserts a single value to the field of name $key in $this->_table
241 * @param $key Fieldname
242 * @param $value Value
243 * @return bool
245 public function insertValue($key, $value, $escape = null)
247 if (!$this->_checkDevice() || !$this->_checkValue($key, $value))
249 return false;
252 return $this->storageObject()->insert(array($key), array($value), $escape);
256 * Removes a number of rows from $this->_table
257 * @param int $count Number of rows to delete
258 * @return bool
260 public function removeRows($count = 1)
262 if (!$this->_checkDevice())
264 return false;
267 if(!is_int($count))
269 throw new AOOSException($this->core(), $this->tr("not_integer"));
270 return false;
275 * Selects values from the table and puts them into a model
276 * @param array|* $fields Fields to select
277 * @param string $where A where-clause of the form \code field = 'value' \code
278 * @param string $limit A limit-clause of the from \code start, end \code
279 * @param AOOSModel $model If given a model the values will be put directly into that model.
280 * @return AOOSModel
282 public function selectModel($fields, $where = null, $limit = null, $order = null, &$model = null)
284 $first = true;
286 if (!$this->_checkDevice())
288 return false;
291 if ($fields != "*")
293 if (!$this->_checkArray($fields))
295 return false;
299 // Do we have a valid where and limit-clause?
300 if (($where != null && !$this->_checkWhere($where)) || ($limit != null && !$this->_checkLimit($limit)))
302 return false;
305 // Make sure we have a model to put data into.
306 if ($model == null)
308 $model = new AOOSModel($this->core());
310 elseif (!$this->_checkModel($model))
312 return false;
315 while ($row = $this->storageObject()->select($fields, $where, $limit, $order, $this->_sort))
317 if ($first)
319 $model->setColumnIndex(array_keys($row));
320 $first = false;
322 $model->addRow();
324 foreach($row as $key => $value)
326 $model->setData($value, -1, $key);
330 if ($model->rows() == 0) {
331 return false;
333 return $model;
337 * Updates values in the table from the given model
338 * @param AOOSModel $model The model
339 * @param string|string $where A valid where clause. If "auto" is given where clauses will be made automatically.
340 * @return bool
342 public function updateFromModel(&$model, $where)
344 if (!$this->_checkDevice() || !$this->_checkModel($model) || !$this->_checkWhere($where))
346 return false;
349 if (strtolower($where) == "auto")
351 $f = $model->columnIndex();
352 $keys = array();
353 $values = $this->selectModel(array($f[0]))->getColumn($f[0], 0, $model->rows()-1);
354 foreach ($values as $i)
356 $keys[] = $f[0];
358 unset($f);
360 else
362 if (!$this->_checkWhere($where) && !is_array($where))
364 return false;
367 if (!is_array($where))
369 $split = explode("=", $where);
370 $keys = array(trim(rtrim($split[0])));
371 $values = array(trim(rtrim($split[1])));
372 unset($split);
374 else
376 $keys = array_keys($where);
377 $values = array_values($where);
381 // We only want to loop as long as we have where-clauses
382 $c = count($keys);
383 for ($i = 0; $i<$c; $i++)
385 $key = array_shift($keys);
386 $val = array_shift($values);
387 $w = $key." = ".$val;
388 unset($key);
389 unset($val);
390 $this->updateFromArray($model->getRow($i), $w);
393 return true;
397 * Updates values in the table based on the given array.
398 * Each element in the array is translated into a 'key = value' pair based on the array keys and values.
399 * @param array $array The array
400 * @param string $where A valid where clause
401 * @return bool
403 public function updateFromArray(&$array, $where)
405 if (!$this->_checkDevice() || !$this->_checkArray($array))
407 return false;
410 return $this->storageObject()->update(array_keys($array), array_values($array), $where);
414 * Deletes each row from the table which is equal to a row in the model
415 * @param AOOSModel $model The model
416 * @param int $limit Maximum times a matching row can be deleted
417 * @return bool
419 public function deleteFromModel(&$model, $limit = null)
421 if (!$this->_checkDevice() || !$this->_checkModel($model))
423 return false;
426 for($i = 0; $i < $model->rows(); $i++)
428 $this->deleteFromArray($model->getRow($i), $limit);
430 return true;
434 * Deletes a row from the table if a row matches the array in a such way that array keys matches field names and the corresponding array values matches the corresponding field values.
435 * @param array $array The array
436 * @param int $limit Maximum times a matching row can be deleted
437 * @return bool
439 public function deleteFromArray(&$array, $limit = null)
441 if (!$this->_checkDevice() || !$this->_checkArray($array) || ($limit != null && !is_int($limit)))
443 return false;
446 $sep = array();
447 $merged = "";
448 foreach($array as $key => $value)
450 $sep[] = $key." = ".$value;
452 $merged = implode(" AND ", $sep);
453 return $this->storageObject()->delete($merged, $limit);
457 * Sets a query if the selected storage type support it.
458 * @return bool
460 public function setQuery($query)
462 if (!is_string($query))
464 throw new AOOSException($this->core(), $this->tr("not_string"));
465 return false;
468 // Check if it supports it.
470 if (!$this->storageObject()->setQuery($query))
472 $str = $this->tr("query").": ".$query."<br />".
473 $this->tr("error").": ".mysql_error();
474 throw new AOOSException($this->core(), $this->tr("query_failed"), $str);
475 return false;
477 return true;
481 * Returns row count
482 * @param string $where An optional, valid where clause
483 * @return int|false
485 public function numRows($where = null)
487 if ($where != null && !$this->_checkWhere($where))
489 return false;
492 return $this->storageObject()->numRows($where);
495 public function setSort($sort) {
496 $sort = strtoupper($sort);
497 if ($sort != "ASC" && $sort != "DESC") {
498 throw new AOOSException($this->core(), $this->tr("not_ASC_or_DESC"), "", true, 1);
499 return false;
501 $this->_sort = $sort;
502 return true;