KumbiaPHP beta2-dev
Framework PHP en español
|
00001 <?php 00026 require CORE_PATH . 'libs/db/db.php'; 00067 class KumbiaActiveRecord 00068 { 00069 //Soportados 00070 00076 protected $db; 00082 protected $database; 00088 protected $schema; 00094 protected $source; 00100 protected $count; 00106 protected $fields = array(); 00112 protected $primary_key = array(); 00118 protected $non_primary = array(); 00124 protected $not_null = array(); 00130 protected $_with_default = array(); 00136 protected $alias = array(); 00143 protected $is_view = false; 00149 protected $debug = false; 00155 protected $logger = false; 00161 protected $persistent = false; 00162 00176 protected $_validates = array('inclusion_in' => array(), 'exclusion_of' => array(), 'numericality_of' => array(), 00177 'format_of' => array(), 'date_in' => array(), 'email_in' => array(), 'uniqueness_of' => array()); 00183 protected $_in = array(); 00189 protected $_at = array(); 00196 protected $_where_pk; 00202 protected $_dumped = false; 00209 protected $_dump_lock = false; 00215 protected $_data_type = array(); 00221 protected $_has_one = array(); 00227 protected $_has_many = array(); 00233 protected $_belongs_to = array(); 00239 protected $_has_and_belongs_to_many = array(); 00245 protected $parent_of = array(); 00249 protected static $_models = array(); 00253 protected static $models = array(); 00259 function __construct($data=null) 00260 { 00261 if (!$this->source) { 00262 $this->_model_name(); 00263 } 00264 00268 if (method_exists($this, 'initialize')) { 00269 $this->initialize(); 00270 } 00271 00275 $this->_connect(); 00276 00277 if ($data) { 00278 if (!is_array($data)) 00279 $data = Util::getParams(func_get_args()); 00280 $this->dump_result_self($data); 00281 } 00282 } 00287 protected function _model_name() 00288 { 00289 if (!$this->source) { 00290 $this->source = Util::uncamelize(get_class($this)); 00291 } 00292 } 00298 public function set_source($source) 00299 { 00300 $this->source = $source; 00301 } 00307 public function get_source() 00308 { 00309 return $this->source; 00310 } 00316 public function set_database($database) 00317 { 00318 $this->database = $database; 00319 } 00325 public function get_database() 00326 { 00327 if ($this->database) { 00328 return $this->database; 00329 } else { 00330 $core = Config::read('config'); 00331 return $core['application']['database']; 00332 } 00333 } 00340 public function is_dumped() 00341 { 00342 return $this->_dumped; 00343 } 00350 function __get($property) 00351 { 00352 if (!$this->_dump_lock) { 00353 if (!isset($this->$property)) { 00354 if (array_key_exists($property, $this->_belongs_to)) { 00355 $relation = $this->_belongs_to[$property]; 00356 return self::get($relation->model)->find_first($this->{$relation->fk}); 00357 } elseif (array_key_exists($property, $this->_has_one)) { 00358 $relation = $this->_has_one[$property]; 00359 if ($this->{$this->primary_key[0]}) { 00360 return self::get($relation->model)->find_first("{$relation->fk}={$this->db->add_quotes($this->{$this->primary_key[0]}) }"); 00361 } else { 00362 return null; 00363 } 00364 } elseif (array_key_exists($property, $this->_has_many)) { 00365 $relation = $this->_has_many[$property]; 00366 if ($this->{$this->primary_key[0]}) { 00367 return self::get($relation->model)->find("{$relation->fk}={$this->db->add_quotes($this->{$this->primary_key[0]}) }"); 00368 } else { 00369 return array(); 00370 } 00371 } elseif (array_key_exists($property, $this->_has_and_belongs_to_many)) { 00372 $relation = $this->_has_and_belongs_to_many[$property]; 00373 $relation_model = self::get($relation->model); 00374 $relation_model->dump_model(); 00375 $source = $this->source; 00376 $relation_source = $relation_model->source; 00381 if (!isset($relation->through)) { 00382 if ($source > $relation_source) { 00383 $relation->through = "{$this->source}_{$relation_source}"; 00384 } else { 00385 $relation->through = "{$relation_source}_{$this->source}"; 00386 } 00387 } 00388 if ($this->{$this->primary_key[0]}) { 00389 return self::get($relation->model)->find_all_by_sql("SELECT $relation_source.* FROM $relation_source, {$relation->through}, $source 00390 WHERE {$relation->through}.{$relation->key} = {$this->db->add_quotes($this->{$this->primary_key[0]}) } 00391 AND {$relation->through}.{$relation->fk} = $relation_source.{$relation_model->primary_key[0]} 00392 AND {$relation->through}.{$relation->key} = $source.{$this->primary_key[0]} 00393 ORDER BY $relation_source.{$relation_model->primary_key[0]}"); 00394 } else { 00395 return array(); 00396 } 00397 } else { 00398 return null; 00399 } 00400 } 00401 } 00402 return $this->$property; 00403 } 00411 function __set($property, $value) 00412 { 00413 if (!$this->_dump_lock) { 00414 if (!isset($this->$property) && is_object($value) && is_subclass_of($value, 'ActiveRecordBase')) { 00415 if (array_key_exists($property, $this->_belongs_to)) { 00416 $relation = $this->_belongs_to[$property]; 00417 $value->dump_model(); 00418 $this->{$relation->fk} = $value->{$value->primary_key[0]}; 00419 } elseif (array_key_exists($property, $this->_has_one)) { 00420 $relation = $this->_has_one[$property]; 00421 $value->{$relation->fk} = $this->{$this->primary_key[0]}; 00422 } 00423 } elseif ($property == "source") { 00424 $value = ActiveRecord::sql_item_sanizite($value); 00425 } 00426 } 00427 $this->$property = $value; 00428 } 00433 public function __call($method, $args = array()) 00434 { 00435 $has_relation = false; 00436 if (substr($method, 0, 8) == "find_by_") { 00437 $field = substr($method, 8); 00438 ActiveRecord::sql_item_sanizite($field); 00439 if (isset($args[0])) { 00440 $arg = array("conditions: $field = {$this->db->add_quotes($args[0]) }"); 00441 unset($args[0]); 00442 } else { 00443 $arg = array(); 00444 } 00445 return call_user_func_array(array($this, "find_first"), array_merge($arg, $args)); 00446 } 00447 if (substr($method, 0, 9) == "count_by_") { 00448 $field = substr($method, 9); 00449 ActiveRecord::sql_item_sanizite($field); 00450 if (isset($args[0])) { 00451 $arg = array("conditions: $field = {$this->db->add_quotes($args[0]) }"); 00452 unset($args[0]); 00453 } else { 00454 $arg = array(); 00455 } 00456 return call_user_func_array(array($this, "count"), array_merge($arg, $args)); 00457 } 00458 if (substr($method, 0, 12) == "find_all_by_") { 00459 $field = substr($method, 12); 00460 ActiveRecord::sql_item_sanizite($field); 00461 if (isset($args[0])) { 00462 $arg = array("conditions: $field = {$this->db->add_quotes($args[0]) }"); 00463 unset($args[0]); 00464 } else { 00465 $arg = array(); 00466 } 00467 return call_user_func_array(array($this, "find"), array_merge($arg, $args)); 00468 } 00469 $model = preg_replace('/^get/', '', $method); 00470 $mmodel = Util::uncamelize($model); 00471 if (array_key_exists($mmodel, $this->_belongs_to)) { 00472 $has_relation = true; 00473 $relation = $this->_belongs_to[$mmodel]; 00474 return self::get($relation->model)->find_first($this->{$relation->fk}); 00475 } 00476 if (array_key_exists($mmodel, $this->_has_many)) { 00477 $has_relation = true; 00478 $relation = $this->_has_many[$mmodel]; 00479 if ($this->{$this->primary_key[0]}) { 00480 return self::get($relation->model)->find("{$relation->fk}={$this->db->add_quotes($this->{$this->primary_key[0]}) }"); 00481 } else { 00482 return array(); 00483 } 00484 } 00485 if (array_key_exists($mmodel, $this->_has_one)) { 00486 $has_relation = true; 00487 $relation = $this->_has_one[$mmodel]; 00488 if ($this->{$this->primary_key[0]}) { 00489 return self::get($relation->model)->find_first("{$relation->fk}={$this->db->add_quotes($this->{$this->primary_key[0]}) }"); 00490 } else { 00491 return null; 00492 } 00493 } 00494 if (array_key_exists($mmodel, $this->_has_and_belongs_to_many)) { 00495 $has_relation = true; 00496 $relation = $this->_has_and_belongs_to_many[$mmodel]; 00497 if ($this->{$this->primary_key[0]}) { 00498 $source = $this->source; 00499 $relation_model = self::get($relation->model); 00500 $relation_model->dump_model(); 00501 $relation_source = $relation_model->source; 00506 if (!isset($relation->through)) { 00507 if ($source > $relation_source) { 00508 $relation->through = "{$this->source}_{$relation_source}"; 00509 } else { 00510 $relation->through = "{$relation_source}_{$this->source}"; 00511 } 00512 } 00513 return self::get($relation->model)->find_all_by_sql("SELECT $relation_source.* FROM $relation_source, {$relation->through}, $source 00514 WHERE {$relation->through}.{$relation->key} = {$this->db->add_quotes($this->{$this->primary_key[0]}) } 00515 AND {$relation->through}.{$relation->fk} = $relation_source.{$relation_model->primary_key[0]} 00516 AND {$relation->through}.{$relation->key} = $source.{$this->primary_key[0]} 00517 ORDER BY $relation_source.{$relation_model->primary_key[0]}"); 00518 } else { 00519 return array(); 00520 } 00521 } 00522 try { 00523 if (method_exists($this, $method)) { 00524 call_user_func_array(array($this, $method), $args); 00525 } else { 00526 if ($has_relation) { 00527 throw new KumbiaException("No existe el modelo '$model' para relacionar con ActiveRecord::{$this->source}"); 00528 } else { 00529 throw new KumbiaException("No existe el método '$method' en ActiveRecord::" . get_class($this)); 00530 } 00531 } 00532 } 00533 catch(Exception $e) { 00534 $this->exceptions($e); 00535 } 00536 return $this->$method($args); 00537 } 00543 protected function _connect($new_connection = false) 00544 { 00545 if (!is_object($this->db) || $new_connection) { 00546 $this->db = Db::factory($this->database, $new_connection); 00547 } 00548 $this->db->debug = $this->debug; 00549 $this->db->logger = $this->logger; 00550 $this->dump(); 00551 } 00556 public function dump_model() 00557 { 00558 $this->_connect(); 00559 } 00566 protected function dump() 00567 { 00568 if ($this->_dumped) { 00569 return false; 00570 } 00571 $a = array(); 00572 if ($this->source) { 00573 $this->source = str_replace(";", '', strtolower($this->source)); 00574 } else { 00575 $this->_model_name(); 00576 if (!$this->source) { 00577 return false; 00578 } 00579 } 00580 $table = $this->source; 00581 $schema = $this->schema; 00582 if (!count(self::get_meta_data($this->source))) { 00583 $this->_dumped = true; 00584 $this->_dump_info($table, $schema); 00585 if (!count($this->primary_key)) { 00586 if (!$this->is_view) { 00587 throw new KumbiaException("No se ha definido una llave primaria para la tabla '$table' esto imposibilita crear el ActiveRecord para esta entidad"); 00588 return false; 00589 } 00590 } 00591 } else { 00592 if (!$this->is_dumped()) { 00593 $this->_dumped = true; 00594 $this->_dump_info($table, $schema); 00595 } 00596 } 00597 return true; 00598 } 00606 protected function _dump_info($table, $schema = '') 00607 { 00608 $this->_dump_lock = true; 00609 if (!count(self::get_meta_data($table))) { 00610 $meta_data = $this->db->describe_table($table, $schema); 00611 if ($meta_data) { 00612 self::set_meta_data($table, $meta_data); 00613 } 00614 } 00615 foreach(self::get_meta_data($table) as $field) { 00616 $this->fields[] = $field['Field']; 00617 $aliasAux = $field['Field']; 00618 if ($field['Key'] == 'PRI') { 00619 $this->primary_key[] = $field['Field']; 00620 $this->alias[$field['Field']] = 'Código'; 00621 } else $this->non_primary[] = $field['Field']; 00628 if ($field['Null'] == 'NO' && !(isset($field['Default']) && $field['Default'])) { 00629 $this->not_null[] = $field['Field']; 00630 } 00631 if (isset($field['Default']) && $field['Default']) { 00632 $this->_with_default[] = $field['Field']; 00633 } 00634 if ($field['Type']) { 00635 $this->_data_type[$field['Field']] = strtolower($field['Type']); 00636 } 00637 if (substr($field['Field'], strlen($field['Field']) - 3, 3) == '_at') { 00638 $this->_at[] = $field['Field']; 00639 $aliasAux = substr($field['Field'], 0, -3); 00640 } 00641 if (substr($field['Field'], strlen($field['Field']) - 3, 3) == '_in') { 00642 $this->_in[] = $field['Field']; 00643 $aliasAux = substr($field['Field'], 0, -3); 00644 } 00645 if (substr($field['Field'], strlen($field['Field']) - 3, 3) == '_id') { 00646 $aliasAux = substr($field['Field'], 0, -3); 00647 } 00648 //humanizando el alias 00649 $this->alias[$field['Field']] = ucwords(strtr($aliasAux,'_-',' ')); 00650 } 00651 $this->_dump_lock = false; 00652 return true; 00653 } 00660 public function get_alias($key=null) 00661 { 00662 if($key && array_key_exists($key, $this->alias)){ 00663 return $this->alias[$key]; 00664 } else { 00665 throw new KumbiaException("No se pudo obtener el Alias, porque el key: \"$key\" no existe."); 00666 } 00667 return $this->alias; 00668 } 00675 public function set_alias($key=null, $value=null) 00676 { 00677 if($key && array_key_exists($key, $this->alias)){ 00678 $this->alias[$key] = $value; 00679 } else { 00680 throw new KumbiaException("No se pudo asignar el nuevo valor al Alias, porque el key: \"$key\" no existe."); 00681 } 00682 00683 } 00689 public function commit() 00690 { 00691 return $this->db->commit(); 00692 } 00698 public function rollback() 00699 { 00700 return $this->db->rollback(); 00701 } 00707 public function begin() 00708 { 00709 $this->_connect(true); 00710 return $this->db->begin(); 00711 } 00718 public function find_all_by_sql($sqlQuery) 00719 { 00720 $results = array(); 00721 foreach($this->db->fetch_all($sqlQuery) as $result) { 00722 $results[] = $this->dump_result($result); 00723 } 00724 return $results; 00725 } 00732 public function find_by_sql($sqlQuery) 00733 { 00734 $row = $this->db->fetch_one($sqlQuery); 00735 if ($row !== false) { 00736 $this->dump_result_self($row); 00737 return $this->dump_result($row); 00738 } else { 00739 return false; 00740 } 00741 } 00748 public function sql($sqlQuery) 00749 { 00750 return $this->db->query($sqlQuery); 00751 } 00762 public function find_first($what = '') 00763 { 00764 $what = Util::getParams(func_get_args()); 00765 $select = "SELECT "; 00766 if (isset($what['columns'])) { 00767 $select.= ActiveRecord::sql_sanizite($what['columns']); 00768 } elseif (isset($what['distinct'])) { 00769 $select.= 'DISTINCT '; 00770 $select.= $what['distinct'] ? ActiveRecord::sql_sanizite($what['distinct']) : join(",", $this->fields); 00771 } else { 00772 $select.= join(",", $this->fields); 00773 } 00774 if ($this->schema) { 00775 $select.= " FROM {$this->schema}.{$this->source}"; 00776 } else { 00777 $select.= " FROM {$this->source}"; 00778 } 00779 $what['limit'] = 1; 00780 $select.= $this->convert_params_to_sql($what); 00781 $resp = false; 00782 try { 00783 $result = $this->db->fetch_one($select); 00784 if ($result) { 00785 $this->dump_result_self($result); 00786 $resp = $this->dump_result($result); 00787 } 00788 } 00789 catch(Exception $e) { 00790 $this->exceptions($e); 00791 } 00792 return $resp; 00793 } 00808 public function find($what = '') 00809 { 00810 $what = Util::getParams(func_get_args()); 00811 $select = "SELECT "; 00812 if (isset($what['columns'])) { 00813 $select.= $what['columns'] ? ActiveRecord::sql_sanizite($what['columns']) : join(",", $this->fields); 00814 } elseif (isset($what['distinct'])) { 00815 $select.= 'DISTINCT '; 00816 $select.= $what['distinct'] ? ActiveRecord::sql_sanizite($what['distinct']) : join(",", $this->fields); 00817 } else { 00818 $select.= join(",", $this->fields); 00819 } 00820 if ($this->schema) { 00821 $select.= " FROM {$this->schema}.{$this->source}"; 00822 } else { 00823 $select.= " FROM {$this->source}"; 00824 } 00825 $select.= $this->convert_params_to_sql($what); 00826 $results = array(); 00827 $all_results = $this->db->in_query($select); 00828 foreach($all_results AS $result) { 00829 $results[] = $this->dump_result($result); 00830 } 00831 00832 $this->count = count($results, COUNT_NORMAL); 00833 if (isset($what[0]) && is_numeric($what[0])) { 00834 if (!isset($results[0])) { 00835 $this->count = 0; 00836 return false; 00837 } else { 00838 $this->dump_result_self($all_results[0]); 00839 $this->count = 1; 00840 return $results[0]; 00841 } 00842 } else { 00843 $this->count = count($results, COUNT_NORMAL); 00844 return $results; 00845 } 00846 } 00847 /* 00848 * Arma una consulta SQL con el parametro $what, así: 00849 * $what = Util::getParams(func_get_args()); 00850 * $select = "SELECT * FROM Clientes"; 00851 * $select.= $this->convert_params_to_sql($what); 00852 * 00853 * @param string $what 00854 * @return string 00855 */ 00856 public function convert_params_to_sql($what = '') 00857 { 00858 $select = ''; 00859 if (is_array($what)) { 00860 if (!isset($what['conditions'])) { 00861 if (!isset($this->primary_key[0]) && (isset($this->id) || $this->is_view)) { 00862 $this->primary_key[0] = "id"; 00863 } 00864 ActiveRecord::sql_item_sanizite($this->primary_key[0]); 00865 if (isset($what[0])) { 00866 if (is_numeric($what[0])) { 00867 $what['conditions'] = "{$this->primary_key[0]} = {$this->db->add_quotes($what[0]) }"; 00868 } else { 00869 if ($what[0] == '') { 00870 $what['conditions'] = "{$this->primary_key[0]} = ''"; 00871 } else { 00872 $what['conditions'] = $what[0]; 00873 } 00874 } 00875 } 00876 } 00877 if (isset($what['join'])) { 00878 $select.= " {$what['join']}"; 00879 } 00880 if (isset($what['conditions'])) { 00881 $select.= " WHERE {$what['conditions']}"; 00882 } 00883 if (isset($what['group'])) { 00884 $select.= " GROUP BY {$what['group']}"; 00885 } 00886 if (isset($what['having'])) { 00887 $select.= " HAVING {$what['having']}"; 00888 } 00889 if (isset($what['order'])) { 00890 ActiveRecord::sql_sanizite($what['order']); 00891 $select.= " ORDER BY {$what['order']}"; 00892 } 00893 $limit_args = array($select); 00894 if (isset($what['limit'])) { 00895 array_push($limit_args, "limit: $what[limit]"); 00896 } 00897 if (isset($what['offset'])) { 00898 array_push($limit_args, "offset: $what[offset]"); 00899 } 00900 if (count($limit_args) > 1) { 00901 $select = call_user_func_array(array($this, 'limit'), $limit_args); 00902 } 00903 } else { 00904 if (strlen($what)) { 00905 if (is_numeric($what)) { 00906 $select.= "WHERE {$this->primary_key[0]} = '$what'"; 00907 } else { 00908 $select.= "WHERE $what"; 00909 } 00910 } 00911 } 00912 return $select; 00913 } 00914 /* 00915 * Devuelve una clausula LIMIT adecuada al RDBMS empleado 00916 * 00917 * limit: maxima cantidad de elementos a mostrar 00918 * offset: desde que elemento se comienza a mostrar 00919 * 00920 * @param string $sql consulta select 00921 * @return String clausula LIMIT adecuada al RDBMS empleado 00922 */ 00923 public function limit($sql) 00924 { 00925 $args = func_get_args(); 00926 return call_user_func_array(array($this->db, 'limit'), $args); 00927 } 00936 public function distinct($what = '') 00937 { 00938 $what = Util::getParams(func_get_args()); 00939 if ($this->schema) { 00940 $table = $this->schema . "." . $this->source; 00941 } else { 00942 $table = $this->source; 00943 } 00944 if (!isset($what['columns'])) { 00945 $what['columns'] = $what['0']; 00946 } else { 00947 if (!$what['columns']) { 00948 $what['columns'] = $what['0']; 00949 } 00950 } 00951 $what['columns'] = ActiveRecord::sql_sanizite($what['columns']); 00952 $select = "SELECT DISTINCT {$what['columns']} FROM $table "; 00956 unset($what[0]); 00957 $select.= $this->convert_params_to_sql($what); 00958 $results = array(); 00959 foreach($this->db->fetch_all($select) as $result) { 00960 $results[] = $result[0]; 00961 } 00962 return $results; 00963 } 00970 static public function static_select_one($sql) 00971 { 00972 $db = Db::factory(); 00973 if (substr(ltrim($sql), 0, 7) != "SELECT") { 00974 $sql = "SELECT " . $sql; 00975 } 00976 $num = $db->fetch_one($sql); 00977 return $num[0]; 00978 } 00985 public function count($what = '') 00986 { 00987 $what = Util::getParams(func_get_args()); 00988 if ($this->schema) { 00989 $table = "{$this->schema}.{$this->source}"; 00990 } else { 00991 $table = $this->source; 00992 } 00993 if (isset($what['distinct']) && $what['distinct']) { 00994 if (isset($what['group']) || isset($what['order'])) { 00995 $select = "SELECT COUNT(*) FROM (SELECT DISTINCT {$what['distinct']} FROM $table "; 00996 $select.= $this->convert_params_to_sql($what); 00997 $select.= ') AS t '; 00998 } else { 00999 $select = "SELECT COUNT(DISTINCT {$what['distinct']}) FROM $table "; 01000 $select.= $this->convert_params_to_sql($what); 01001 } 01002 } else { 01003 $select = "SELECT COUNT(*) FROM $table "; 01004 $select.= $this->convert_params_to_sql($what); 01005 } 01006 $num = $this->db->fetch_one($select); 01007 return $num[0]; 01008 } 01015 public function average($what = '') 01016 { 01017 $what = Util::getParams(func_get_args()); 01018 if (isset($what['column'])) { 01019 if (!$what['column']) { 01020 $what['column'] = $what[0]; 01021 } 01022 } else { 01023 $what['column'] = $what[0]; 01024 } 01025 unset($what[0]); 01026 ActiveRecord::sql_item_sanizite($what['column']); 01027 if ($this->schema) { 01028 $table = "{$this->schema}.{$this->source}"; 01029 } else { 01030 $table = $this->source; 01031 } 01032 $select = "SELECT AVG({$what['column']}) FROM $table "; 01033 $select.= $this->convert_params_to_sql($what); 01034 $num = $this->db->fetch_one($select); 01035 return $num[0]; 01036 } 01037 public function sum($what = '') 01038 { 01039 $what = Util::getParams(func_get_args()); 01040 if (isset($what['column'])) { 01041 if (!$what['column']) { 01042 $what['column'] = $what[0]; 01043 } 01044 } else { 01045 $what['column'] = $what[0]; 01046 } 01047 unset($what[0]); 01048 ActiveRecord::sql_item_sanizite($what['column']); 01049 if ($this->schema) { 01050 $table = "{$this->schema}.{$this->source}"; 01051 } else { 01052 $table = $this->source; 01053 } 01054 $select = "SELECT SUM({$what['column']}) FROM $table "; 01055 $select.= $this->convert_params_to_sql($what); 01056 $num = $this->db->fetch_one($select); 01057 return $num[0]; 01058 } 01065 public function maximum($what = '') 01066 { 01067 $what = Util::getParams(func_get_args()); 01068 if (isset($what['column'])) { 01069 if (!$what['column']) { 01070 $what['column'] = $what[0]; 01071 } 01072 } else { 01073 $what['column'] = $what[0]; 01074 } 01075 unset($what[0]); 01076 ActiveRecord::sql_item_sanizite($what['column']); 01077 if ($this->schema) { 01078 $table = "{$this->schema}.{$this->source}"; 01079 } else { 01080 $table = $this->source; 01081 } 01082 $select = "SELECT MAX({$what['column']}) FROM $table "; 01083 $select.= $this->convert_params_to_sql($what); 01084 $num = $this->db->fetch_one($select); 01085 return $num[0]; 01086 } 01093 public function minimum($what = '') 01094 { 01095 $what = Util::getParams(func_get_args()); 01096 if (isset($what['column'])) { 01097 if (!$what['column']) { 01098 $what['column'] = $what[0]; 01099 } 01100 } else { 01101 $what['column'] = $what[0]; 01102 } 01103 unset($what[0]); 01104 ActiveRecord::sql_item_sanizite($what['column']); 01105 if ($this->schema) { 01106 $table = "{$this->schema}.{$this->source}"; 01107 } else { 01108 $table = $this->source; 01109 } 01110 $select = "SELECT MIN({$what['column']}) FROM $table "; 01111 $select.= $this->convert_params_to_sql($what); 01112 $num = $this->db->fetch_one($select); 01113 return $num[0]; 01114 } 01121 public function count_by_sql($sqlQuery) 01122 { 01123 $num = $this->db->fetch_one($sqlQuery); 01124 return $num[0]; 01125 } 01134 public function dump_result($result){ 01135 $obj = clone $this; 01139 if (isset($result['type'])) { 01140 if (in_array($result['type'], $this->parent_of)) { 01141 if (class_exists($result['type'])) { 01142 $obj = new $result['type']; 01143 unset($result['type']); 01144 } 01145 } 01146 } 01147 $this->_dump_lock = true; 01148 if (is_array($result)) { 01149 foreach($result as $k => $r) { 01150 if (!is_numeric($k)) { 01151 $obj->$k = stripslashes($r); 01152 } 01153 } 01154 } 01155 $this->_dump_lock = false; 01156 return $obj; 01157 } 01165 public function dump_result_self($result) 01166 { 01167 $this->_dump_lock = true; 01168 if (is_array($result)) { 01169 foreach($result as $k => $r) { 01170 if (!is_numeric($k)) { 01171 $this->$k = stripslashes($r); 01172 } 01173 } 01174 } 01175 $this->_dump_lock = false; 01176 } 01183 public function create_from_request($form = null) 01184 { 01185 if(!$form){ 01186 $form = $this->source; 01187 } 01188 $result = $this->create($_REQUEST[$form]); 01189 if(!$result) { 01190 Dispatcher::get_controller()->$form = $_REQUEST[$form]; 01191 } 01192 return $result; 01193 } 01200 public function save_from_request($form = null) 01201 { 01202 if(!$form){ 01203 $form = $this->source; 01204 } 01205 $result = $this->save($_REQUEST[$form]); 01206 if(!$result) { 01207 Dispatcher::get_controller()->$form = $_REQUEST[$form]; 01208 } 01209 return $result; 01210 } 01217 public function update_from_request($form = null) 01218 { 01219 if(!$form){ 01220 $form = $this->source; 01221 } 01222 $result = $this->update($_REQUEST[$form]); 01223 if(!$result) { 01224 Dispatcher::get_controller()->$form = $_REQUEST[$form]; 01225 } 01226 return $result; 01227 } 01234 public function create() 01235 { 01236 if (func_num_args() > 0) { 01237 $params = Util::getParams(func_get_args()); 01238 $values = (isset($params[0]) && is_array($params[0])) ? $params[0] : $params; 01239 foreach($this->fields as $field) { 01240 if (isset($values[$field])) { 01241 $this->$field = $values[$field]; 01242 } 01243 } 01244 } 01245 if ($this->primary_key[0] == 'id') { 01246 $this->id = null; 01247 } 01248 return $this->save(); 01249 } 01256 function exists($where_pk = '') 01257 { 01258 if ($this->schema) { 01259 $table = "{$this->schema}.{$this->source}"; 01260 } else { 01261 $table = $this->source; 01262 } 01263 if (!$where_pk) { 01264 $where_pk = array(); 01265 foreach($this->primary_key as $key) { 01266 if ($this->$key) { 01267 $where_pk[] = " $key = '{$this->$key}'"; 01268 } 01269 } 01270 if (count($where_pk)) { 01271 $this->_where_pk = join(" AND ", $where_pk); 01272 } else { 01273 return 0; 01274 } 01275 $query = "SELECT COUNT(*) FROM $table WHERE {$this->_where_pk}"; 01276 } else { 01277 if (is_numeric($where_pk)) { 01278 $query = "SELECT COUNT(*) FROM $table WHERE id = '$where_pk'"; 01279 } else { 01280 $query = "SELECT COUNT(*) FROM $table WHERE $where_pk"; 01281 } 01282 } 01283 $num = $this->db->fetch_one($query); 01284 return $num[0]; 01285 } 01291 public function save($values=null) 01292 { 01293 if ($values) { 01294 if(!is_array($values)) 01295 $values = Util::getParams(func_get_args()); 01296 foreach($this->fields as $field) { 01297 if (isset($values[$field])) { 01298 $this->$field = $values[$field]; 01299 } 01300 } 01301 } 01302 $ex = $this->exists(); 01303 if ($this->schema) { 01304 $table = $this->schema . "." . $this->source; 01305 } else { 01306 $table = $this->source; 01307 } 01308 #Run Validation Callbacks Before 01309 if (method_exists($this, 'before_validation')) { 01310 if ($this->before_validation() == 'cancel') { 01311 return false; 01312 } 01313 } else { 01314 if (isset($this->before_validation)) { 01315 $method = $this->before_validation; 01316 if ($this->$method() == 'cancel') { 01317 return false; 01318 } 01319 } 01320 } 01321 if(!$ex){ 01322 if (method_exists($this, "before_validation_on_create")) { 01323 if ($this->before_validation_on_create() == 'cancel') { 01324 return false; 01325 } 01326 } else { 01327 if (isset($this->before_validation_on_create)) { 01328 $method = $this->before_validation_on_create; 01329 if ($this->$method() == 'cancel') { 01330 return false; 01331 } 01332 } 01333 } 01334 } 01335 if($ex){ 01336 if (method_exists($this, "before_validation_on_update")) { 01337 if ($this->before_validation_on_update() == 'cancel') { 01338 return false; 01339 } 01340 } else { 01341 if (isset($this->before_validation_on_update)) { 01342 $method = $this->before_validation_on_update; 01343 if($this->$method() == 'cancel') { 01344 return false; 01345 } 01346 } 01347 } 01348 } 01349 01354 if(isset($this->_validates['presence_of'])) { 01355 foreach($this->_validates['presence_of'] as $f => $opt) { 01356 if (isset($this->$f) && (is_null($this->$f) || $this->$f == '')) { 01357 if (!$ex && $f == 'id') 01358 continue; 01359 if (isset($opt['message'])) { 01360 Flash::error($opt['message']); 01361 return false; 01362 } else { 01363 $field = isset($opt['field']) ? $opt['field'] : $f; 01364 Flash::error("Error: El campo $field no puede ser nulo"); 01365 return false; 01366 } 01367 } 01368 } 01369 } 01370 01378 foreach ($this->not_null as $f) { 01379 if(in_array($f, $this->_with_default)) { 01380 continue; 01381 } 01382 01383 if (!isset($this->$f) || is_null($this->$f) || $this->$f == '') { 01384 if (!$ex && $f == 'id') { 01385 continue; 01386 } 01387 if (!$ex && in_array($f, $this->_at)) { 01388 continue; 01389 } 01390 if ($ex && in_array($f, $this->_in)) { 01391 continue; 01392 } 01393 Flash::error("Error: El campo $f no puede ser nulo"); 01394 return false; 01395 } 01396 } 01397 01402 if(isset($this->_validates['length_of'])) { 01403 foreach($this->_validates['length_of'] as $f => $opt) { 01404 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01405 $field = isset($opt['field']) ? $opt['field'] : $f; 01406 01407 if (strlen($this->$f) < $opt['min']) { 01408 if (isset($opt['too_short'])) 01409 Flash::error($opt['too_short']); 01410 else 01411 Flash::error("Error: El campo $field debe tener como mínimo $opt[min] caracteres"); 01412 return false; 01413 } 01414 01415 if (strlen($this->$f) > $opt['max']) { 01416 if (isset($opt['too_long'])) 01417 Flash::error($opt['too_long']); 01418 else 01419 Flash::error("Error: El campo $field debe tener como máximo $opt[max] caracteres"); 01420 return false; 01421 } 01422 } 01423 } 01424 } 01425 01430 foreach($this->_validates['inclusion_in'] as $f => $opt) { 01431 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01432 if (!in_array($this->$f, $opt['list'])) { 01433 if (isset($opt['message'])) { 01434 Flash::error($opt['message']); 01435 } else { 01436 $field = isset($opt['field']) ? $opt['field'] : $f; 01437 Flash::error("$field debe tener un valor entre (" . join(",", $opt['list']) . ")"); 01438 } 01439 return false; 01440 } 01441 } 01442 } 01443 01448 foreach($this->_validates['exclusion_of'] as $f => $opt) { 01449 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01450 if (in_array($this->$f, $opt['list'])) { 01451 if (isset($opt['message'])) { 01452 Flash::error($opt['message']); 01453 } else { 01454 $field = isset($opt['field']) ? $opt['field'] : $f; 01455 Flash::error("$field no debe tener un valor entre (" . join(",", $opt['list']) . ")"); 01456 } 01457 return false; 01458 } 01459 } 01460 } 01461 01466 foreach($this->_validates['numericality_of'] as $f => $opt) { 01467 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01468 if (!is_numeric($this->$f)) { 01469 if (isset($opt['message'])) { 01470 Flash::error($opt['message']); 01471 } else { 01472 $field = isset($opt['field']) ? $opt['field'] : $f; 01473 Flash::error("$field debe tener un valor numérico"); 01474 } 01475 return false; 01476 } 01477 } 01478 } 01479 01484 foreach($this->_validates['format_of'] as $f => $opt) { 01485 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01486 if (!filter_var($this->$f, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>$opt['pattern'])))) { 01487 if (isset($opt['message'])) { 01488 Flash::error($opt['message']); 01489 } else { 01490 $field = isset($opt['field']) ? $opt['field'] : $f; 01491 Flash::error("Formato erroneo para $field"); 01492 } 01493 return false; 01494 } 01495 } 01496 } 01497 01502 foreach($this->_validates['date_in'] as $f => $opt) { 01503 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01504 if (!filter_var($this->$f, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^\d{4}[-\/](0[1-9]|1[012])[-\/](0[1-9]|[12][0-9]|3[01])$/")))) { 01505 if (isset($opt['message'])) { 01506 Flash::error($opt['message']); 01507 } else { 01508 $field = isset($opt['field']) ? $opt['field'] : $f; 01509 Flash::error("Formato de fecha erroneo para $field"); 01510 } 01511 return false; 01512 } 01513 } 01514 } 01515 01520 foreach($this->_validates['email_in'] as $f=>$opt) { 01521 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01522 if (!filter_var($this->$f, FILTER_VALIDATE_EMAIL)) { 01523 if (isset($opt['message'])) { 01524 Flash::error($opt['message']); 01525 } else { 01526 $field = isset($opt['field']) ? $opt['field'] : $f; 01527 Flash::error("Formato de e-mail erroneo en el campo $field"); 01528 } 01529 return false; 01530 } 01531 } 01532 } 01533 01538 // parche para que no tome encuenta el propio registro 01539 // al validar campos unicos, ya que si lo toma en cuenta 01540 // lanzará error de validacion porque ya existe un registro 01541 // con igual valor en el campo unico. 01542 $and_condition = $ex ? " AND id != '$this->id'" : ''; 01543 foreach($this->_validates['uniqueness_of'] as $f => $opt) { 01544 if (isset($this->$f) && !is_null($this->$f) && $this->$f != '') { 01545 $result = $this->db->fetch_one("SELECT COUNT(*) FROM $table WHERE $f = {$this->db->add_quotes($this->$f)} $and_condition"); 01546 if ($result[0]) { 01547 if (isset($opt['message'])) { 01548 Flash::error($opt['message']); 01549 } else { 01550 $field = isset($opt['field']) ? $opt['field'] : $f; 01551 Flash::error("El valor '{$this->$f}' ya existe para el campo $field"); 01552 } 01553 return false; 01554 } 01555 } 01556 } 01557 01558 #Run Validation Callbacks After 01559 if(!$ex){ 01560 if (method_exists($this, "after_validation_on_create")) { 01561 if ($this->after_validation_on_create() == 'cancel') { 01562 return false; 01563 } 01564 } else { 01565 if (isset($this->after_validation_on_create)) { 01566 $method = $this->after_validation_on_create; 01567 if ($this->$method() == 'cancel') { 01568 return false; 01569 } 01570 } 01571 } 01572 } 01573 if($ex){ 01574 if (method_exists($this, "after_validation_on_update")) { 01575 if ($this->after_validation_on_update() == 'cancel') { 01576 return false; 01577 } 01578 } else { 01579 if (isset($this->after_validation_on_update)) { 01580 $method = $this->after_validation_on_update; 01581 if ($this->$method() == 'cancel') return false; 01582 } 01583 } 01584 } 01585 01586 if (method_exists($this, 'after_validation')) { 01587 if ($this->after_validation() == 'cancel') { 01588 return false; 01589 } 01590 } else { 01591 if (isset($this->after_validation)) { 01592 $method = $this->after_validation; 01593 if ($this->$method() == 'cancel') { 01594 return false; 01595 } 01596 } 01597 } 01598 # Run Before Callbacks 01599 if (method_exists($this, "before_save")) { 01600 if ($this->before_save() == 'cancel') { 01601 return false; 01602 } 01603 } else { 01604 if (isset($this->before_save)) { 01605 $method = $this->before_save; 01606 if ($this->$method() == 'cancel') { 01607 return false; 01608 } 01609 } 01610 } 01611 if($ex){ 01612 if (method_exists($this, "before_update")) { 01613 if ($this->before_update() == 'cancel') { 01614 return false; 01615 } 01616 } else { 01617 if (isset($this->before_update)) { 01618 $method = $this->before_update; 01619 if ($this->$method() == 'cancel') { 01620 return false; 01621 } 01622 } 01623 } 01624 } 01625 if(!$ex){ 01626 if (method_exists($this, "before_create")) { 01627 if ($this->before_create() == 'cancel') { 01628 return false; 01629 } 01630 } else { 01631 if (isset($this->before_create)) { 01632 $method = $this->before_create; 01633 if ($this->$method() == 'cancel') { 01634 return false; 01635 } 01636 } 01637 } 01638 } 01639 $environment = Config::read('databases'); 01640 $config = $environment[$this->get_database()]; 01641 if ($ex) { 01642 $fields = array(); 01643 $values = array(); 01644 foreach($this->non_primary as $np) { 01645 $np = ActiveRecord::sql_item_sanizite($np); 01646 if (in_array($np, $this->_in)) { 01647 if ($config['type'] == 'oracle') { 01648 $this->$np = date("Y-m-d"); 01649 } else { 01650 $this->$np = date("Y-m-d G:i:s"); 01651 } 01652 } 01653 if (isset($this->$np)) { 01654 $fields[] = $np; 01655 if (is_null($this->$np) || $this->$np == '') { 01656 $values[] = 'NULL'; 01657 } else { 01661 if ($this->_data_type[$np] == 'date' && $config['type'] == 'oracle') { 01662 $values[] = "TO_DATE(" . $this->db->add_quotes($this->$np) . ", 'YYYY-MM-DD')"; 01663 } else { 01664 $values[] = $this->db->add_quotes($this->$np); 01665 } 01666 } 01667 } 01668 } 01669 $val = $this->db->update($table, $fields, $values, $this->_where_pk); 01670 } else { 01671 $fields = array(); 01672 $values = array(); 01673 foreach($this->fields as $field) { 01674 if ($field != 'id' && !$this->id) { 01675 if (in_array($field, $this->_at)) { 01676 if ($config['type'] == 'oracle') { 01677 $this->$field = date("Y-m-d"); 01678 } else { 01679 $this->$field = date("Y-m-d G:i:s"); 01680 } 01681 } 01682 if (in_array($field, $this->_in)) { 01683 unset($this->$field); 01684 } 01685 01686 if(isset($this->$field) && $this->$field != '') { 01687 $fields[] = ActiveRecord::sql_sanizite($field); 01688 01689 if(($this->_data_type[$field] == 'datetime' || $this->_data_type[$field] == 'date') && $config['type'] == 'mysql'){ 01690 $values[] = $this->db->add_quotes(date("Y-m-d G:i:s",strtotime($this->$field))); 01691 } elseif ($this->_data_type[$field] == 'date' && $config['type'] == 'oracle') { 01692 //Se debe especificar el formato de fecha en Oracle 01693 $values[] = "TO_DATE(" . $this->db->add_quotes($this->$field) . ", 'YYYY-MM-DD')"; 01694 } else { 01695 $values[] = $this->db->add_quotes($this->$field); 01696 } 01697 01698 } elseif (!in_array($field, $this->_with_default)) { 01699 $fields[] = ActiveRecord::sql_sanizite($field); 01700 $values[] = 'NULL'; 01701 } 01702 01703 } else { 01707 if ($config['type'] == 'oracle') { 01708 if (!$this->id) { 01709 $fields[] = "id"; 01710 $values[] = $this->source . "_id_seq.NEXTVAL"; 01711 } 01712 } 01713 if ($config['type'] == 'informix') { 01714 if (!$this->id) { 01715 $fields[] = "id"; 01716 $values[] = 0; 01717 } 01718 } 01719 } 01720 } 01721 01722 $val = $this->db->insert($table, $values, $fields); 01723 } 01724 if (!isset($config['pdo']) && $config['type'] == 'oracle') { 01725 $this->commit(); 01726 } 01727 if (!$ex) { 01728 //$this->db->logger = true; 01729 $m = $this->db->last_insert_id($table, $this->primary_key[0]); 01730 $this->find_first($m); 01731 } 01732 if ($val) { 01733 if($ex){ 01734 if (method_exists($this, "after_update")) { 01735 if ($this->after_update() == 'cancel') { 01736 return false; 01737 } 01738 } else { 01739 if (isset($this->after_update)) { 01740 $method = $this->after_update; 01741 if ($this->$method() == 'cancel') { 01742 return false; 01743 } 01744 } 01745 } 01746 } 01747 if(!$ex){ 01748 if (method_exists($this, "after_create")) { 01749 if ($this->after_create() == 'cancel') { 01750 return false; 01751 } 01752 } else { 01753 if (isset($this->after_create)) { 01754 $method = $this->after_create; 01755 if ($this->$method() == 'cancel') { 01756 return false; 01757 } 01758 } 01759 } 01760 } 01761 if (method_exists($this, "after_save")) { 01762 if ($this->after_save() == 'cancel') { 01763 return false; 01764 } 01765 } else { 01766 if (isset($this->after_save)) { 01767 $method = $this->after_save; 01768 if ($this->$method() == 'cancel') { 01769 return false; 01770 } 01771 } 01772 } 01773 return $val; 01774 } else { 01775 return false; 01776 } 01777 } 01785 function find_all_by($field, $value) 01786 { 01787 ActiveRecord::sql_item_sanizite($field); 01788 return $this->find("conditions: $field = {$this->db->add_quotes($value) }"); 01789 } 01796 function update() 01797 { 01798 if (func_num_args() > 0) { 01799 $params = Util::getParams(func_get_args()); 01800 $values = (isset($params[0]) && is_array($params[0])) ? $params[0] : $params; 01801 foreach($this->fields as $field) { 01802 if (isset($values[$field])) { 01803 $this->$field = $values[$field]; 01804 } 01805 } 01806 } 01807 if ($this->exists()) { 01808 if (method_exists($this, 'before_change')) { 01809 $obj = clone $this; 01810 if($this->before_change($obj->find($this->id)) == 'cancel'){ 01811 return false; 01812 } 01813 unset($obj); 01814 } 01815 if($this->save()){ 01816 if (method_exists($this, 'after_change')) { 01817 if ($this->after_change($this) == 'cancel') { 01818 return false; 01819 } 01820 } 01821 return true; 01822 } 01823 } else { 01824 Flash::error('No se puede actualizar porque el registro no existe'); 01825 return false; 01826 } 01827 } 01833 public function delete($what = '') 01834 { 01835 if (func_num_args() > 1) { 01836 $what = Util::getParams(func_get_args()); 01837 } 01838 if ($this->schema) { 01839 $table = $this->schema . "." . $this->source; 01840 } else { 01841 $table = $this->source; 01842 } 01843 $conditions = ''; 01844 if (is_array($what)) { 01845 if ($what["conditions"]) { 01846 $conditions = $what["conditions"]; 01847 } 01848 } else { 01849 if (is_numeric($what)) { 01850 ActiveRecord::sql_sanizite($this->primary_key[0]); 01851 $conditions = "{$this->primary_key[0]} = '$what'"; 01852 } else { 01853 if ($what) { 01854 $conditions = $what; 01855 } else { 01856 ActiveRecord::sql_sanizite($this->primary_key[0]); 01857 $conditions = "{$this->primary_key[0]} = '{$this->{$this->primary_key[0]}}'"; 01858 } 01859 } 01860 } 01861 if (method_exists($this, "before_delete")) { 01862 if ($this->id) { 01863 $this->find($this->id); 01864 } 01865 if ($this->before_delete() == 'cancel') { 01866 return false; 01867 } 01868 } else { 01869 if (isset($this->before_delete)) { 01870 if ($this->id) { 01871 $this->find($this->id); 01872 } 01873 $method = $this->before_delete; 01874 if ($this->$method() == 'cancel') { 01875 return false; 01876 } 01877 } 01878 } 01879 $val = $this->db->delete($table, $conditions); 01880 if ($val) { 01881 if (method_exists($this, "after_delete")) { 01882 if ($this->after_delete() == 'cancel') { 01883 return false; 01884 } 01885 } else { 01886 if (isset($this->after_delete)) { 01887 $method = $this->after_delete; 01888 if ($this->$method() == 'cancel') { 01889 return false; 01890 } 01891 } 01892 } 01893 } 01894 return $val; 01895 } 01903 public function update_all($values) { 01904 $params = array(); 01905 if ($this->schema) { 01906 $table = $this->schema . "." . $this->source; 01907 } else { 01908 $table = $this->source; 01909 } 01910 if (func_num_args() > 1) { 01911 $params = Util::getParams(func_get_args()); 01912 } 01913 if (!isset($params['conditions']) || !$params['conditions']) { 01914 if (isset($params[1])) { 01915 $params['conditions'] = $params[1]; 01916 } else { 01917 $params['conditions'] = ''; 01918 } 01919 } 01920 if ($params['conditions']) { 01921 $params['conditions'] = " WHERE " . $params['conditions']; 01922 } 01923 $sql = "UPDATE $table SET $values {$params['conditions']}"; 01924 $limit_args = array($sql); 01925 if (isset($params['limit'])) { 01926 array_push($limit_args, "limit: $params[limit]"); 01927 } 01928 if (isset($params['offset'])) { 01929 array_push($limit_args, "offset: $params[offset]"); 01930 } 01931 if (count($limit_args) > 1) { 01932 $sql = call_user_func_array(array($this, 'limit'), $limit_args); 01933 } 01934 $environment = Config::read('databases'); 01935 $config = $environment[$this->get_database()]; 01936 if (!isset($config->pdo) || !$config->pdo) { 01937 if ($config['type'] == "informix") { 01938 $this->db->set_return_rows(false); 01939 } 01940 } 01941 return $this->db->query($sql); 01942 } 01949 public function delete_all($conditions = '') { 01950 $limit = ''; 01951 if ($this->schema) { 01952 $table = $this->schema . "." . $this->source; 01953 } else { 01954 $table = $this->source; 01955 } 01956 if (func_num_args() > 1) { 01957 $params = Util::getParams(func_get_args()); 01958 $limit_args = array($select); 01959 if (isset($params['limit'])) { 01960 array_push($limit_args, "limit: $params[limit]"); 01961 } 01962 if (isset($params['offset'])) { 01963 array_push($limit_args, "offset: $params[offset]"); 01964 } 01965 if (count($limit_args) > 1) { 01966 $select = call_user_func_array(array($this, 'limit'), $limit_args); 01967 } 01968 } 01969 return $this->db->delete($table, $conditions); 01970 } 01981 public function inspect() { 01982 $inspect = array(); 01983 foreach($this->fields as $field) { 01984 if (!is_array($field)) { 01985 $inspect[] = "$field: {$this->$field}"; 01986 } 01987 } 01988 return join(", ", $inspect); 01989 } 02004 protected function validates_presence_of($field, $params=array()) 02005 { 02006 if (is_string($params)) 02007 $params = Util::getParams(func_get_args()); 02008 02009 $this->_validates['presence_of'][$field] = $params; 02010 } 02024 protected function validates_length_of($field, $max, $min=0, $params=array()) 02025 { 02026 if (is_string($params)) 02027 $params = Util::getParams(func_get_args()); 02028 02029 $this->_validates['length_of'][$field] = $params; 02030 $this->_validates['length_of'][$field]['min'] = $min; 02031 $this->_validates['length_of'][$field]['max'] = $max; 02032 } 02043 protected function validates_inclusion_in($field, $list, $params=array()) 02044 { 02045 if (is_string($params)) 02046 $params = Util::getParams(func_get_args()); 02047 02048 $this->_validates['inclusion_in'][$field] = $params; 02049 $this->_validates['inclusion_in'][$field]['list'] = $list; 02050 } 02061 protected function validates_exclusion_of($field, $list, $params=array()) 02062 { 02063 if (is_string($params)) 02064 $params = Util::getParams(func_get_args()); 02065 02066 $this->_validates['exclusion_of'][$field] = $params; 02067 $this->_validates['exclusion_of'][$field]['list'] = $list; 02068 } 02079 protected function validates_format_of($field, $pattern, $params=array()) 02080 { 02081 if (is_string($params)) 02082 $params = Util::getParams(func_get_args()); 02083 02084 $this->_validates['format_of'][$field] = $params; 02085 $this->_validates['format_of'][$field]['pattern'] = $pattern; 02086 } 02096 protected function validates_numericality_of($field, $params=array()) 02097 { 02098 if (is_string($params)) 02099 $params = Util::getParams(func_get_args()); 02100 02101 $this->_validates['numericality_of'][$field] = $params; 02102 } 02112 protected function validates_email_in($field, $params=array()) 02113 { 02114 if (is_string($params)) 02115 $params = Util::getParams(func_get_args()); 02116 02117 $this->_validates['email_in'][$field] = $params; 02118 } 02128 protected function validates_uniqueness_of($field, $params=array()) 02129 { 02130 if (is_string($params)) 02131 $params = Util::getParams(func_get_args()); 02132 02133 $this->_validates['uniqueness_of'][$field] = $params; 02134 } 02144 protected function validates_date_in($field, $params=array()) 02145 { 02146 if (is_string($params)) 02147 $params = Util::getParams(func_get_args()); 02148 02149 $this->_validates['date_in'][$field] = $params; 02150 } 02157 public function is_a_numeric_type($field) 02158 { 02159 if (strpos(" " . $this->_data_type[$field], "int") || strpos(" " . $this->_data_type[$field], "decimal") || strpos(" " . $this->_data_type[$field], "number")) { 02160 return true; 02161 } else { 02162 return false; 02163 } 02164 } 02171 static function get_meta_data($table) 02172 { 02173 if (isset(self::$models[$table])) { 02174 return self::$models[$table]; 02175 } elseif(PRODUCTION) { 02176 02177 $metadata = Cache::driver()->get($table, 'kumbia.models'); 02178 if($metadata) { 02179 return self::$models[$table] = unserialize($metadata); 02180 } 02181 } 02182 return array(); 02183 } 02190 static function set_meta_data($table, $meta_data) 02191 { 02192 if(PRODUCTION) { 02193 Cache::driver()->save(serialize($meta_data), Config::get('config.application.metadata_lifetime'), $table, 'kumbia.models'); 02194 } 02195 self::$models[$table] = $meta_data; 02196 return true; 02197 } 02198 /******************************************************************************************* 02199 * Metodos para generacion de relaciones 02200 *******************************************************************************************/ 02209 protected function has_one($relation) 02210 { 02211 $params = Util::getParams(func_get_args()); 02212 for ($i = 0;isset($params[$i]);$i++) { 02213 $relation = Util::uncamelize($params[$i]); 02214 if (!array_key_exists($relation, $this->_has_one)) { 02215 $this->_has_one[$relation] = new stdClass(); 02216 $this->_has_one[$relation]->model = isset($params['model']) ? $params['model'] : $relation; 02217 $this->_has_one[$relation]->fk = isset($params['fk']) ? $params['fk'] : Util::uncamelize(get_class($this)) . '_id'; 02218 } 02219 } 02220 } 02229 protected function belongs_to($relation) 02230 { 02231 $params = Util::getParams(func_get_args()); 02232 for ($i = 0;isset($params[$i]);$i++) { 02233 $relation = Util::uncamelize($params[$i]); 02234 if (!array_key_exists($relation, $this->_belongs_to)) { 02235 $this->_belongs_to[$relation] = new stdClass(); 02236 $this->_belongs_to[$relation]->model = isset($params['model']) ? $params['model'] : $relation; 02237 $this->_belongs_to[$relation]->fk = isset($params['fk']) ? $params['fk'] : "{$relation}_id"; 02238 } 02239 } 02240 } 02249 protected function has_many($relation) 02250 { 02251 $params = Util::getParams(func_get_args()); 02252 for ($i = 0;isset($params[$i]);$i++) { 02253 $relation = Util::uncamelize($params[$i]); 02254 if (!array_key_exists($relation, $this->_has_many)) { 02255 $this->_has_many[$relation] = new stdClass(); 02256 $this->_has_many[$relation]->model = isset($params['model']) ? $params['model'] : $relation; 02257 $this->_has_many[$relation]->fk = isset($params['fk']) ? $params['fk'] : Util::uncamelize(get_class($this)) . '_id'; 02258 } 02259 } 02260 } 02271 protected function has_and_belongs_to_many($relation) 02272 { 02273 $params = Util::getParams(func_get_args()); 02274 for ($i = 0;isset($params[$i]);$i++) { 02275 $relation = Util::uncamelize($params[$i]); 02276 if (!array_key_exists($relation, $this->_has_and_belongs_to_many)) { 02277 $this->_has_and_belongs_to_many[$relation] = new stdClass(); 02278 $this->_has_and_belongs_to_many[$relation]->model = isset($params['model']) ? $params['model'] : $relation; 02279 $this->_has_and_belongs_to_many[$relation]->fk = isset($params['fk']) ? $params['fk'] : "{$relation}_id"; 02280 $this->_has_and_belongs_to_many[$relation]->key = isset($params['key']) ? $params['key'] : Util::uncamelize(get_class($this)) . '_id'; 02281 if (isset($params['through'])) { 02282 $this->_has_and_belongs_to_many[$relation]->through = $params['through']; 02283 } 02284 } 02285 } 02286 } 02295 public function parent_of($parent) 02296 { 02297 $parents = func_get_args(); 02298 foreach($parents as $parent) { 02299 if (!in_array($parent, $this->parent_of)) { 02300 $this->parent_of[] = $parent; 02301 } 02302 } 02303 } 02310 public static function sql_item_sanizite($sql_item) 02311 { 02312 $sql_item = trim($sql_item); 02313 if ($sql_item !== '' && $sql_item !== null) { 02314 $sql_temp = preg_replace('/\s+/', '', $sql_item); 02315 if (!preg_match('/^[a-zA-Z0-9_\.]+$/', $sql_temp)) { 02316 throw new KumbiaException("Se esta tratando de ejecutar una operacion maliciosa!"); 02317 } 02318 } 02319 return $sql_item; 02320 } 02327 public static function sql_sanizite($sql_item) 02328 { 02329 $sql_item = trim($sql_item); 02330 if ($sql_item !== '' && $sql_item !== null) { 02331 $sql_temp = preg_replace('/\s+/', '', $sql_item); 02332 if (!preg_match('/^[a-zA-Z_0-9\,\(\)\.\*]+$/', $sql_temp)) { 02333 throw new KumbiaException("Se esta tratando de ejecutar una operacion maliciosa!"); 02334 } 02335 } 02336 return $sql_item; 02337 } 02343 protected function exceptions($e) 02344 { 02345 throw $e; 02346 } 02351 public function __toString() 02352 { 02353 return "<" . get_class() . " Object>"; 02354 } 02365 public function paginate() 02366 { 02367 $args = func_get_args(); 02368 array_unshift($args, $this); 02369 //if(!class_exists('Paginator')){ 02370 require_once CORE_PATH . 'libs/kumbia_active_record/behaviors/paginate.php'; 02371 //} 02372 return call_user_func_array(array('Paginator' , 'paginate'), $args); 02373 } 02385 public function paginate_by_sql($sql) 02386 { 02387 $args = func_get_args(); 02388 array_unshift($args, $this); 02389 //if(!class_exists('Paginator')){ 02390 require_once CORE_PATH . 'libs/kumbia_active_record/behaviors/paginate.php'; 02391 //} 02392 return call_user_func_array(array('Paginator' , 'paginate_by_sql'), $args); 02393 } 02398 public function __sleep() 02399 { 02403 $this->db = null; 02404 02405 return array_keys(get_object_vars($this)); 02406 } 02411 public function __wakeup() 02412 { 02416 $this->_connect(); 02417 } 02425 public static function get($model) 02426 { 02427 if(isset(self::$_models[$model])) { 02428 return self::$_models[$model]; 02429 } 02430 02434 $Model = Util::camelcase(basename($model)); 02435 02439 if(!class_exists($Model, false)) { 02443 $file = APP_PATH . "models/$model.php"; 02444 if(is_file($file)) { 02445 include $file; 02446 } else { 02447 throw new KumbiaException(null, 'no_model'); 02448 } 02449 } 02450 02451 self::$_models[$model] = $obj = new $Model(); 02452 return $obj; 02453 } 02459 public function to_json() 02460 { 02461 return json_encode($this); 02462 } 02468 public function to_array() 02469 { 02470 return ((array) $this); 02471 } 02478 public function serialize() 02479 { 02480 return serialize($this); 02481 } 02482 02483 }