Added tr() and added type check in getTranslated()
[AOOS.git] / AOOSModel.php
blobf10fc17bd04f816282cdf6e1a76aa2a858bc547a
1 <?php
2 define("AOOSMODEL_TYPE_STRING" , 1);
3 define("AOOSMODEL_TYPE_INTEGER" , 2);
4 define("AOOSMODEL_TYPE_ARRAY" , 4);
5 define("AOOSMODEL_TYPE_AOOSMODEL" , 8);
6 define("AOOSMODEL_TYPE_UNKNOWN" , 16);
7 define("AOOSMODEL_TYPE_EMAIL" , 32);
9 define("AOOSMODEL_PROP_DATA_INCREASING" , 1);
10 define("AOOSMODEL_PROP_DATA_DECREASING" , 2);
11 define("AOOSMODEL_PROP_DATA_QUOTES" , 4);
12 define("AOOSMODEL_PROP_DATA_ESCAPE" , 8);
13 define("AOOSMODEL_PROP_DATA_NOHTML" , 16);
14 define("AOOSMODEL_PROP_DATA_HASH" , 32);
15 define("AOOSMODEL_PROP_DATA_STRIP" , 64);
17 define("AOOSMODEL_PROP_GUI_NOTEDITABLE" , 1<<8);
18 define("AOOSMODEL_PROP_GUI_PRIVATE" , 2<<8);
19 define("AOOSMODEL_PROP_FROM_DATABASE" , 4<<8);
20 define("AOOSMODEL_PROP_UNIQUE" , 8<<8);
22 /**
23 * Second-generation AOOSModel
24 * On the good side:
25 * - The addition of properties allowing easy per-column settings
26 * @author Sebastian Skejø
28 class AOOSModel extends AOOSModule {
29 const INTERN_DATA_UPDATED = 1;
30 const INTERN_DATA_REMOVED = 2;
31 const INTERN_DATA_INSERTED = 3;
33 private $_data = array();
34 private $_index = array();
35 private $_props = array();
36 private $_types = array();
37 private $_intern = array();
39 private $_source = null;
40 private $_table = null;
41 private $_connection = null;
44 private $_rows = 0;
45 private $_curRow = 0;
46 private $_curCol = 0;
48 /**
49 * Standard destructor
51 public function __destruct() {
54 /**
55 * Transforms to a printable string
57 public function __toString() {
58 return nl2br(str_replace(" ", "&nbsp;", print_r($this->data(), true)));
61 /**
62 * Appends a row to the end of the model with 0 as values unless $values is
63 * provided. Appended rows will NOT be inserted into database when AOOSModel::save() is called.
64 * @param $values If given null an empty row will be added. Otherwise an
65 * associative array is assumed.
66 * @param $ignore Flags to ignores when inserting data.
67 * @see insert
68 * @return true
70 public function appendRow($values = null, $ignore = 0) {
71 $this->_data[] = array_fill_keys($this->_index, 0);
72 $this->_rows++;
73 if (is_array($values)) {
74 $index = $this->columnIndex();
75 $last = $this->rows()-1;
76 foreach ($values as $key => $value) {
77 if (in_array($key, $index)) {
78 $this->setData($last, $key, $value, $ignore);
82 return true;
85 /**
86 * Sets the data of a single field. Fields updated this way will NOT be
87 * updated in the database when AOOSModel::save() is called. If the type of
88 * the inserted data doesn't match the column type, an AOOSTypeException is
89 * thrown. If $row is less than 0 or greater that the row count, an
90 * AOOSException is throw.
91 * @param $row An integer representing the row
92 * @param $column A column index
93 * @param $value Value
94 * @param $ignore Flags to ignore when inserting data
95 * @return bool
97 public function setData($row, $column, $value, $ignore = 0) {
98 if (!$this->inColumnIndex($column)) {
99 // Exception?
100 return false;
102 $props = $this->_props[$column];
103 $type = $this->_types[$column];
105 try {
106 $this->_checkType($value, $type);
108 catch (AOOSTypeException $e) {
109 throw $e;
110 return false;
113 $value = $this->_fixDataProps($value, $props, $ignore);
115 // XXX
116 if ($row < 0 || $row > $this->rows()) {
117 throw new AOOSException($this->core(), $this->tr("row_out_of_bounds"));
118 return false;
120 $this->_data[$row][$column] = $value;
121 return true;
125 * Sets a row of data
126 * @param $row The row number
127 * @param $values An associative array with column indices as keys and new values as
128 * array values
129 * @param $ignore Flags to ignore when inserting data
130 * @return bool
131 * @sa setData
133 public function setDataRow($row, $values, $ignore = 0) {
134 foreach ($values as $index => $value) {
135 if (!$this->setData($row, $index, $value, $ignore)) {
136 return false;
139 return true;
142 private function _checkType($value, $type) {
143 // Only type-props
144 $correct = false;
145 $continue = true;
146 if ($type & AOOSMODEL_TYPE_UNKNOWN) {
147 $correct = true;
148 $continue = false;
150 elseif($continue && $type & AOOSMODEL_TYPE_STRING) {
151 $correct = is_string($value);
152 $continue = false;
154 elseif($continue && $type & AOOSMODEL_TYPE_INTEGER) {
155 $correct = is_integer((int)$value);
156 $continue = false;
158 elseif($continue && $type & AOOSMODEL_TYPE_ARRAY) {
159 $correct = is_array($value);
160 $continue = false;
162 elseif($continue && $type & AOOSMODEL_TYPE_AOOSMODEL) {
163 $correct = $value instanceof AOOSModel;
164 $continue = false;
166 elseif($continue && $type & AOOSMODEL_TYPE_EMAIL) {
167 $correct = preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $value);
168 $continue = false;
171 if (!$correct) {
172 throw new AOOSTypeException($this->core(), "", "When inserting ".$value);
173 return false;
175 return true;
178 private function _fixDataProps($value, $props, $ignore = 0) {
179 // Only data props
180 if ($props & AOOSMODEL_PROP_DATA_NOHTML && !(AOOSMODEL_PROP_DATA_NOHTML & $ignore)) {
181 $value = htmlspecialchars($value);
184 if ($props & AOOSMODEL_PROP_DATA_ESCAPE && !(AOOSMODEL_PROP_DATA_ESCAPE & $ignore)) {
185 $value = mysql_real_escape_string($value);
188 if ($props & AOOSMODEL_PROP_DATA_STRIP && !(AOOSMODEL_PROP_DATA_STRIP & $ignore)) {
189 $value = rtrim(trim($value));
192 if ($props & AOOSMODEL_PROP_DATA_HASH && !(AOOSMODEL_PROP_DATA_HASH & $ignore)) {
193 $value = hash("sha256", $value);
195 if ($props & AOOSMODEL_PROP_DATA_QUOTES && !(AOOSMODEL_PROP_DATA_QUOTES & $ignore)) {
196 $first = substr($value, 0,1);
197 if ($first != "'" && $first != '"' && $first != substr($value, -1)) {
198 $value = "'".$value."'";
202 return $value;
206 * Returns a to-dimensional array containing the data.
207 * @return array
209 public function data() {
210 return $this->_data;
214 * Returns the column with the name $column
215 * @param $column The name of the column
216 * @param $offset Column values starts at this row
217 * @param $length The array of column values has this length
218 * @return array
220 public function getColumn($column, $start = 0, $length = null) {
221 if (!$this->inColumnIndex($column)) {
222 return false;
224 if ($length === null) {
225 $length = $this->rows();
227 if ($start < 0) {
228 $start = $this->rows() + $start;
230 $a = array();
231 for ($i= $start; $length > 0; $length--) {
232 $r = $this->getRow($i);
233 $a[] = $r[$column];
234 $i++;
236 return $a;
240 * Returns an array containing the columns of the given $row
241 * @param $row The row number. If this is negative the row selected is the
242 * $row'th number from the end.
243 * @return array
245 public function getRow($row) {
246 return array_pop(array_slice($this->data(), $row, 1));
250 * Returns the number of rows
251 * @return integer
253 public function rows() {
254 return $this->_rows;
258 * Returns only columns which match the given properties
259 * @param $props Properties
261 public function filter($props = 0, $offset = 0, $length = null) {
262 if ($length === null) {
263 $length = $this->rows();
265 $a = array();
266 for ($i = $offset; $length > 0; $length--) {
267 $r = $this->getRow($i);
268 $ra = array();
269 foreach ($this->_props as $col => $colprops) {
270 if ($colprops & $props) {
271 $ra[$col] = $r[$col];
274 $a[] = $ra;
275 $i++;
277 return $a;
281 * Returns the first row from $start which matches $match
282 * @param $match An associative array in which keys should match column
283 * indices and values should match values
284 * @param $start An integer representing the row from which search should.
285 * Defaults to 0.
286 * start
287 * @return Integer
288 * @sa findAll
290 public function find($match, $start = 0) {
291 if ($match && !($match = $this->_fixWhere($match))) {
292 return false;
294 for ($i = $start; $i < $this->rows(); $i++) {
295 $r = $this->getRow($i);
296 $fkey = key($match);
297 if ($r[$fkey] == $match[$fkey]) {
298 foreach ($match as $key => $val) {
299 if ($r[$key] != $val) {
300 continue 2;
303 return $i;
306 return false;
310 * Returns all rows which match $match, starting from $start
311 * @param $match The row to match against.
312 * @param $start An integer representing the row from which to start from.
313 * Defaults to 0.
314 * @return An array containing integers.
315 * @sa find
317 public function findAll($match, $start = 0, $length = null) {
318 if ($length === null) {
319 $length = $this->rows();
321 $i = $start;
322 $a = array();
323 while (true) {
324 if (!($f = $this->find($match, $i))) {
325 break;
327 $a[] = $f;
328 $i = ++$f;
330 $a = array_slice($a, 0, $length);
331 return count($a) ? $a : false;
335 * Sets a columns properties to be $property
336 * @param $column Column index name
337 * @param $type The type of the column
338 * @param $property An integer representing the property
339 * @return true
341 public function setProperty($column, $type, $property) {
342 if (!$this->inColumnIndex($column)) {
343 // Exception?
344 return false;
346 if ($property & AOOSMODEL_PROP_FROM_DATABASE) {
347 $property |= AOOSMODEL_PROP_DATA_QUOTES;
349 $this->_types[$column] = $type;
350 $this->_props[$column] = $property;
351 return true;
355 * Returns the properties of the given $column
356 * @param $column Name of the column
357 * @return integer
359 public function getProperty($column) {
360 if (!$this->inColumnIndex($column)) {
361 return false;
363 return $this->_props[$column];
367 * Toggles a given property using the ... operation.
368 * @param $column Column index name
369 * @param $property An integer representing the property to toggle
370 * @return true
372 public function toggleProperty($column, $property) {
373 if (!$this->inColumnIndex($column)) {
374 // Exception?
375 return false;
377 if ($property & AOOSMODEL_PROP_FROM_DATABASE) {
378 $property |= AOOSMODEL_PROP_DATA_QUOTES;
380 $this->_props[$column] ^= $property;
381 return true;
385 * Returns the type of the given $column
386 * @param $column Name of the column
387 * @return string
389 public function getType($column) {
390 if (!$this->inColumnIndex($column)) {
391 // Exception?
392 return false;
394 $type = $this->_types[$column];
395 $typename = 0;
396 $continue = true;
397 if ($type & AOOSMODEL_TYPE_UNKNOWN) {
398 $typename = "UNKNOWN";
399 $continue = false;
401 elseif($continue && $type & AOOSMODEL_TYPE_STRING) {
402 $typename = "STRING";
403 $continue = false;
405 elseif($continue && $type & AOOSMODEL_TYPE_INTEGER) {
406 $typename = "INTEGER";
407 $continue = false;
409 elseif($continue && $type & AOOSMODEL_TYPE_ARRAY) {
410 $typename = "ARRAY";
411 $continue = false;
413 elseif($continue && $type & AOOSMODEL_TYPE_AOOSMODEL) {
414 $typename = "AOOSModel";
415 $continue = false;
418 return $typename;
422 * Returns true if the given $property is set, otherwise return false
423 * @param $column Column index name
424 * @param $property An integer representing the property
425 * @return boolean
427 public function checkProperty($column, $property) {
428 if (!$this->inColumnIndex($column)) {
429 // Exception?
430 return false;
432 if ($this->_props[$column] & $property) {
433 return true;
435 return false;
439 * Sets the column index to be $index. Note: this resets the properties AND
440 * data
441 * If $index isn't an array an AOOSException is thrown.
442 * @param $index An array containing the column indices
443 * @return true
445 public function setColumnIndex($index) {
446 if (!is_array($index)) {
447 throw new AOOSTypeException($this->core(), $this->tr("not_array"));
448 return false;
450 $this->_index = $index;
451 $this->_props = array_fill_keys($index, 0);
452 return true;
456 * Returns the column index
457 * @return array
459 public function columnIndex() { return $this->_index; }
462 * Returns true if the given $index is in the column index. Otherwise returns
463 * false.
464 * @param $index Name of the index
465 * @return bool
467 public function inColumnIndex($index) {
468 return in_array($index, $this->_index);
473 * Sets the table from in which data is contained
474 * @param $table Table name
475 * @return true
477 public function setTable($table) {
478 $this->_table = $this->core()->getSetting("DBPrefix").$table;
479 return true;
483 * Returns the table name
484 * @return string
486 public function table() {
487 return $this->_table;
491 * Sets the type of source from which data is fetched, inserted and deleted.
492 * @param $source The type of source, e.g. "mysql".
493 * @return true
495 public function setSource($source) {
496 $this->_source = strtolower($source);
497 return true;
501 * Returns the type of source in a string
502 * @return string
504 public function source() {
505 return $this->_source;
509 * Populates the model. If the model is successfully populated $this is
510 * returned. Otherwise false is returned.
511 * @param $where An associative array containing the where-keys and values.
512 * This means that array("FOO" => "BAR") will expand to WHERE FOO = 'BAR'
513 * @param $order An array with two rows. First row defines the row to order
514 * by, the second row defines the order. This means that array("BAZ",
515 * "DESC") will expand to ORDER BY BAZ DESC.
516 * @param $limit An array with two rows, where the first row is the start
517 * limit and the second row is the end limit. This means that array(0,2)
518 * will expand into LIMIT 0,2
519 * @return
521 public function populate($where = null, $order = null, $limit = null) {
522 $this->_reset();
523 if ($where && !($where = $this->_fixWhere($where))) {
524 return false;
526 $fields = array();
527 foreach ($this->_props as $col => $prop) {
528 if ($prop & AOOSMODEL_PROP_FROM_DATABASE) {
529 $fields[] = $col;
532 if (!($values = $this->_connection()->select($fields, $where, $order, $limit))) {
533 throw new AOOSException($this->core(), $this->tr("couldnt_select_values"));
534 return false;
536 foreach ($values as $row) {
537 $this->appendRow($row, AOOSMODEL_PROP_DATA_HASH);
539 return $this;
543 * Inserts the given array into the model. Note that data isn't saved to
544 * database before calling AOOSModel::save()
545 * @param $values An associative array, in which the array keys corresponds
546 * to column indices and the array values are the value that should be
547 * inserted.
549 public function insert($values) {
550 $this->appendRow($values);
551 $values = $this->filter(AOOSMODEL_PROP_FROM_DATABASE, -1, 1);
552 $this->_intern[] = array(AOOSModel::INTERN_DATA_INSERTED, $values);
553 return true;
557 * Deletes the row which matches $where. As with AOOSModel::insert() and
558 * AOOSModel::update(), changes aren't saved to database before AOOSModel::save() is
559 * called. An AOOSException is thrown if no rows match $where.
560 * @param $where Either an associative array containing the where-keys and values.
561 * This means that array("FOO" => "BAR") will expand to WHERE FOO = 'BAR' or
562 * an integer representing a row number.
563 * @param $limit An array with two rows, where the first row is the start
564 * limit and the second row is the end limit. This means that array(0,2)
565 * will expand into LIMIT 0,2 or a single integer
567 public function remove($where, $limit = null) {
568 $limit = $this->_fixLimit($limit);
569 if (is_array($where)) {
570 if (!($w = $this->findAll($where, $limit[0], $limit[1]))) {
571 throw new AOOSException($this->core(), $this->tr("no_rows_found"), "", true, 2);
572 return false;
575 elseif (is_integer($where)) {
576 $w = array($where);
577 $where = $this->getRow($where);
579 else {
580 return false;
582 foreach($w as $row) {
583 unset($this->_data[$row]);
584 $this->_rows--;
586 $where = $this->_fixWhere($where);
587 $this->_intern[] = array(AOOSModel::INTERN_DATA_REMOVED, $where, $limit);
588 return 0;
592 * Updates the row that matches $where with the values, $values. Changes
593 * aren't saved to database until AOOSModel::save() is called..
594 * @param $values An associative array, in which the array keys matches
595 * column indices and the array values are the values to use to update the
596 * selected row
597 * @param $where Either an associative array containing the where-keys and values.
598 * This means that array("FOO" => "BAR") will expand to WHERE FOO = 'BAR' or
599 * an integer representing a row number
600 * @param $limit An array with two rows, where the first row is the start
601 * limit and the second row is the end limit. This means that array(0,2)
602 * will expand into LIMIT 0,2
604 public function update($values, $where, $limit = null) {
605 $limit = $this->_fixLimit($limit);
606 $w = $this->findAll($where, $limit[0], $limit[1]);
607 foreach ($w as $row) {
608 $this->setDataRow($row, $values);
610 $where = $this->_fixWhere($where);
611 $values = $this->_fixWhere($values);
612 $this->_intern[] = array(AOOSModel::INTERN_DATA_UPDATED, $values, $where, $limit);
613 return 0;
617 * Creates the model as a new table in the database.
618 * @return bool
620 public function create() {
621 if (!$this->_connection()) {
622 return false;
624 return $this->_connection()->create($this->_types, $this->_props);
628 * Saves the changes caused by AOOSModel::insert(), AOOSModel::remove() or
629 * AOOSModel::update()
631 public function save() {
632 if (!$this->_connection()) {
633 return false;
635 foreach ($this->_intern as $key => $row) {
636 switch($row[0]) {
637 case(AOOSModel::INTERN_DATA_INSERTED):
638 if (!$this->_connection()->insert($row[1])) {
639 return false;
641 break;
642 case(AOOSModel::INTERN_DATA_REMOVED):
643 if (!$this->_connection()->remove($row[1], $row[2])) {
644 return false;
646 case(AOOSModel::INTERN_DATA_UPDATED):
647 if (!$this->_connection()->update($row[1], $row[2], $row[3])) {
648 return false;
651 unset($this->_intern[$key]);
653 return true;
656 private function _connect() {
657 if ($this->_connection) {
658 return $this->_connection;
660 if (!$this->source() || !$this->table()) {
661 throw new AOOSException($this->core(), $this->tr("no_source_or_table_set"));
662 return false;
664 switch ($this->source()) {
665 case("mysql"):
666 require_once("lib/AOOSMysqlInterface.php");
667 $this->_connection = new AOOSMysqlInterface($this->core());
668 break;
670 $this->_connection->setTable($this->table());
673 private function _connection() {
674 if (!$this->_connection) {
675 try {
676 $this->_connect();
678 catch (AOOSException $e) {
679 throw $e;
680 return false;
683 return $this->_connection;
687 * \internal Fixes where clauses so that the given values are correctly
688 * formatted according to the properties for their column
690 private function _fixWhere($where) {
691 $ci = $this->columnIndex();
693 if (!is_array($where)) {
694 return false;
697 foreach ($where as $key => $value) {
698 if (!in_array($key, $ci)) {
699 unset($where[$ci]);
700 continue;
702 $where[$key] = $this->_fixDataProps($value, $this->getProperty($key));
704 return $where;
708 * \internal Fixes a limit
710 private function _fixLimit($l) {
711 $limit = array(0,$this->rows());
712 if (is_integer($l)) {
713 $limit[1] = $l;
715 elseif(is_array($l)) {
716 $limit = $l;
718 return $limit;
721 private function _reset() {
722 $this->_data = array();
723 $this->_connect();
724 $this->_rows = 0;
728 * Dummy function
730 public function dataModelDefinition() { return 0; }
732 // vim: textwidth=80