Removed unused method AkAR->_validateFindOptions().
[akelos.git] / lib / AkActiveRecord.php
blob7c0b4ac6fffdb5d5e04b6ecfc1adc2af43e1e77a
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 // +----------------------------------------------------------------------+
5 // | Akelos Framework - http://www.akelos.org |
6 // +----------------------------------------------------------------------+
7 // | Copyright (c) 2002-2006, Akelos Media, S.L. & Bermi Ferrer Martinez |
8 // | Released under the GNU Lesser General Public License, see LICENSE.txt|
9 // +----------------------------------------------------------------------+
11 /**
12 * @package ActiveRecord
13 * @subpackage Base
14 * @component Active Record
15 * @author Bermi Ferrer <bermi a.t akelos c.om> 2004 - 2007
16 * @author Kaste 2007
17 * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
18 * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
21 require_once(AK_LIB_DIR.DS.'AkActiveRecord'.DS.'AkAssociatedActiveRecord.php');
22 require_once(AK_LIB_DIR.DS.'AkActiveRecord'.DS.'AkDbAdapter.php');
24 /**#@+
25 * Constants
27 // Akelos args is a short way to call functions that is only intended for fast prototyping
28 defined('AK_ENABLE_AKELOS_ARGS') ? null : define('AK_ENABLE_AKELOS_ARGS', false);
29 // Use setColumnName if available when using set('column_name', $value);
30 defined('AK_ACTIVE_RECORD_INTERNATIONALIZE_MODELS_BY_DEFAULT') ? null : define('AK_ACTIVE_RECORD_INTERNATIONALIZE_MODELS_BY_DEFAULT', true);
31 defined('AK_ACTIVE_RECORD_ENABLE_AUTOMATIC_SETTERS_AND_GETTERS') ? null : define('AK_ACTIVE_RECORD_ENABLE_AUTOMATIC_SETTERS_AND_GETTERS', false);
32 defined('AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS') ? null : define('AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS', AK_ACTIVE_RECORD_ENABLE_AUTOMATIC_SETTERS_AND_GETTERS);
33 defined('AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS') ? null : define('AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS', AK_ACTIVE_RECORD_ENABLE_AUTOMATIC_SETTERS_AND_GETTERS);
34 defined('AK_ACTIVE_RECORD_ENABLE_PERSISTENCE') ? null : define('AK_ACTIVE_RECORD_ENABLE_PERSISTENCE', AK_ENVIRONMENT != 'testing');
35 defined('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA') ? null : define('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA', AK_ACTIVE_RECORD_ENABLE_PERSISTENCE && AK_ENVIRONMENT != 'development');
36 defined('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE') ? null : define('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE', 300);
37 defined('AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES') ? null : define('AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES', true);
38 defined('AK_ACTIVE_RECORD_SKIP_SETTING_ACTIVE_RECORD_DEFAULTS') ? null : define('AK_ACTIVE_RECORD_SKIP_SETTING_ACTIVE_RECORD_DEFAULTS', false);
39 defined('AK_NOT_EMPTY_REGULAR_EXPRESSION') ? null : define('AK_NOT_EMPTY_REGULAR_EXPRESSION','/.+/');
40 defined('AK_EMAIL_REGULAR_EXPRESSION') ? null : define('AK_EMAIL_REGULAR_EXPRESSION',"/^([a-z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-z0-9\-]+\.)+))([a-z]{2,4}|[0-9]{1,3})(\]?)$/i");
41 defined('AK_NUMBER_REGULAR_EXPRESSION') ? null : define('AK_NUMBER_REGULAR_EXPRESSION',"/^[0-9]+$/");
42 defined('AK_PHONE_REGULAR_EXPRESSION') ? null : define('AK_PHONE_REGULAR_EXPRESSION',"/^([\+]?[(]?[\+]?[ ]?[0-9]{2,3}[)]?[ ]?)?[0-9 ()\-]{4,25}$/");
43 defined('AK_DATE_REGULAR_EXPRESSION') ? null : define('AK_DATE_REGULAR_EXPRESSION',"/^(([0-9]{1,2}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{2,4})|([0-9]{2,4}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{1,2})){1}$/");
44 defined('AK_IP4_REGULAR_EXPRESSION') ? null : define('AK_IP4_REGULAR_EXPRESSION',"/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/");
45 defined('AK_POST_CODE_REGULAR_EXPRESSION') ? null : define('AK_POST_CODE_REGULAR_EXPRESSION',"/^[0-9A-Za-z -]{2,9}$/");
46 /**#@-*/
48 // Forces loading database schema on every call
49 if(AK_DEV_MODE && isset($_SESSION['__activeRecordColumnsSettingsCache'])){
50 unset($_SESSION['__activeRecordColumnsSettingsCache']);
53 ak_compat('array_combine');
55 /**
56 * Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with
57 * which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
58 * is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
59 * database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
61 * See the mapping rules in table_name and the full example in README.txt for more insight.
63 * == Creation ==
65 * Active Records accepts constructor parameters either in an array or as a list of parameters in a specific format. The array method is especially useful when
66 * you're receiving the data from somewhere else, like a HTTP request. It works like this:
68 * <code>
69 * $user = new User(array('name' => 'David', 'occupation' => 'Code Artist'));
70 * echo $user->name; // Will print "David"
71 * </code>
73 * You can also use a parameter list initialization.:
75 * $user = new User('name->', 'David', 'occupation->', 'Code Artist');
77 * And of course you can just create a bare object and specify the attributes after the fact:
79 * <code>
80 * $user = new User();
81 * $user->name = 'David';
82 * $user->occupation = 'Code Artist';
83 * </code>
85 * == Conditions ==
87 * Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement.
88 * The array form is to be used when the condition input is tainted and requires sanitization. The string form can
89 * be used for statements that doesn't involve tainted data. Examples:
91 * <code>
92 * class User extends ActiveRecord
93 * {
94 * function authenticateUnsafely($user_name, $password)
95 * {
96 * return findFirst("user_name = '$user_name' AND password = '$password'");
97 * }
99 * function authenticateSafely($user_name, $password)
101 * return findFirst("user_name = ? AND password = ?", $user_name, $password);
104 * </code>
106 * The <tt>authenticateUnsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
107 * attacks if the <tt>$user_name</tt> and <tt>$password</tt> parameters come directly from a HTTP request. The <tt>authenticateSafely</tt> method,
108 * on the other hand, will sanitize the <tt>$user_name</tt> and <tt>$password</tt> before inserting them in the query, which will ensure that
109 * an attacker can't escape the query and fake the login (or worse).
111 * When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
112 * question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
113 * the question marks with symbols and supplying a hash with values for the matching symbol keys:
115 * <code>
116 * $Company->findFirst(
117 * "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
118 * array(':id' => 3, ':name' => "37signals", ':division' => "First", ':accounting_date' => '2005-01-01')
119 * );
120 * </code>
122 * == Accessing attributes before they have been type casted ==
124 * Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first.
125 * That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model
126 * has a balance attribute, you can call $Account->balance_before_type_cast or $Account->id_before_type_cast.
128 * This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
129 * the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn't what you
130 * want.
132 * == Saving arrays, hashes, and other non-mappable objects in text columns ==
134 * Active Record can serialize any object in text columns. To do so, you must specify this with by setting the attribute serialize with
135 * a comma separated list of columns or an array.
136 * This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
138 * <code>
139 * class User extends ActiveRecord
141 * var $serialize = 'preferences';
144 * $User = new User(array('preferences'=>array("background" => "black", "display" => 'large')));
145 * $User->find($user_id);
146 * $User->preferences // array("background" => "black", "display" => 'large')
147 * </code>
149 * == Single table inheritance ==
151 * Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed
152 * by overwriting <tt>AkActiveRecord->_inheritanceColumn</tt>). This means that an inheritance looking like this:
154 * <code>
155 * class Company extends ActiveRecord{}
156 * class Firm extends Company{}
157 * class Client extends Company{}
158 * class PriorityClient extends Client{}
159 * </code>
161 * When you do $Firm->create('name =>', "akelos"), this record will be saved in the companies table with type = "Firm". You can then
162 * fetch this row again using $Company->find('first', "name = '37signals'") and it will return a Firm object.
164 * If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
165 * like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
167 * Note, all the attributes for all the cases are kept in the same table. Read more:
168 * http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
170 * == Connection to multiple databases in different models ==
172 * Connections are usually created through AkActiveRecord->establishConnection and retrieved by AkActiveRecord->connection.
173 * All classes inheriting from AkActiveRecord will use this connection. But you can also set a class-specific connection.
174 * For example, if $Course is a AkActiveRecord, but resides in a different database you can just say $Course->establishConnection
175 * and $Course and all its subclasses will use this connection instead.
177 * Active Records will automatically record creation and/or update timestamps of database objects
178 * if fields of the names created_at/created_on or updated_at/updated_on are present.
179 * Date only: created_on, updated_on
180 * Date and time: created_at, updated_at
182 * This behavior can be turned off by setting <tt>$this->_recordTimestamps = false</tt>.
184 class AkActiveRecord extends AkAssociatedActiveRecord
186 /**#@+
187 * @access private
189 //var $disableAutomatedAssociationLoading = true;
190 var $_tableName;
191 var $_db;
192 var $_newRecord;
193 var $_freeze;
194 var $_dataDictionary;
195 var $_primaryKey;
196 var $_inheritanceColumn;
198 var $_associations;
200 var $_internationalize;
202 var $_errors = array();
204 var $_attributes = array();
206 var $_protectedAttributes = array();
207 var $_accessibleAttributes = array();
209 var $_recordTimestamps = true;
211 // Column description
212 var $_columnNames = array();
213 // Array of column objects for the table associated with this class.
214 var $_columns = array();
215 // Columns that can be edited/viewed
216 var $_contentColumns = array();
217 // Methods that will be dinamically loaded for the model (EXPERIMENTAL) This pretends to generate something similar to Ruby on Rails finders.
218 // If you set array('findOneByUsernameAndPassword', 'findByCompany', 'findAllByExipringDate')
219 // You'll get $User->findOneByUsernameAndPassword('admin', 'pass');
220 var $_dynamicMethods = false;
221 var $_combinedAttributes = array();
223 var $_BlobQueryStack = null;
225 var $_automated_max_length_validator = true;
226 var $_automated_validators_enabled = true;
227 var $_automated_not_null_validator = false;
228 var $_set_default_attribute_values_automatically = true;
230 // This is needed for enabling support for static active record instantation under php
231 var $_activeRecordHasBeenInstantiated = true;
233 var $__ActsLikeAttributes = array();
236 * Holds a hash with all the default error messages, such that they can be replaced by your own copy or localizations.
238 var $_defaultErrorMessages = array(
239 'inclusion' => "is not included in the list",
240 'exclusion' => "is reserved",
241 'invalid' => "is invalid",
242 'confirmation' => "doesn't match confirmation",
243 'accepted' => "must be accepted",
244 'empty' => "can't be empty",
245 'blank' => "can't be blank",
246 'too_long' => "is too long (max is %d characters)",
247 'too_short' => "is too short (min is %d characters)",
248 'wrong_length' => "is the wrong length (should be %d characters)",
249 'taken' => "has already been taken",
250 'not_a_number' => "is not a number"
253 var $__activeRecordObject = true;
255 /**#@-*/
257 function __construct()
259 $attributes = (array)func_get_args();
260 return $this->init($attributes);
263 function init($attributes = array())
265 AK_LOG_EVENTS ? ($this->Logger =& Ak::getLogger()) : null;
266 $this->_internationalize = is_null($this->_internationalize) && AK_ACTIVE_RECORD_INTERNATIONALIZE_MODELS_BY_DEFAULT ? count($this->getAvailableLocales()) > 1 : $this->_internationalize;
268 @$this->_instantiateDefaultObserver();
270 $this->setConnection();
272 if(!empty($this->table_name)){
273 $this->setTableName($this->table_name);
276 $this->_loadActAsBehaviours();
278 if(!empty($this->combined_attributes)){
279 foreach ($this->combined_attributes as $combined_attribute){
280 $this->addCombinedAttributeConfiguration($combined_attribute);
284 if(isset($attributes[0]) && is_array($attributes[0]) && count($attributes) === 1){
285 $attributes = $attributes[0];
286 $this->_newRecord = true;
289 // new AkActiveRecord(23); //Returns object with primary key 23
290 if(isset($attributes[0]) && count($attributes) === 1 && $attributes[0] > 0){
291 $record = $this->find($attributes[0]);
292 if(!$record){
293 return false;
294 }else {
295 $this->setAttributes($record->getAttributes(), true);
297 // This option is only used internally for loading found objects
298 }elseif(isset($attributes[0]) && isset($attributes[1]) && $attributes[0] == 'attributes' && is_array($attributes[1])){
299 foreach(array_keys($attributes[1]) as $k){
300 $attributes[1][$k] = $this->castAttributeFromDatabase($k, $attributes[1][$k]);
303 $avoid_loading_associations = isset($attributes[1]['load_associations']) ? false : !empty($this->disableAutomatedAssociationLoading);
304 $this->setAttributes($attributes[1], true);
305 }else{
306 $this->newRecord($attributes);
309 $this->_buildFinders();
310 empty($avoid_loading_associations) ? $this->loadAssociations() : null;
313 function __destruct()
319 * New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved
320 * (pass an array with key names matching the associated table column names).
321 * In both instances, valid attribute keys are determined by the column names of the associated table; hence you can't
322 * have attributes that aren't part of the table columns.
324 function newRecord($attributes)
326 $this->_newRecord = true;
328 if(AK_ACTIVE_RECORD_SKIP_SETTING_ACTIVE_RECORD_DEFAULTS && empty($attributes)){
329 return;
332 if(isset($attributes) && !is_array($attributes)){
333 $attributes = func_get_args();
335 $this->setAttributes($this->attributesFromColumnDefinition(),true);
336 $this->setAttributes($attributes);
341 * Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.
343 function cloneRecord()
345 $model_name = $this->getModelName();
346 $attributes = $this->getAttributesBeforeTypeCast();
347 if(isset($attributes[$this->getPrimaryKey()])){
348 unset($attributes[$this->getPrimaryKey()]);
350 return new $model_name($attributes);
355 * Returns true if this object hasn't been saved yet that is, a record for the object doesn't exist yet.
357 function isNewRecord()
359 if(!isset($this->_newRecord) && !isset($this->{$this->getPrimaryKey()})){
360 $this->_newRecord = true;
362 return $this->_newRecord;
368 * Reloads the attributes of this object from the database.
370 function reload()
373 * @todo clear cache
375 if($object = $this->find($this->getId())){
376 $this->setAttributes($object->getAttributes(), true);
377 return true;
378 }else {
379 return false;
386 Creating records
387 ====================================================================
390 * Creates an object, instantly saves it as a record (if the validation permits it), and returns it.
391 * If the save fail under validations, the unsaved object is still returned.
393 function &create($attributes = null)
395 if(!isset($this->_activeRecordHasBeenInstantiated)){
396 return Ak::handleStaticCall();
399 if(func_num_args() > 1){
400 $attributes = func_get_args();
402 $model = $this->getModelName();
404 $object =& new $model();
405 $object->setAttributes($attributes);
406 $object->save();
407 return $object;
410 function createOrUpdate($validate = true)
412 if($validate && !$this->isValid()){
413 $this->transactionFail();
414 return false;
416 return $this->isNewRecord() ? $this->_create() : $this->_update();
419 function &findOrCreateBy()
421 $args = func_get_args();
422 $Item =& Ak::call_user_func_array(array(&$this,'findFirstBy'), $args);
423 if(!$Item){
424 $attributes = array();
426 list($sql, $columns) = $this->_getFindBySqlAndColumns(array_shift($args), $args);
428 if(!empty($columns)){
429 foreach ($columns as $column){
430 $attributes[$column] = array_shift($args);
433 $Item =& $this->create($attributes);
434 $Item->has_been_created = true;
435 }else{
436 $Item->has_been_created = false;
438 $Item->has_been_found = !$Item->has_been_created;
439 return $Item;
443 * Creates a new record with values matching those of the instance attributes.
444 * Must be called as a result of a call to createOrUpdate.
446 * @access private
448 function _create()
450 if (!$this->beforeCreate() || !$this->notifyObservers('beforeCreate')){
451 return $this->transactionFail();
454 $this->_setRecordTimestamps();
456 // deprecated section
457 if($this->isLockingEnabled() && is_null($this->get('lock_version'))){
458 Ak::deprecateWarning(array("Column %lock_version_column should have a default setting. Assumed '1'.",'%lock_version_column'=>'lock_version'));
459 $this->setAttribute('lock_version',1);
460 } // end
462 $attributes = $this->getColumnsForAttributes($this->getAttributes());
463 foreach ($attributes as $column=>$value){
464 $attributes[$column] = $this->castAttributeForDatabase($column,$value);
467 $pk = $this->getPrimaryKey();
468 $table = $this->getTableName();
470 $id = $this->_db->incrementsPrimaryKeyAutomatically() ? null : $this->_db->getNextSequenceValueFor($table);
471 $attributes[$pk] = $id;
473 $attributes = array_diff($attributes, array(''));
476 $sql = 'INSERT INTO '.$table.' '.
477 '('.join(', ',array_keys($attributes)).') '.
478 'VALUES ('.join(',',array_values($attributes)).')';
480 $inserted_id = $this->_db->insert($sql, $id, $pk, $table, 'Create '.$this->getModelName());
481 if ($this->transactionHasFailed()){
482 return false;
484 $this->setId($inserted_id);
486 $this->_newRecord = false;
488 if (!$this->afterCreate() || !$this->notifyObservers('afterCreate')){
489 return $this->transactionFail();
492 return true;
495 function _setRecordTimestamps()
497 if (!$this->_recordTimestamps){
498 return;
500 if ($this->_newRecord){
501 if ($this->hasColumn('created_at')){
502 $this->setAttribute('created_at', Ak::getDate());
504 if ($this->hasColumn('created_on')){
505 $this->setAttribute('created_on', Ak::getDate(null, 'Y-m-d'));
507 }else{
508 if ($this->hasColumn('updated_at')){
509 $this->setAttribute('updated_at', Ak::getDate());
511 if ($this->hasColumn('updated_on')){
512 $this->setAttribute('updated_on', Ak::getDate(null, 'Y-m-d'));
516 if($this->_newRecord && isset($this->expires_on)){
517 if(isset($this->expires_at) && $this->hasColumn('expires_at')){
518 $this->setAttribute('expires_at',Ak::getDate(strtotime($this->expires_at) + (defined('AK_TIME_DIFFERENCE') ? AK_TIME_DIFFERENCE*60 : 0)));
519 }elseif(isset($this->expires_on) && $this->hasColumn('expires_on')){
520 $this->setAttribute('expires_on',Ak::getDate(strtotime($this->expires_on) + (defined('AK_TIME_DIFFERENCE') ? AK_TIME_DIFFERENCE*60 : 0), 'Y-m-d'));
526 /*/Creating records*/
530 Saving records
531 ====================================================================
534 * - No record exists: Creates a new record with values matching those of the object attributes.
535 * - A record does exist: Updates the record with values matching those of the object attributes.
537 function save($validate = true)
539 if($this->isFrozen()){
540 return false;
542 $result = false;
543 $this->transactionStart();
544 if($this->beforeSave() && $this->notifyObservers('beforeSave')){
545 $result = $this->createOrUpdate($validate);
546 if(!$this->transactionHasFailed()){
547 if(!$this->afterSave()){
548 $this->transactionFail();
549 }else{
550 if(!$this->notifyObservers('afterSave')){
551 $this->transactionFail();
555 }else{
556 $this->transactionFail();
559 $result = $this->transactionHasFailed() ? false : $result;
560 $this->transactionComplete();
562 return $result;
565 /*/Saving records*/
568 Counting Records
569 ====================================================================
570 See also: Counting Attributes.
574 * Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
576 * $Product->countBySql("SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id");
578 function countBySql($sql)
580 if(!isset($this->_activeRecordHasBeenInstantiated)){
581 return Ak::handleStaticCall();
583 if(!stristr($sql, 'COUNT') && stristr($sql, ' FROM ')){
584 $sql = 'SELECT COUNT(*) '.substr($sql,strpos(str_replace(' from ',' FROM ', $sql),' FROM '));
586 if(!$this->isConnected()){
587 $this->setConnection();
590 return (integer)$this->_db->selectValue($sql);
592 /*/Counting Records*/
595 Updating records
596 ====================================================================
597 See also: Callbacks.
601 * Finds the record from the passed id, instantly saves it with the passed attributes (if the validation permits it),
602 * and returns it. If the save fail under validations, the unsaved object is still returned.
604 function update($id, $attributes)
606 if(!isset($this->_activeRecordHasBeenInstantiated)){
607 return Ak::handleStaticCall();
609 if(is_array($id)){
610 $results = array();
611 foreach ($id as $idx=>$single_id){
612 $results[] = $this->update($single_id, isset($attributes[$idx]) ? $attributes[$idx] : $attributes);
614 return $results;
615 }else{
616 $object =& $this->find($id);
617 $object->updateAttributes($attributes);
618 return $object;
623 * Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
625 function updateAttribute($name, $value, $should_validate=true)
627 $this->setAttribute($name, $value);
628 return $this->save($should_validate);
633 * Updates all the attributes in from the passed array and saves the record. If the object is
634 * invalid, the saving will fail and false will be returned.
636 function updateAttributes($attributes, $object = null)
638 isset($object) ? $object->setAttributes($attributes) : $this->setAttributes($attributes);
640 return isset($object) ? $object->save() : $this->save();
644 * Updates all records with the SET-part of an SQL update statement in updates and returns an
645 * integer with the number of rows updates. A subset of the records can be selected by specifying conditions. Example:
646 * <code>$Billing->updateAll("category = 'authorized', approved = 1", "author = 'David'");</code>
648 * Important note: Conditions are not sanitized yet so beware of accepting
649 * variable conditions when using this function
651 function updateAll($updates, $conditions = null)
653 if(!isset($this->_activeRecordHasBeenInstantiated)){
654 return Ak::handleStaticCall();
657 * @todo sanitize sql conditions
659 $sql = 'UPDATE '.$this->getTableName().' SET '.$updates;
660 $this->addConditions($sql, $conditions);
661 return $this->_db->update($sql, $this->getModelName().' Update All');
666 * Updates the associated record with values matching those of the instance attributes.
667 * Must be called as a result of a call to createOrUpdate.
669 * @access private
671 function _update()
673 if(!$this->beforeUpdate() || !$this->notifyObservers('beforeUpdate')){
674 return $this->transactionFail();
677 $this->_setRecordTimestamps();
679 $lock_check_sql = '';
680 if ($this->isLockingEnabled()){
681 $previous_value = $this->lock_version;
682 $this->setAttribute('lock_version', $previous_value + 1);
683 $lock_check_sql = ' AND lock_version = '.$previous_value;
686 $quoted_attributes = $this->getAvailableAttributesQuoted();
687 $sql = 'UPDATE '.$this->getTableName().' '.
688 'SET '.join(', ', $quoted_attributes) .' '.
689 'WHERE '.$this->getPrimaryKey().'='.$this->quotedId().$lock_check_sql;
691 $affected_rows = $this->_db->update($sql,'Updating '.$this->getModelName());
692 if($this->transactionHasFailed()){
693 return false;
696 if ($this->isLockingEnabled() && $affected_rows != 1){
697 $this->setAttribute('lock_version', $previous_value);
698 trigger_error(Ak::t('Attempted to update a stale object'), E_USER_NOTICE);
699 return $this->transactionFail();
702 if(!$this->afterUpdate() || !$this->notifyObservers('afterUpdate')){
703 return $this->transactionFail();
706 return true;
709 /*/Updating records*/
714 Deleting records
715 ====================================================================
716 See also: Callbacks.
720 * Deletes the record with the given id without instantiating an object first. If an array of
721 * ids is provided, all of them are deleted.
723 function delete($id)
725 if(!isset($this->_activeRecordHasBeenInstantiated)){
726 return Ak::handleStaticCall();
728 $id = func_num_args() > 1 ? func_get_args() : $id;
729 return $this->deleteAll($this->getPrimaryKey().' IN ('.(is_array($id) ? join(', ',$id) : $id).')');
734 * Deletes all the records that matches the condition without instantiating the objects first
735 * (and hence not calling the destroy method). Example:
737 * <code>$Post->destroyAll("person_id = 5 AND (category = 'Something' OR category = 'Else')");</code>
739 * Important note: Conditions are not sanitized yet so beware of accepting
740 * variable conditions when using this function
742 function deleteAll($conditions = null)
744 if(!isset($this->_activeRecordHasBeenInstantiated)){
745 return Ak::handleStaticCall();
748 * @todo sanitize sql conditions
750 $sql = 'DELETE FROM '.$this->getTableName();
751 $this->addConditions($sql,$conditions);
752 return $this->_db->delete($sql,$this->getModelName().' Delete All');
757 * Destroys the record with the given id by instantiating the object and calling destroy
758 * (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.
759 * Deletes the record in the database and freezes this instance to reflect that no changes should be
760 * made (since they can't be persisted).
762 function destroy($id = null)
764 if(!isset($this->_activeRecordHasBeenInstantiated)){
765 return Ak::handleStaticCall();
768 $id = func_num_args() > 1 ? func_get_args() : $id;
770 if(isset($id)){
771 $this->transactionStart();
772 $id_arr = is_array($id) ? $id : array($id);
773 if($objects = $this->find($id_arr)){
774 $results = count($objects);
775 $no_problems = true;
776 for ($i=0; $results > $i; $i++){
777 if(!$objects[$i]->destroy()){
778 $no_problems = false;
781 $this->transactionComplete();
782 return $no_problems;
783 }else {
784 $this->transactionComplete();
785 return false;
787 }else{
788 if(!$this->isNewRecord()){
789 $this->transactionStart();
790 $return = $this->_destroy() && $this->freeze();
791 $this->transactionComplete();
792 return $return;
797 function _destroy()
799 if(!$this->beforeDestroy() || !$this->notifyObservers('beforeDestroy')){
800 return $this->transactionFail();
803 $sql = 'DELETE FROM '.$this->getTableName().' WHERE '.$this->getPrimaryKey().' = '.$this->_db->quote_string($this->getId());
804 if ($this->_db->delete($sql,$this->getModelName().' Destroy') !== 1){
805 return $this->transactionFail();
808 if (!$this->afterDestroy() || !$this->notifyObservers('afterDestroy')){
809 return $this->transactionFail();
811 return true;
815 * Destroys the objects for all the records that matches the condition by instantiating
816 * each object and calling the destroy method.
818 * Example:
820 * $Person->destroyAll("last_login < '2004-04-04'");
822 function destroyAll($conditions)
824 if($objects = $this->find('all',array('conditions'=>$conditions))){
825 $results = count($objects);
826 $no_problems = true;
827 for ($i=0; $results > $i; $i++){
828 if(!$objects[$i]->destroy()){
829 $no_problems = false;
832 return $no_problems;
833 }else {
834 return false;
838 /*/Deleting records*/
844 Finding records
845 ====================================================================
849 * Returns true if the given id represents the primary key of a record in the database, false otherwise. Example:
851 * $Person->exists(5);
853 function exists($id)
855 return $this->find('first',array('conditions' => array($this->getPrimaryKey().' = '.$id))) !== false;
859 * Find operates with three different retrieval approaches:
860 * * Find by id: This can either be a specific id find(1), a list of ids find(1, 5, 6),
861 * or an array of ids find(array(5, 6, 10)). If no record can be found for all of the listed ids,
862 * then RecordNotFound will be raised.
863 * * Find first: This will return the first record matched by the options used. These options
864 * can either be specific conditions or merely an order.
865 * If no record can matched, false is returned.
866 * * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.
868 * All approaches accepts an $option array as their last parameter. The options are:
870 * 'conditions' => An SQL fragment like "administrator = 1" or array("user_name = ?" => $username). See conditions in the intro.
871 * 'order' => An SQL fragment like "created_at DESC, name".
872 * 'limit' => An integer determining the limit on the number of rows that should be returned.
873 * 'offset' => An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
874 * 'joins' => An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = $id". (Rarely needed).
875 * 'include' => Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols
876 * named refer to already defined associations. See eager loading under Associations.
878 * Examples for find by id:
879 * <code>
880 * $Person->find(1); // returns the object for ID = 1
881 * $Person->find(1, 2, 6); // returns an array for objects with IDs in (1, 2, 6), Returns false if any of those IDs is not available
882 * $Person->find(array(7, 17)); // returns an array for objects with IDs in (7, 17)
883 * $Person->find(array(1)); // returns an array for objects the object with ID = 1
884 * $Person->find(1, array('conditions' => "administrator = 1", 'order' => "created_on DESC"));
885 * </code>
887 * Examples for find first:
888 * <code>
889 * $Person->find('first'); // returns the first object fetched by SELECT * FROM people
890 * $Person->find('first', array('conditions' => array("user_name = ':user_name'", ':user_name' => $user_name)));
891 * $Person->find('first', array('order' => "created_on DESC", 'offset' => 5));
892 * </code>
894 * Examples for find all:
895 * <code>
896 * $Person->find('all'); // returns an array of objects for all the rows fetched by SELECT * FROM people
897 * $Person->find(); // Same as $Person->find('all');
898 * $Person->find('all', array('conditions' => array("category IN (categories)", 'categories' => join(','$categories)), 'limit' => 50));
899 * $Person->find('all', array('offset' => 10, 'limit' => 10));
900 * $Person->find('all', array('include' => array('account', 'friends'));
901 * </code>
903 function &find()
905 if(!isset($this->_activeRecordHasBeenInstantiated)){
906 return Ak::handleStaticCall();
909 $args = func_get_args();
911 $options = $this->_extractOptionsFromArgs($args);
912 list($fetch,$options) = $this->_extractConditionsFromArgs($args,$options);
914 $this->_sanitizeConditionsVariables($options);
916 switch ($fetch) {
917 case 'first':
918 // HACK: php4 pass by ref
919 $result =& $this->_findInitial($options);
920 return $result;
921 break;
923 case 'all':
924 // HACK: php4 pass by ref
925 $result =& $this->_findEvery($options);
926 return $result;
927 break;
929 default:
930 // HACK: php4 pass by ref
931 $result =& $this->_findFromIds($args, $options);
932 return $result;
933 break;
935 $result = false;
936 return $result;
939 function &_findInitial($options)
941 // TODO: virtual_limit is a hack
942 // actually we fetch_all and return only the first row
943 $options = array_merge($options, array((!empty($options['include']) ?'virtual_limit':'limit')=>1));
944 $result =& $this->_findEvery($options);
946 if(!empty($result) && is_array($result)){
947 $_result =& $result[0];
948 }else{
949 $_result = false;
950 // if we return an empty array instead of false we need to change this->exists()!
951 //$_result = array();
953 return $_result;
957 function &_findEvery($options)
959 $limit = isset($options['limit']) ? $options['limit'] : null;
960 $offset = isset($options['offset']) ? $options['offset'] : null;
962 $sql = $this->constructFinderSql($options);
963 if(!empty($options['bind']) && is_array($options['bind']) && strstr($sql,'?')){
964 $sql = array_merge(array($sql),$options['bind']);
967 if((!empty($options['include']) && $this->hasAssociations())){
968 $result =& $this->findWithAssociations($options);
969 }else{
970 $result =& $this->findBySql($sql);
973 if(!empty($result) && is_array($result)){
974 $_result =& $result;
975 }else{
976 $_result = false;
978 return $_result;
982 function &_findFromIds($ids, $options)
984 $expects_array = is_array($ids[0]);
985 $ids = array_unique($expects_array ? (isset($ids[1]) ? array_merge($ids[0],$ids) : $ids[0]) : $ids);
987 $num_ids = count($ids);
989 //at this point $options['conditions'] can't be an array
990 $conditions = !empty($options['conditions']) ? ' AND '.$options['conditions'] : '';
992 switch ($num_ids){
993 case 0 :
994 trigger_error($this->t('Couldn\'t find %object_name without an ID%conditions',array('%object_name'=>$this->getModelName(),'%conditions'=>$conditions)), E_USER_ERROR);
995 break;
997 case 1 :
998 $table_name = !empty($options['include']) && $this->hasAssociations() ? '__owner' : $this->getTableName();
999 $options['conditions'] = $table_name.'.'.$this->getPrimaryKey().' = '.$ids[0].$conditions;
1000 $result =& $this->_findEvery($options);
1001 if (!$expects_array && $result !== false){
1002 return $result[0];
1004 return $result;
1005 break;
1007 default:
1008 $without_conditions = empty($options['conditions']) ? true : false;
1009 $ids_condition = $this->getPrimaryKey().' IN ('.join(', ',$ids).')';
1010 $options['conditions'] = $ids_condition.$conditions;
1012 $result =& $this->_findEvery($options);
1013 if(is_array($result) && (count($result) != $num_ids && $without_conditions)){
1014 $result = false;
1016 return $result;
1017 break;
1022 function _extractOptionsFromArgs(&$args)
1024 $last_arg = count($args)-1;
1025 return isset($args[$last_arg]) && is_array($args[$last_arg]) && $this->_isOptionsHash($args[$last_arg]) ? array_pop($args) : array();
1028 function _isOptionsHash($options)
1030 if (isset($options[0])){
1031 return false;
1033 $valid_keys = array('conditions', 'include', 'joins', 'limit', 'offset', 'group', 'order', 'sort', 'bind', 'select','select_prefix', 'readonly');
1034 foreach (array_keys($options) as $key){
1035 if (!in_array($key,$valid_keys)){
1036 return false;
1039 return true;
1042 function _extractConditionsFromArgs($args, $options)
1044 if(empty($args)){
1045 $fetch = 'all';
1046 } else {
1047 $fetch = $args[0];
1049 $num_args = count($args);
1051 // deprecated: acts like findFirstBySQL
1052 if ($num_args === 1 && !is_numeric($args[0]) && is_string($args[0]) && $args[0] != 'all' && $args[0] != 'first'){
1053 // $Users->find("last_name = 'Williams'"); => find('first',"last_name = 'Williams'");
1054 Ak::deprecateWarning(array("AR::find('%sql') is ambiguous and therefore deprecated, use AR::find('first',%sql) instead", '%sql'=>$args[0]));
1055 $options = array('conditions'=> $args[0]);
1056 return array('first',$options);
1057 } //end
1059 // set fetch_mode to 'all' if none is given
1060 if (!is_numeric($fetch) && !is_array($fetch) && $fetch != 'all' && $fetch != 'first') {
1061 array_unshift($args, 'all');
1062 $num_args = count($args);
1064 if ($num_args > 1) {
1065 if (is_string($args[1])){
1066 // $Users->find(:fetch_mode,"first_name = ?",'Tim');
1067 $fetch = array_shift($args);
1068 $options = array_merge($options, array('conditions'=>$args)); //TODO: merge_conditions
1069 }elseif (is_array($args[1])) {
1070 // $Users->find(:fetch_mode,array('first_name = ?,'Tim'));
1071 $fetch = array_shift($args);
1072 $options = array_merge($options, array('conditions'=>$args[0])); //TODO: merge_conditions
1076 return array($fetch,$options);
1079 function _sanitizeConditionsVariables(&$options)
1081 if(!empty($options['conditions']) && is_array($options['conditions'])){
1082 if (isset($options['conditions'][0]) && strstr($options['conditions'][0], '?') && count($options['conditions']) > 1){
1083 //array('conditions' => array("name=?",$name))
1084 $pattern = array_shift($options['conditions']);
1085 $options['bind'] = array_values($options['conditions']);
1086 $options['conditions'] = $pattern;
1087 }elseif (isset($options['conditions'][0])){
1088 //array('conditions' => array("user_name = :user_name", ':user_name' => 'hilario')
1089 $pattern = array_shift($options['conditions']);
1090 $options['conditions'] = str_replace(array_keys($options['conditions']), array_values($this->getSanitizedConditionsArray($options['conditions'])),$pattern);
1091 }else{
1092 //array('conditions' => array('user_name'=>'Hilario'))
1093 $options['conditions'] = join(' AND ',(array)$this->getAttributesQuoted($options['conditions']));
1099 function &findFirst()
1101 if(!isset($this->_activeRecordHasBeenInstantiated)){
1102 return Ak::handleStaticCall();
1104 $args = func_get_args();
1105 $result =& Ak::call_user_func_array(array(&$this,'find'), array_merge(array('first'),$args));
1106 return $result;
1109 function &findAll()
1111 if(!isset($this->_activeRecordHasBeenInstantiated)){
1112 return Ak::handleStaticCall();
1114 $args = func_get_args();
1115 $result =& Ak::call_user_func_array(array(&$this,'find'), array_merge(array('all'),$args));
1116 return $result;
1121 * Works like find_all, but requires a complete SQL string. Examples:
1122 * $Post->findBySql("SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id");
1123 * $Post->findBySql(array("SELECT * FROM posts WHERE author = ? AND created_on > ?", $author_id, $start_date));
1125 function &findBySql($sql, $limit = null, $offset = null, $bindings = null)
1127 if ($limit || $offset){
1128 Ak::deprecateWarning("You're calling AR::findBySql with \$limit or \$offset parameters. This has been deprecated.");
1129 $this->_db->addLimitAndOffset($sql, array('limit'=>$limit,'offset'=>$offset));
1131 if(!isset($this->_activeRecordHasBeenInstantiated)){
1132 return Ak::handleStaticCall();
1134 $objects = array();
1135 $records = $this->_db->select ($sql,'selecting');
1136 foreach ($records as $record){
1137 $objects[] =& $this->instantiate($this->getOnlyAvailableAttributes($record), false);
1139 return $objects;
1143 * This function pretends to emulate RoR finders until AkActiveRecord::addMethod becomes stable on future PHP versions.
1144 * @todo use PHP5 __call method for handling the magic finder methods like findFirstByUnsenameAndPassword('bermi','pass')
1146 function &findFirstBy()
1148 if(!isset($this->_activeRecordHasBeenInstantiated)){
1149 return Ak::handleStaticCall();
1151 $args = func_get_args();
1152 array_unshift($args,'first');
1153 $result =& Ak::call_user_func_array(array(&$this,'findBy'), $args);
1154 return $result;
1157 function &findLastBy()
1159 if(!isset($this->_activeRecordHasBeenInstantiated)){
1160 return Ak::handleStaticCall();
1162 $args = func_get_args();
1163 $options = $this->_extractOptionsFromArgs($args);
1164 $options['order'] = $this->getPrimaryKey().' DESC';
1165 array_push($args, $options);
1166 $result =& Ak::call_user_func_array(array(&$this,'findFirstBy'), $args);
1167 return $result;
1170 function &findAllBy()
1172 if(!isset($this->_activeRecordHasBeenInstantiated)){
1173 return Ak::handleStaticCall();
1175 $args = func_get_args();
1176 array_unshift($args,'all');
1177 $result =& Ak::call_user_func_array(array(&$this,'findBy'), $args);
1178 return $result;
1182 * This method allows you to use finders in a more flexible way like:
1184 * findBy('username AND password', $username, $password);
1185 * findBy('age > ? AND name:contains', 18, 'Joe');
1186 * findBy('is_active = true AND session_id', session_id());
1189 function &findBy()
1191 if(!isset($this->_activeRecordHasBeenInstantiated)){
1192 return Ak::handleStaticCall();
1194 $args = func_get_args();
1195 $find_by_sql = array_shift($args);
1196 if($find_by_sql == 'all' || $find_by_sql == 'first'){
1197 $fetch = $find_by_sql;
1198 $find_by_sql = array_shift($args);
1199 }else{
1200 $fetch = 'all';
1203 $options = $this->_extractOptionsFromArgs($args);
1205 $query_values = $args;
1206 $query_arguments_count = count($query_values);
1208 list($sql, $requested_args) = $this->_getFindBySqlAndColumns($find_by_sql, $query_values);
1210 if($query_arguments_count != count($requested_args)){
1211 trigger_error(Ak::t('Argument list did not match expected set. Requested arguments are:').join(', ',$requested_args),E_USER_ERROR);
1212 $false = false;
1213 return $false;
1216 $true_bool_values = array(true,1,'true','True','TRUE','1','y','Y','yes','Yes','YES','s','Si','SI','V','v','T','t');
1218 foreach ($requested_args as $k=>$v){
1219 switch ($this->getColumnType($v)) {
1220 case 'boolean':
1221 $query_values[$k] = in_array($query_values[$k],$true_bool_values) ? true : false;
1222 break;
1224 case 'date':
1225 case 'datetime':
1226 $query_values[$k] = str_replace('/','-', $this->castAttributeForDatabase($k,$query_values[$k],false));
1227 break;
1229 default:
1230 break;
1234 $conditions = array($sql);
1235 foreach ($query_values as $bind_value){
1236 $conditions[] = $bind_value;
1239 * @todo merge_conditions
1241 $options['conditions'] = $conditions;
1243 $result =& Ak::call_user_func_array(array(&$this,'find'), array($fetch,$options));
1244 return $result;
1248 function _getFindBySqlAndColumns($find_by_sql, &$query_values)
1250 $sql = str_replace(array('(',')','||','|','&&','&',' '),array(' ( ',' ) ',' OR ',' OR ',' AND ',' AND ',' '), $find_by_sql);
1251 $operators = array('AND','and','(',')','&','&&','NOT','<>','OR','|','||');
1252 $pieces = explode(' ',$sql);
1253 $pieces = array_diff($pieces,array(' ',''));
1254 $params = array_diff($pieces,$operators);
1255 $operators = array_diff($pieces,$params);
1257 $new_sql = '';
1258 $parameter_count = 0;
1259 $requested_args = array();
1260 foreach ($pieces as $piece){
1261 if(in_array($piece,$params) && $this->hasColumn($piece)){
1262 $new_sql .= $piece.' = ? ';
1263 $requested_args[$parameter_count] = $piece;
1264 $parameter_count++;
1265 }elseif (!in_array($piece,$operators)){
1267 if(strstr($piece,':')){
1268 $_tmp_parts = explode(':',$piece);
1269 if($this->hasColumn($_tmp_parts[0])){
1270 $query_values[$parameter_count] = isset($query_values[$parameter_count]) ? $query_values[$parameter_count] : $this->get($_tmp_parts[0]);
1271 switch (strtolower($_tmp_parts[1])) {
1272 case 'like':
1273 case '%like%':
1274 case 'is':
1275 case 'has':
1276 case 'contains':
1277 $query_values[$parameter_count] = '%'.$query_values[$parameter_count].'%';
1278 $new_sql .= $_tmp_parts[0]." LIKE ? ";
1279 break;
1280 case 'like_left':
1281 case 'like%':
1282 case 'begins':
1283 case 'begins_with':
1284 case 'starts':
1285 case 'starts_with':
1286 $query_values[$parameter_count] = $query_values[$parameter_count].'%';
1287 $new_sql .= $_tmp_parts[0]." LIKE ? ";
1288 break;
1289 case 'like_right':
1290 case '%like':
1291 case 'ends':
1292 case 'ends_with':
1293 case 'finishes':
1294 case 'finishes_with':
1295 $query_values[$parameter_count] = '%'.$query_values[$parameter_count];
1296 $new_sql .= $_tmp_parts[0]." LIKE ? ";
1297 break;
1298 default:
1299 $query_values[$parameter_count] = $query_values[$parameter_count];
1300 $new_sql .= $_tmp_parts[0].' '.$_tmp_parts[1].' ? ';
1301 break;
1303 $requested_args[$parameter_count] = $_tmp_parts[0];
1304 $parameter_count++;
1305 }else {
1306 $new_sql .= $_tmp_parts[0];
1308 }else{
1309 $new_sql .= $piece.' ';
1311 }else{
1312 $new_sql .= $piece.' ';
1316 return array($new_sql, $requested_args);
1321 * Given a condition that uses bindings like "user = ? AND created_at > ?" will return a
1322 * string replacing the "?" bindings with the column values for current Active Record
1324 * @return string
1326 function _getVariableSqlCondition($variable_condition)
1328 $query_values = array();
1329 list($sql, $requested_columns) = $this->_getFindBySqlAndColumns($variable_condition, $query_values);
1330 $replacements = array();
1331 $sql = preg_replace('/((('.join($requested_columns,'|').') = \?) = \?)/','$2', $sql);
1332 foreach ($requested_columns as $attribute){
1333 $replacements[$attribute] = $this->castAttributeForDatabase($attribute, $this->get($attribute));
1335 return trim(preg_replace('/('.join('|',array_keys($replacements)).')\s+([^\?]+)\s+\?/e', "isset(\$replacements['\\1']) ? '\\1 \\2 '.\$replacements['\\1']:'\\1 \\2 null'", $sql));
1339 function constructFinderSql($options, $select_from_prefix = 'default')
1341 $sql = isset($options['select_prefix']) ? $options['select_prefix'] : ($select_from_prefix == 'default' ? 'SELECT '.(!empty($options['joins'])?$this->getTableName().'.':'') .'* FROM '.$this->getTableName() : $select_from_prefix);
1342 $sql .= !empty($options['joins']) ? ' '.$options['joins'] : '';
1344 $this->addConditions($sql, isset($options['conditions']) ? $options['conditions'] : array());
1346 // Create an alias for order
1347 if(empty($options['order']) && !empty($options['sort'])){
1348 $options['order'] = $options['sort'];
1351 $sql .= !empty($options['group']) ? ' GROUP BY '.$options['group'] : '';
1352 $sql .= !empty($options['order']) ? ' ORDER BY '.$options['order'] : '';
1354 $this->_db->addLimitAndOffset($sql,$options);
1356 return $sql;
1361 * Adds a sanitized version of $conditions to the $sql string. Note that the passed $sql string is changed.
1363 function addConditions(&$sql, $conditions = null, $table_alias = null)
1365 $concat = empty($sql) ? '' : ' WHERE ';
1366 if (empty($conditions) && $this->_getDatabaseType() == 'sqlite') $conditions = '1'; // sqlite HACK
1367 if(!empty($conditions)){
1368 $sql .= $concat.$conditions;
1369 $concat = ' AND ';
1372 if($this->getInheritanceColumn() !== false && $this->descendsFromActiveRecord($this)){
1373 $type_condition = $this->typeCondition($table_alias);
1374 $sql .= !empty($type_condition) ? $concat.$type_condition : '';
1376 return $sql;
1380 * Gets a sanitized version of the input array. Each element will be escaped
1382 function getSanitizedConditionsArray($conditions_array)
1384 $result = array();
1385 foreach ($conditions_array as $k=>$v){
1386 $k = str_replace(':','',$k); // Used for Oracle type bindings
1387 if($this->hasColumn($k)){
1388 $v = $this->castAttributeForDatabase($k, $v);
1389 $result[$k] = $v;
1392 return $result;
1397 * This functions is used to get the conditions from an AkRequest object
1399 function getConditions($conditions, $prefix = '', $model_name = null)
1401 $model_name = isset($model_name) ? $model_name : $this->getModelName();
1402 $model_conditions = !empty($conditions[$model_name]) ? $conditions[$model_name] : $conditions;
1403 if(is_a($this->$model_name)){
1404 $model_instance =& $this->$model_name;
1405 }else{
1406 $model_instance =& $this;
1408 $new_conditions = array();
1409 if(is_array($model_conditions)){
1410 foreach ($model_conditions as $col=>$value){
1411 if($model_instance->hasColumn($col)){
1412 $new_conditions[$prefix.$col] = $value;
1416 return $new_conditions;
1421 * @access private
1423 function _quoteColumnName($column_name)
1425 return $this->_db->nameQuote.$column_name.$this->_db->nameQuote;
1432 * EXPERIMENTAL: Will allow to create finders when PHP includes aggregate_methods as a stable feature on PHP4, for PHP5 we might use __call
1434 * @access private
1436 function _buildFinders($finderFunctions = array('find','findFirst'))
1438 if(!$this->_dynamicMethods){
1439 return;
1441 $columns = !is_array($this->_dynamicMethods) ? array_keys($this->getColumns()) : $this->_dynamicMethods;
1442 $class_name = 'ak_'.md5(serialize($columns));
1443 if(!class_exists($class_name)){
1444 $permutations = Ak::permute($columns);
1445 $implementations = '';
1446 foreach ($finderFunctions as $finderFunction){
1447 foreach ($permutations as $permutation){
1448 $permutation = array_map(array('AkInflector','camelize'),$permutation);
1449 foreach ($permutation as $k=>$v){
1450 $method_name = $finderFunction.'By'.join($permutation,'And');
1451 $implementation = 'function &'.$method_name.'(';
1452 $first_param = '';
1453 $params = '';
1454 $i = 1;
1455 foreach ($permutation as $column){
1456 $column = AkInflector::underscore($column);
1457 $params .= "$$column, ";
1458 $first_param .= "$column ";
1459 $i++;
1461 $implementation .= trim($params,' ,')."){\n";
1462 $implementation .= '$options = func_num_args() == '.$i.' ? func_get_arg('.($i-1).') : array();'."\n";
1463 $implementation .= 'return $this->'.$finderFunction.'By(\''.$first_param.'\', '.trim($params,' ,').", \$options);\n }\n";
1464 $implementations[$method_name] = $implementation;
1465 array_shift($permutation);
1469 eval('class '.$class_name.' { '.join("\n",$implementations).' } ');
1472 aggregate_methods(&$this, $class_name);
1477 * Finder methods must instantiate through this method to work with the single-table inheritance model and
1478 * eager loading associations.
1479 * that makes it possible to create objects of different types from the same table.
1481 function &instantiate($record, $set_as_new = true)
1483 $inheritance_column = $this->getInheritanceColumn();
1484 if(!empty($record[$inheritance_column])){
1485 $inheritance_column = $record[$inheritance_column];
1486 $inheritance_model_name = AkInflector::camelize($inheritance_column);
1487 @require_once(AkInflector::toModelFilename($inheritance_model_name));
1488 if(!class_exists($inheritance_model_name)){
1489 trigger_error($this->t("The single-table inheritance mechanism failed to locate the subclass: '%class_name'. ".
1490 "This error is raised because the column '%column' is reserved for storing the class in case of inheritance. ".
1491 "Please rename this column if you didn't intend it to be used for storing the inheritance class ".
1492 "or overwrite #{self.to_s}.inheritance_column to use another column for that information.",
1493 array('%class_name'=>$inheritance_model_name, '%column'=>$this->getInheritanceColumn())),E_USER_ERROR);
1497 $model_name = isset($inheritance_model_name) ? $inheritance_model_name : $this->getModelName();
1498 $object =& new $model_name('attributes', $record);
1500 $object->_newRecord = $set_as_new;
1502 (AK_CLI && AK_ENVIRONMENT == 'development') ? $object ->toString() : null;
1504 return $object;
1507 /*/Finding records*/
1512 Table inheritance
1513 ====================================================================
1515 function descendsFromActiveRecord(&$object)
1517 if(substr(strtolower(get_parent_class($object)),-12) == 'activerecord'){
1518 return true;
1520 if(!method_exists($object, 'getInheritanceColumn')){
1521 return false;
1523 $inheritance_column = $object->getInheritanceColumn();
1524 return !empty($inheritance_column);
1528 * Gets the column name for use with single table inheritance. Can be overridden in subclasses.
1530 function getInheritanceColumn()
1532 return empty($this->_inheritanceColumn) ? ($this->hasColumn('type') ? 'type' : false ) : $this->_inheritanceColumn;
1536 * Defines the column name for use with single table inheritance. Can be overridden in subclasses.
1538 function setInheritanceColumn($column_name)
1540 if(!$this->hasColumn($column_name)){
1541 trigger_error(Ak::t('Could not set "%column_name" as the inheritance column as this column is not available on the database.',array('%column_name'=>$column_name)), E_USER_NOTICE);
1542 return false;
1543 }elseif($this->getColumnType($column_name) != 'string'){
1544 trigger_error(Ak::t('Could not set %column_name as the inheritance column as this column type is "%column_type" instead of "string".',array('%column_name'=>$column_name,'%column_type'=>$this->getColumnType($column_name))), E_USER_NOTICE);
1545 return false;
1546 }else{
1547 $this->_inheritanceColumn = $column_name;
1548 return true;
1553 function getSubclasses()
1555 $current_class = get_class($this);
1556 $subclasses = array();
1557 $classes = get_declared_classes();
1559 while ($class = array_shift($classes)) {
1560 $parent_class = get_parent_class($class);
1561 if($parent_class == $current_class || in_array($parent_class,$subclasses)){
1562 $subclasses[] = $class;
1563 }elseif(!empty($parent_class)){
1564 $classes[] = $parent_class;
1567 $subclasses = array_unique(array_map(array(&$this,'_getModelName'),$subclasses));
1568 return $subclasses;
1572 function typeCondition($table_alias = null)
1574 $inheritance_column = $this->getInheritanceColumn();
1575 $type_condition = array();
1576 $table_name = $this->getTableName();
1577 $available_types = array_merge(array($this->getModelName()),$this->getSubclasses());
1578 foreach ($available_types as $subclass){
1579 $type_condition[] = ' '.($table_alias != null ? $table_alias : $table_name).'.'.$inheritance_column.' = \''.AkInflector::humanize(AkInflector::underscore($subclass)).'\' ';
1581 return empty($type_condition) ? '' : '('.join('OR',$type_condition).') ';
1584 /*/Table inheritance*/
1589 Setting Attributes
1590 ====================================================================
1591 See also: Getting Attributes, Model Attributes, Toggling Attributes, Counting Attributes.
1593 function setAttribute($attribute, $value, $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS, $compose_after_set = true)
1595 if($attribute[0] == '_'){
1596 return false;
1599 if($this->isFrozen()){
1600 return false;
1602 if($inspect_for_callback_child_method === true && method_exists($this,'set'.AkInflector::camelize($attribute))){
1603 static $watchdog;
1604 $watchdog[$attribute] = @$watchdog[$attribute]+1;
1605 if($watchdog[$attribute] == 5000){
1606 if((!defined('AK_ACTIVE_RECORD_PROTECT_SET_RECURSION')) || defined('AK_ACTIVE_RECORD_PROTECT_SET_RECURSION') && AK_ACTIVE_RECORD_PROTECT_SET_RECURSION){
1607 trigger_error(Ak::t('You are calling recursively AkActiveRecord::setAttribute by placing parent::setAttribute() or parent::set() on your model "%method" method. In order to avoid this, set the 3rd paramenter of parent::setAttribute to FALSE. If this was the behaviour you expected, please define the constant AK_ACTIVE_RECORD_PROTECT_SET_RECURSION and set it to false',array('%method'=>'set'.AkInflector::camelize($attribute))),E_USER_ERROR);
1608 return false;
1611 $this->{$attribute.'_before_type_cast'} = $value;
1612 return $this->{'set'.AkInflector::camelize($attribute)}($value);
1614 if($this->hasAttribute($attribute)){
1615 $this->{$attribute.'_before_type_cast'} = $value;
1616 $this->$attribute = $value;
1617 if($compose_after_set && !empty($this->_combinedAttributes) && !$this->requiredForCombination($attribute)){
1618 $combined_attributes = $this->_getCombinedAttributesWhereThisAttributeIsUsed($attribute);
1619 foreach ($combined_attributes as $combined_attribute){
1620 $this->composeCombinedAttribute($combined_attribute);
1623 if ($compose_after_set && $this->isCombinedAttribute($attribute)){
1624 $this->decomposeCombinedAttribute($attribute);
1626 }elseif(substr($attribute,-12) == 'confirmation' && $this->hasAttribute(substr($attribute,0,-13))){
1627 $this->$attribute = $value;
1630 if($this->_internationalize){
1631 if(is_array($value)){
1632 $this->setAttributeLocales($attribute, $value);
1633 }elseif(is_string($inspect_for_callback_child_method)){
1634 $this->setAttributeByLocale($attribute, $value, $inspect_for_callback_child_method);
1635 }else{
1636 $this->_groupInternationalizedAttribute($attribute, $value);
1639 return true;
1642 function set($attribute, $value = null, $inspect_for_callback_child_method = true, $compose_after_set = true)
1644 if(is_array($attribute)){
1645 return $this->setAttributes($attribute);
1647 return $this->setAttribute($attribute, $value, $inspect_for_callback_child_method, $compose_after_set);
1651 * Allows you to set all the attributes at once by passing in an array with
1652 * keys matching the attribute names (which again matches the column names).
1653 * Sensitive attributes can be protected from this form of mass-assignment by
1654 * using the $this->setProtectedAttributes method. Or you can alternatively
1655 * specify which attributes can be accessed in with the $this->setAccessibleAttributes method.
1656 * Then all the attributes not included in that won?t be allowed to be mass-assigned.
1658 function setAttributes($attributes, $override_attribute_protection = false)
1660 $this->parseAkelosArgs($attributes);
1661 if(!$override_attribute_protection){
1662 $attributes = $this->removeAttributesProtectedFromMassAssignment($attributes);
1664 if(!empty($attributes) && is_array($attributes)){
1665 foreach ($attributes as $k=>$v){
1666 $this->setAttribute($k, $v);
1672 function setId($value)
1674 if($this->isFrozen()){
1675 return false;
1677 $pk = $this->getPrimaryKey();
1678 $this->$pk = $value;
1679 return true;
1683 /*/Setting Attributes*/
1686 Getting Attributes
1687 ====================================================================
1688 See also: Setting Attributes, Model Attributes, Toggling Attributes, Counting Attributes.
1691 function getAttribute($attribute, $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS)
1693 if($attribute[0] == '_'){
1694 return false;
1697 if($inspect_for_callback_child_method === true && method_exists($this,'get'.AkInflector::camelize($attribute))){
1698 static $watchdog;
1699 $watchdog[@$attribute] = @$watchdog[$attribute]+1;
1700 if($watchdog[$attribute] == 5000){
1701 if((!defined('AK_ACTIVE_RECORD_PROTECT_GET_RECURSION')) || defined('AK_ACTIVE_RECORD_PROTECT_GET_RECURSION') && AK_ACTIVE_RECORD_PROTECT_GET_RECURSION){
1702 trigger_error(Ak::t('You are calling recursivelly AkActiveRecord::getAttribute by placing parent::getAttribute() or parent::get() on your model "%method" method. In order to avoid this, set the 2nd paramenter of parent::getAttribute to FALSE. If this was the behaviour you expected, please define the constant AK_ACTIVE_RECORD_PROTECT_GET_RECURSION and set it to false',array('%method'=>'get'.AkInflector::camelize($attribute))),E_USER_ERROR);
1703 return false;
1706 $value = $this->{'get'.AkInflector::camelize($attribute)}();
1707 return $this->getInheritanceColumn() === $attribute ? AkInflector::humanize(AkInflector::underscore($value)) : $value;
1709 if(isset($this->$attribute) || (!isset($this->$attribute) && $this->isCombinedAttribute($attribute))){
1710 if($this->hasAttribute($attribute)){
1711 if (!empty($this->_combinedAttributes) && $this->isCombinedAttribute($attribute)){
1712 $this->composeCombinedAttribute($attribute);
1714 return isset($this->$attribute) ? $this->$attribute : null;
1715 }elseif($this->_internationalize && $this->_isInternationalizeCandidate($attribute)){
1716 if(!empty($this->$attribute) && is_string($this->$attribute)){
1717 return $this->$attribute;
1719 $current_locale = $this->getCurrentLocale();
1720 if(!empty($this->$attribute[$current_locale]) && is_array($this->$attribute)){
1721 return $this->$attribute[$current_locale];
1723 return $this->getAttribute($current_locale.'_'.$attribute);
1727 if($this->_internationalize){
1728 return $this->getAttributeByLocale($attribute, is_bool($inspect_for_callback_child_method) ? $this->getCurrentLocale() : $inspect_for_callback_child_method);
1730 return null;
1733 function get($attribute = null, $inspect_for_callback_child_method = true)
1735 return !isset($attribute) ? $this->getAttributes($inspect_for_callback_child_method) : $this->getAttribute($attribute, $inspect_for_callback_child_method);
1739 * Returns an array of all the attributes with their names as keys and clones of their objects as values in case they are objects.
1741 function getAttributes()
1743 $attributes = array();
1744 $available_attributes = $this->getAvailableAttributes();
1745 foreach ($available_attributes as $available_attribute){
1746 $attribute = $this->getAttribute($available_attribute['name']);
1747 $attributes[$available_attribute['name']] = AK_PHP5 && is_object($attribute) ? clone($attribute) : $attribute;
1750 if($this->_internationalize){
1751 $current_locale = $this->getCurrentLocale();
1752 foreach ($this->getInternationalizedColumns() as $column=>$languages){
1753 if(empty($attributes[$column]) && isset($attributes[$current_locale.'_'.$column]) && in_array($current_locale,$languages)){
1754 $attributes[$column] = $attributes[$current_locale.'_'.$column];
1759 return $attributes;
1764 * Every Active Record class must use "id" as their primary ID. This getter overwrites the native id method, which isn't being used in this context.
1766 function getId()
1768 return $this->{$this->getPrimaryKey()};
1771 /*/Getting Attributes*/
1776 Toggling Attributes
1777 ====================================================================
1778 See also: Setting Attributes, Getting Attributes.
1781 * Turns an attribute that's currently true into false and vice versa. Returns attribute value.
1783 function toggleAttribute($attribute)
1785 $value = $this->getAttribute($attribute);
1786 $new_value = $value ? false : true;
1787 $this->setAttribute($attribute, $new_value);
1788 return $new_value;
1793 * Toggles the attribute and saves the record.
1795 function toggleAttributeAndSave($attribute)
1797 $value = $this->toggleAttribute($attribute);
1798 if($this->updateAttribute($attribute, $value)){
1799 return $value;
1801 return null;
1804 /*/Toggling Attributes*/
1808 Counting Attributes
1809 ====================================================================
1810 See also: Counting Records, Setting Attributes, Getting Attributes.
1814 * Increments the specified counter by one. So $DiscussionBoard->incrementCounter("post_count",
1815 * $discussion_board_id); would increment the "post_count" counter on the board responding to
1816 * $discussion_board_id. This is used for caching aggregate values, so that they doesn't need to
1817 * be computed every time. Especially important for looping over a collection where each element
1818 * require a number of aggregate values. Like the $DiscussionBoard that needs to list both the number of posts and comments.
1820 function incrementCounter($counter_name, $id, $difference = 1)
1822 return $this->updateAll("$counter_name = $counter_name + $difference", $this->getPrimaryKey().' = '.$this->castAttributeForDatabase($this->getPrimaryKey(), $id)) === 1;
1826 * Works like AkActiveRecord::incrementCounter, but decrements instead.
1828 function decrementCounter($counter_name, $id, $difference = 1)
1830 return $this->updateAll("$counter_name = $counter_name - $difference", $this->getPrimaryKey().' = '.$this->castAttributeForDatabase($this->getPrimaryKey(), $id)) === 1;
1834 * Initializes the attribute to zero if null and subtracts one. Only makes sense for number-based attributes. Returns attribute value.
1836 function decrementAttribute($attribute)
1838 if(!isset($this->$attribute)){
1839 $this->$attribute = 0;
1841 return $this->$attribute -= 1;
1845 * Decrements the attribute and saves the record.
1847 function decrementAndSaveAttribute($attribute)
1849 return $this->updateAttribute($attribute,$this->decrementAttribute($attribute));
1854 * Initializes the attribute to zero if null and adds one. Only makes sense for number-based attributes. Returns attribute value.
1856 function incrementAttribute($attribute)
1858 if(!isset($this->$attribute)){
1859 $this->$attribute = 0;
1861 return $this->$attribute += 1;
1865 * Increments the attribute and saves the record.
1867 function incrementAndSaveAttribute($attribute)
1869 return $this->updateAttribute($attribute,$this->incrementAttribute($attribute));
1872 /*/Counting Attributes*/
1875 Protecting attributes
1876 ====================================================================
1880 * If this macro is used, only those attributed named in it will be accessible
1881 * for mass-assignment, such as new ModelName($attributes) and $this->attributes($attributes).
1882 * This is the more conservative choice for mass-assignment protection.
1883 * If you'd rather start from an all-open default and restrict attributes as needed,
1884 * have a look at AkActiveRecord::setProtectedAttributes().
1886 function setAccessibleAttributes()
1888 $args = func_get_args();
1889 $this->_accessibleAttributes = array_unique(array_merge((array)$this->_accessibleAttributes, $args));
1893 * Attributes named in this macro are protected from mass-assignment, such as
1894 * new ModelName($attributes) and $this->attributes(attributes). Their assignment
1895 * will simply be ignored. Instead, you can use the direct writer methods to do assignment.
1896 * This is meant to protect sensitive attributes to be overwritten by URL/form hackers.
1898 * Example:
1899 * <code>
1900 * class Customer extends ActiveRecord
1902 * function Customer()
1904 * $this->setProtectedAttributes('credit_rating');
1908 * $Customer = new Customer('name' => 'David', 'credit_rating' => 'Excellent');
1909 * $Customer->credit_rating // => null
1910 * $Customer->attributes(array('description' => 'Jolly fellow', 'credit_rating' => 'Superb'));
1911 * $Customer->credit_rating // => null
1913 * $Customer->credit_rating = 'Average'
1914 * $Customer->credit_rating // => 'Average'
1915 * </code>
1917 function setProtectedAttributes()
1919 $args = func_get_args();
1920 $this->_protectedAttributes = array_unique(array_merge((array)$this->_protectedAttributes, $args));
1923 function removeAttributesProtectedFromMassAssignment($attributes)
1925 if(!empty($this->_accessibleAttributes) && is_array($this->_accessibleAttributes) && is_array($attributes)){
1926 foreach (array_keys($attributes) as $k){
1927 if(!in_array($k,$this->_accessibleAttributes)){
1928 unset($attributes[$k]);
1931 }elseif (!empty($this->_protectedAttributes) && is_array($this->_protectedAttributes) && is_array($attributes)){
1932 foreach (array_keys($attributes) as $k){
1933 if(in_array($k,$this->_protectedAttributes)){
1934 unset($attributes[$k]);
1938 return $attributes;
1941 /*/Protecting attributes*/
1945 Model Attributes
1946 ====================================================================
1947 See also: Getting Attributes, Setting Attributes.
1950 * Returns an array of all the attributes that have been specified for serialization as keys and the objects as values.
1952 function getSerializedAttributes()
1954 return isset($this->_serializedAttributes) ? $this->_serializedAttributes : array();
1957 function getAvailableAttributes()
1959 return array_merge($this->getColumns(), $this->getAvailableCombinedAttributes());
1962 function getAttributeCaption($attribute)
1964 return $this->t(AkInflector::humanize($attribute));
1968 * This function is useful in case you need to know if attributes have been assigned to an object.
1970 function hasAttributesDefined()
1972 $attributes = join('',$this->getAttributes());
1973 return empty($attributes);
1978 * Returns the primary key field.
1980 function getPrimaryKey()
1982 if(!isset($this->_primaryKey)){
1983 $this->setPrimaryKey();
1985 return $this->_primaryKey;
1988 function getColumnNames()
1990 if(empty($this->_columnNames)){
1991 $columns = $this->getColumns();
1992 foreach ($columns as $column_name=>$details){
1993 $this->_columnNames[$column_name] = isset($details->columnName) ? $this->t($details->columnName) : $this->getAttributeCaption($column_name);
1996 return $this->_columnNames;
2001 * Returns an array of columns objects where the primary id, all columns ending in "_id" or "_count",
2002 * and columns used for single table inheritance has been removed.
2004 function getContentColumns()
2006 $inheritance_column = $this->getInheritanceColumn();
2007 $columns = $this->getColumns();
2008 foreach ($columns as $name=>$details){
2009 if((substr($name,-3) == '_id' || substr($name,-6) == '_count') ||
2010 !empty($details['primaryKey']) || ($inheritance_column !== false && $inheritance_column == $name)){
2011 unset($columns[$name]);
2014 return $columns;
2018 * Returns an array of names for the attributes available on this object sorted alphabetically.
2020 function getAttributeNames()
2022 if(!isset($this->_activeRecordHasBeenInstantiated)){
2023 return Ak::handleStaticCall();
2025 $attributes = array_keys($this->getAvailableAttributes());
2026 $names = array_combine($attributes,array_map(array(&$this,'getAttributeCaption'), $attributes));
2027 natsort($names);
2028 return $names;
2033 * Returns true if the specified attribute has been set by the user or by a database load and is neither null nor empty?
2035 function isAttributePresent($attribute)
2037 $value = $this->getAttribute($attribute);
2038 return !empty($value);
2042 * Returns true if given attribute exists for this Model.
2044 * @param string $attribute
2045 * @return boolean
2047 function hasAttribute ($attribute)
2049 empty($this->_columns) ? $this->getColumns() : $this->_columns; // HINT: only used by HasAndBelongsToMany joinObjects, if the table is not present yet!
2050 return isset($this->_columns[$attribute]) || (!empty($this->_combinedAttributes) && $this->isCombinedAttribute($attribute));
2053 /*/Model Attributes*/
2057 Combined attributes
2058 ====================================================================
2060 * The Akelos Framework has a handy way to represent combined fields.
2061 * You can add a new attribute to your models using a printf patter to glue
2062 * multiple parameters in a single one.
2064 * For example, If we set...
2065 * $this->addCombinedAttributeConfiguration('name', "%s %s", 'first_name', 'last_name');
2066 * $this->addCombinedAttributeConfiguration('date', "%04d-%02d-%02d", 'year', 'month', 'day');
2067 * $this->setAttributes('first_name=>','John','last_name=>','Smith','year=>',2005,'month=>',9,'day=>',27);
2069 * $this->name // will have "John Smith" as value and
2070 * $this->date // will be 2005-09-27
2072 * On the other hand if you do
2074 * $this->setAttribute('date', '2008-11-30');
2076 * All the 'year', 'month' and 'day' getters will be fired (if they exist) the following attributes will be set
2078 * $this->year // will be 2008
2079 * $this->month // will be 11 and
2080 * $this->day // will be 27
2082 * Sometimes you might need a pattern for composing and another for decomposing attributes. In this case you can specify
2083 * an array as the pattern values, where first element will be the composing pattern and second element will be used
2084 * for decomposing.
2086 * You can also specify a callback method from this object function instead of a pattern. You can also assign a callback
2087 * for composing and another for decomposing by passing their names as an array like on the patterns.
2089 * <?php
2090 * class User extends ActiveRecord
2091 * {
2092 * function User()
2094 * // You can use a multiple patterns array where "%s, %s" will be used for combining fields and "%[^,], %s" will be used
2095 * // for decomposing fields. (as you can see you can also use regular expressions on your patterns)
2096 * $User->addCombinedAttributeConfiguration('name', array("%s, %s","%[^,], %s"), 'last_name', 'first_name');
2098 * //Here we set email_link so compose_email_link() will be triggered for building up the field and parse_email_link will
2099 * // be used for getting the fields out
2100 * $User->addCombinedAttributeConfiguration('email_link', array("compose_email_link","parse_email_link"), 'email', 'name');
2102 * // We need to tell the ActiveRecord to load it's magic (see the example below for a simpler solution)
2103 * $attributes = (array)func_get_args();
2104 * return $this->init($attributes);
2107 * function compose_email_link()
2109 * $args = func_get_arg(0);
2110 * return "<a href=\'mailto:{$args[\'email\']}\'>{$args[\'name\']}</a>";
2111 * }
2112 * function parse_email_link($email_link)
2113 * {
2114 * $results = sscanf($email_link, "<a href=\'mailto:%[^\']\'>%[^<]</a>");
2115 * return array(\'email\'=>$results[0],\'name\'=>$results[1]);
2116 * }
2118 * }
2119 * ?>
2121 * You can also simplify your live by declaring the combined attributes as a class variable like:
2122 * <?php
2123 * class User extends ActiveRecord
2124 * {
2125 * var $combined_attributes array(
2126 * array('name', array("%s, %s","%[^,], %s"), 'last_name', 'first_name')
2127 * array('email_link', array("compose_email_link","parse_email_link"), 'email', 'name')
2128 * );
2130 * // ....
2131 * }
2132 * ?>
2137 * Returns true if given attribute is a combined attribute for this Model.
2139 * @param string $attribute
2140 * @return boolean
2142 function isCombinedAttribute ($attribute)
2144 return !empty($this->_combinedAttributes) && isset($this->_combinedAttributes[$attribute]);
2147 function addCombinedAttributeConfiguration($attribute)
2149 $args = is_array($attribute) ? $attribute : func_get_args();
2150 $columns = array_slice($args,2);
2151 $invalid_columns = array();
2152 foreach ($columns as $colum){
2153 if(!$this->hasAttribute($colum)){
2154 $invalid_columns[] = $colum;
2157 if(!empty($invalid_columns)){
2158 trigger_error(Ak::t('There was an error while setting the composed field "%field_name", the following mapping column/s "%columns" do not exist',
2159 array('%field_name'=>$args[0],'%columns'=>join(', ',$invalid_columns))), E_USER_ERROR);
2160 }else{
2161 $attribute = array_shift($args);
2162 $this->_combinedAttributes[$attribute] = $args;
2163 $this->composeCombinedAttribute($attribute);
2167 function composeCombinedAttributes()
2170 if(!empty($this->_combinedAttributes)){
2171 $attributes = array_keys($this->_combinedAttributes);
2172 foreach ($attributes as $attribute){
2173 $this->composeCombinedAttribute($attribute);
2178 function composeCombinedAttribute($combined_attribute)
2180 if($this->isCombinedAttribute($combined_attribute)){
2181 $config = $this->_combinedAttributes[$combined_attribute];
2182 $pattern = array_shift($config);
2184 $pattern = is_array($pattern) ? $pattern[0] : $pattern;
2185 $got = array();
2187 foreach ($config as $attribute){
2188 if(isset($this->$attribute)){
2189 $got[$attribute] = $this->getAttribute($attribute);
2192 if(count($got) === count($config)){
2193 $this->$combined_attribute = method_exists($this, $pattern) ? $this->{$pattern}($got) : vsprintf($pattern, $got);
2199 * @access private
2201 function _getCombinedAttributesWhereThisAttributeIsUsed($attribute)
2203 $result = array();
2204 foreach ($this->_combinedAttributes as $combined_attribute=>$settings){
2205 if(in_array($attribute,$settings)){
2206 $result[] = $combined_attribute;
2209 return $result;
2213 function requiredForCombination($attribute)
2215 foreach ($this->_combinedAttributes as $settings){
2216 if(in_array($attribute,$settings)){
2217 return true;
2220 return false;
2223 function hasCombinedAttributes()
2225 return count($this->getCombinedSubattributes()) === 0 ? false :true;
2228 function getCombinedSubattributes($attribute)
2230 $result = array();
2231 if(is_array($this->_combinedAttributes[$attribute])){
2232 $attributes = $this->_combinedAttributes[$attribute];
2233 array_shift($attributes);
2234 foreach ($attributes as $attribute_to_check){
2235 if(isset($this->_combinedAttributes[$attribute_to_check])){
2236 $result[] = $attribute_to_check;
2240 return $result;
2243 function decomposeCombinedAttributes()
2245 if(!empty($this->_combinedAttributes)){
2246 $attributes = array_keys($this->_combinedAttributes);
2247 foreach ($attributes as $attribute){
2248 $this->decomposeCombinedAttribute($attribute);
2253 function decomposeCombinedAttribute($combined_attribute, $used_on_combined_fields = false)
2255 if(isset($this->$combined_attribute) && $this->isCombinedAttribute($combined_attribute)){
2256 $config = $this->_combinedAttributes[$combined_attribute];
2257 $pattern = array_shift($config);
2258 $pattern = is_array($pattern) ? $pattern[1] : $pattern;
2260 if(method_exists($this, $pattern)){
2261 $pieces = $this->{$pattern}($this->$combined_attribute);
2262 if(is_array($pieces)){
2263 foreach ($pieces as $k=>$v){
2264 $is_combined = $this->isCombinedAttribute($k);
2265 if($is_combined){
2266 $this->decomposeCombinedAttribute($k);
2268 $this->setAttribute($k, $v, true, !$is_combined);
2270 if($is_combined && !$used_on_combined_fields){
2271 $combined_attributes_contained_on_this_attribute = $this->getCombinedSubattributes($combined_attribute);
2272 if(count($combined_attributes_contained_on_this_attribute)){
2273 $this->decomposeCombinedAttribute($combined_attribute, true);
2277 }else{
2278 $got = sscanf($this->$combined_attribute, $pattern);
2279 for ($x=0; $x<count($got); $x++){
2280 $attribute = $config[$x];
2281 $is_combined = $this->isCombinedAttribute($attribute);
2282 if($is_combined){
2283 $this->decomposeCombinedAttribute($attribute);
2285 $this->setAttribute($attribute, $got[$x], true, !$is_combined);
2291 function getAvailableCombinedAttributes()
2293 $combined_attributes = array();
2294 foreach ($this->_combinedAttributes as $attribute=>$details){
2295 $combined_attributes[$attribute] = array('name'=>$attribute, 'type'=>'string', 'path' => array_shift($details), 'uses'=>$details);
2297 return !empty($this->_combinedAttributes) && is_array($this->_combinedAttributes) ? $combined_attributes : array();
2300 /*/Combined attributes*/
2306 Database connection
2307 ====================================================================
2310 * Establishes the connection to the database. Accepts either a profile name specified in config/config.php or
2311 * an array as input where the 'type' key must be specified with the name of a database adapter (in lower-case)
2312 * example for regular databases (MySQL, Postgresql, etc):
2314 * $AkActiveRecord->establishConnection('development');
2315 * $AkActiveRecord->establishConnection('super_user');
2317 * $AkActiveRecord->establishConnection(
2318 * array(
2319 * 'type' => "mysql",
2320 * 'host' => "localhost",
2321 * 'username' => "myuser",
2322 * 'password' => "mypass",
2323 * 'database' => "somedatabase"
2324 * ));
2326 * Example for SQLite database:
2328 * $AkActiveRecord->establishConnection(
2329 * array(
2330 * 'type' => "sqlite",
2331 * 'dbfile' => "path/to/dbfile"
2335 function &establishConnection($specification_or_profile = AK_DEFAULT_DATABASE_PROFILE)
2337 $adapter =& AkDbAdapter::getInstance($specification_or_profile);
2338 return $this->setConnection(&$adapter);
2343 * Returns true if a connection that's accessible to this class have already been opened.
2345 function isConnected()
2347 return isset($this->_db);
2351 * Returns the connection currently associated with the class. This can also be used to
2352 * "borrow" the connection to do database work unrelated to any of the specific Active Records.
2354 function &getConnection()
2356 return $this->_db;
2360 * Sets the connection for the class.
2362 function &setConnection($db_adapter = null)
2364 if (is_null($db_adapter)){
2365 $db_adapter =& AkDbAdapter::getInstance();
2367 return $this->_db =& $db_adapter;
2371 * @access private
2373 function _getDatabaseType()
2375 return $this->_db->type();
2377 /*/Database connection*/
2381 Table Settings
2382 ====================================================================
2383 See also: Database Reflection.
2387 * Defines the primary key field ? can be overridden in subclasses.
2389 function setPrimaryKey($primary_key = 'id')
2391 if(!$this->hasColumn($primary_key)){
2392 trigger_error($this->t('Opps! We could not find primary key column %primary_key on the table %table, for the model %model',array('%primary_key'=>$primary_key,'%table'=>$this->getTableName(), '%model'=>$this->getModelName())),E_USER_ERROR);
2393 }else {
2394 $this->_primaryKey = $primary_key;
2399 function getTableName($modify_for_associations = true)
2401 if(!isset($this->_tableName)){
2402 // We check if we are on a inheritance Table Model
2403 $this->getClassForDatabaseTableMapping();
2404 if(!isset($this->_tableName)){
2405 $this->setTableName();
2409 if($modify_for_associations && isset($this->_associationTablePrefixes[$this->_tableName])){
2410 return $this->_associationTablePrefixes[$this->_tableName];
2413 return $this->_tableName;
2416 function setTableName($table_name = null, $check_for_existence = AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES, $check_mode = false)
2418 static $available_tables;
2419 if(empty($table_name)){
2420 $table_name = AkInflector::tableize($this->getModelName());
2422 if($check_for_existence){
2423 if(!isset($available_tables) || $check_mode){
2424 if(!isset($this->_db)){
2425 $this->setConnection();
2427 if(empty($_SESSION['__activeRecordColumnsSettingsCache']['available_tables']) ||
2428 !AK_ACTIVE_RECORD_ENABLE_PERSISTENCE){
2429 $_SESSION['__activeRecordColumnsSettingsCache']['available_tables'] = $this->_db->availableTables();
2431 $available_tables = $_SESSION['__activeRecordColumnsSettingsCache']['available_tables'];
2433 if(!in_array($table_name,(array)$available_tables)){
2434 if(!$check_mode){
2435 trigger_error(Ak::t('Unable to set "%table_name" table for the model "%model".'.
2436 ' There is no "%table_name" available into current database layout.'.
2437 ' Set AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES constant to false in order to'.
2438 ' avoid table name validation',array('%table_name'=>$table_name,'%model'=>$this->getModelName())),E_USER_WARNING);
2440 return false;
2443 $this->_tableName = $table_name;
2444 return true;
2448 function getOnlyAvailableAttributes($attributes)
2450 $table_name = $this->getTableName();
2451 $ret_attributes = array();
2452 if(!empty($attributes) && is_array($attributes)){
2453 $available_attributes = $this->getAvailableAttributes();
2455 $keys = array_keys($attributes);
2456 $size = sizeOf($keys);
2457 for ($i=0; $i < $size; $i++){
2458 $k = str_replace($table_name.'.','',$keys[$i]);
2459 if(isset($available_attributes[$k]['name'][$k])){
2460 $ret_attributes[$k] =& $attributes[$keys[$i]];
2464 return $ret_attributes;
2467 function getColumnsForAttributes($attributes)
2469 $ret_attributes = array();
2470 $table_name = $this->getTableName();
2471 if(!empty($attributes) && is_array($attributes)){
2472 $columns = $this->getColumns();
2473 foreach ($attributes as $k=>$v){
2474 $k = str_replace($table_name.'.','',$k);
2475 if(isset($columns[$k]['name'][$k])){
2476 $ret_attributes[$k] = $v;
2480 return $ret_attributes;
2484 * Returns true if given attribute exists for this Model.
2486 * @param string $name Name of table to look in
2487 * @return boolean
2489 function hasColumn($column)
2491 empty($this->_columns) ? $this->getColumns() : $this->_columns;
2492 return isset($this->_columns[$column]);
2496 /*/Table Settings*/
2499 Database Reflection
2500 ====================================================================
2501 See also: Table Settings, Type Casting.
2506 * Initializes the attributes array with keys matching the columns from the linked table and
2507 * the values matching the corresponding default value of that column, so
2508 * that a new instance, or one populated from a passed-in array, still has all the attributes
2509 * that instances loaded from the database would.
2511 function attributesFromColumnDefinition()
2513 $attributes = array();
2515 foreach ((array)$this->getColumns() as $column_name=>$column_settings){
2516 if (!isset($column_settings['primaryKey']) && isset($column_settings['hasDefault'])) {
2517 $attributes[$column_name] = $this->_extractValueFromDefault($column_settings['defaultValue']);
2518 } else {
2519 $attributes[$column_name] = null;
2522 return $attributes;
2526 * Gets information from the database engine about a single table
2528 * @access private
2530 function _databaseTableInternals($table)
2532 if(empty($_SESSION['__activeRecordColumnsSettingsCache']['database_table_'.$table.'_internals']) || !AK_ACTIVE_RECORD_ENABLE_PERSISTENCE){
2533 $_SESSION['__activeRecordColumnsSettingsCache']['database_table_'.$table.'_internals'] = $this->_db->getColumnDetails($table);
2535 $cache[$table] = $_SESSION['__activeRecordColumnsSettingsCache']['database_table_'.$table.'_internals'];
2537 return $cache[$table];
2540 function getColumnsWithRegexBoundaries()
2542 $columns = array_keys($this->getColumns());
2543 foreach ($columns as $k=>$column){
2544 $columns[$k] = '/([^\.])\b('.$column.')\b/';
2546 return $columns;
2551 * If is the first time we use a model this function will run the installer for the model if it exists
2553 * @access private
2555 function _runCurrentModelInstallerIfExists(&$column_objects)
2557 static $installed_models = array();
2558 if(!defined('AK_AVOID_AUTOMATIC_ACTIVE_RECORD_INSTALLERS') && !in_array($this->getModelName(), $installed_models)){
2559 $installed_models[] = $this->getModelName();
2560 require_once(AK_LIB_DIR.DS.'AkInstaller.php');
2561 $installer_name = $this->getModelName().'Installer';
2562 $installer_file = AK_APP_DIR.DS.'installers'.DS.AkInflector::underscore($installer_name).'.php';
2563 if(file_exists($installer_file)){
2564 require_once($installer_file);
2565 if(class_exists($installer_name)){
2566 $Installer = new $installer_name();
2567 if(method_exists($Installer,'install')){
2568 $Installer->install();
2569 $column_objects = $this->_databaseTableInternals($this->getTableName());
2570 return !empty($column_objects);
2575 return false;
2580 * Returns an array of column objects for the table associated with this class.
2582 function getColumns($force_reload = false)
2584 if(empty($this->_columns) || $force_reload){
2585 $this->_columns = $this->getColumnSettings($force_reload);
2588 return (array)$this->_columns;
2591 function getColumnSettings($force_reload = false)
2593 if(empty($this->_columnsSettings) || $force_reload){
2594 $this->loadColumnsSettings($force_reload);
2595 $this->initiateColumnsToNull();
2597 return isset($this->_columnsSettings) ? $this->_columnsSettings : array();
2600 function loadColumnsSettings($force_reload = false)
2602 if(is_null($this->_db)){
2603 $this->setConnection();
2605 $this->_columnsSettings = $force_reload ? null : $this->_getPersistedTableColumnSettings();
2607 if(empty($this->_columnsSettings) || !AK_ACTIVE_RECORD_ENABLE_PERSISTENCE){
2608 if(empty($this->_dataDictionary)){
2609 $this->_dataDictionary =& $this->_db->getDictionary();
2612 $column_objects = $this->_databaseTableInternals($this->getTableName());
2614 if( !isset($this->_avoidTableNameValidation) &&
2615 !is_array($column_objects) &&
2616 !$this->_runCurrentModelInstallerIfExists($column_objects)){
2617 trigger_error(Ak::t('Ooops! Could not fetch details for the table %table_name.', array('%table_name'=>$this->getTableName())), E_USER_ERROR);
2618 return false;
2619 }elseif (empty($column_objects)){
2620 $this->_runCurrentModelInstallerIfExists($column_objects);
2622 if(is_array($column_objects)){
2623 foreach (array_keys($column_objects) as $k){
2624 $this->setColumnSettings($column_objects[$k]->name, $column_objects[$k]);
2627 if(!empty($this->_columnsSettings)){
2628 $this->_persistTableColumnSettings();
2631 return isset($this->_columnsSettings) ? $this->_columnsSettings : array();
2636 function setColumnSettings($column_name, $column_object)
2638 $this->_columnsSettings[$column_name] = array();
2639 $this->_columnsSettings[$column_name]['name'] = $column_object->name;
2641 if($this->_internationalize && $this->_isInternationalizeCandidate($column_object->name)){
2642 $this->_addInternationalizedColumn($column_object->name);
2645 $this->_columnsSettings[$column_name]['type'] = $this->getAkelosDataType($column_object);
2646 if(!empty($column_object->primary_key)){
2647 $this->_primaryKey = empty($this->_primaryKey) ? $column_object->name : $this->_primaryKey;
2648 $this->_columnsSettings[$column_name]['primaryKey'] = true;
2650 if(!empty($column_object->auto_increment)){
2651 $this->_columnsSettings[$column_name]['autoIncrement'] = true;
2653 if(!empty($column_object->has_default)){
2654 $this->_columnsSettings[$column_name]['hasDefault'] = true;
2656 if(!empty($column_object->not_null)){
2657 $this->_columnsSettings[$column_name]['notNull'] = true;
2659 if(!empty($column_object->max_length) && $column_object->max_length > 0){
2660 $this->_columnsSettings[$column_name]['maxLength'] = $column_object->max_length;
2662 if(!empty($column_object->scale) && $column_object->scale > 0){
2663 $this->_columnsSettings[$column_name]['scale'] = $column_object->scale;
2665 if(isset($column_object->default_value)){
2666 $this->_columnsSettings[$column_name]['defaultValue'] = $column_object->default_value;
2672 * Resets all the cached information about columns, which will cause they to be reloaded on the next request.
2674 function resetColumnInformation()
2676 if(isset($_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName()])){
2677 unset($_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName()]);
2679 $this->_clearPersitedColumnSettings();
2680 $this->_columnNames = $this->_columns = $this->_columnsSettings = $this->_contentColumns = array();
2684 * @access private
2686 function _getColumnsSettings()
2688 return $_SESSION['__activeRecordColumnsSettingsCache'];
2692 * @access private
2694 function _getModelColumnSettings()
2696 return $_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName()];
2700 * @access private
2702 function _persistTableColumnSettings()
2704 $_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName().'_column_settings'] = $this->_columnsSettings;
2708 * @access private
2710 function _getPersistedTableColumnSettings()
2712 $model_name = $this->getModelName();
2713 if(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA && !isset($_SESSION['__activeRecordColumnsSettingsCache']) && AK_CACHE_HANDLER > 0){
2714 $this->_loadPersistedColumnSetings();
2716 return isset($_SESSION['__activeRecordColumnsSettingsCache'][$model_name.'_column_settings']) ?
2717 $_SESSION['__activeRecordColumnsSettingsCache'][$model_name.'_column_settings'] : false;
2721 * @access private
2723 function _clearPersitedColumnSettings()
2725 if(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA && AK_CACHE_HANDLER > 0){
2726 $Cache =& Ak::cache();
2727 $Cache->init(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE);
2728 $Cache->clean('AkActiveRecord');
2733 * @access private
2735 function _savePersitedColumnSettings()
2737 if(isset($_SESSION['__activeRecordColumnsSettingsCache'])){
2738 $Cache =& Ak::cache();
2739 $Cache->init(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE);
2740 $Cache->save(serialize($_SESSION['__activeRecordColumnsSettingsCache']), 'active_record_db_cache', 'AkActiveRecord');
2745 * @access private
2747 function _loadPersistedColumnSetings()
2749 if(!isset($_SESSION['__activeRecordColumnsSettingsCache'])){
2750 $Cache =& Ak::cache();
2751 $Cache->init(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE);
2752 if($serialized_column_settings = $Cache->get('active_record_db_cache', 'AkActiveRecord') && !empty($serialized_column_settings)){
2753 $_SESSION['__activeRecordColumnsSettingsCache'] = @unserialize($serialized_column_settings);
2755 }elseif(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA){
2756 register_shutdown_function(array($this,'_savePersitedColumnSettings'));
2758 }else{
2759 $_SESSION['__activeRecordColumnsSettingsCache'] = array();
2764 function initiateAttributeToNull($attribute)
2766 if(!isset($this->$attribute)){
2767 $this->$attribute = null;
2771 function initiateColumnsToNull()
2773 if(isset($this->_columnsSettings) && is_array($this->_columnsSettings)){
2774 array_map(array(&$this,'initiateAttributeToNull'),array_keys($this->_columnsSettings));
2780 * Akelos data types are mapped to phpAdodb data types
2782 * Returns the Akelos data type for an Adodb Column Object
2784 * 'C'=>'string', // Varchar, capped to 255 characters.
2785 * 'X' => 'text' // Larger varchar, capped to 4000 characters (to be compatible with Oracle).
2786 * 'XL' => 'text' // For Oracle, returns CLOB, otherwise the largest varchar size.
2788 * 'C2' => 'string', // Multibyte varchar
2789 * 'X2' => 'string', // Multibyte varchar (largest size)
2791 * 'B' => 'binary', // BLOB (binary large object)
2793 * 'D' => array('date', 'datetime'), // Date (some databases do not support this, and we return a datetime type)
2794 * 'T' => array('datetime', 'timestamp'), //Datetime or Timestamp
2795 * 'L' => 'boolean', // Integer field suitable for storing booleans (0 or 1)
2796 * 'I' => // Integer (mapped to I4)
2797 * 'I1' => 'integer', // 1-byte integer
2798 * 'I2' => 'integer', // 2-byte integer
2799 * 'I4' => 'integer', // 4-byte integer
2800 * 'I8' => 'integer', // 8-byte integer
2801 * 'F' => 'float', // Floating point number
2802 * 'N' => 'integer' // Numeric or decimal number
2804 * @return string One of this 'string','text','integer','float','datetime','timestamp',
2805 * 'time', 'name','date', 'binary', 'boolean'
2807 function getAkelosDataType(&$adodb_column_object)
2809 $config_var_name = AkInflector::variablize($adodb_column_object->name.'_data_type');
2810 if(!empty($this->{$config_var_name})){
2811 return $this->{$config_var_name};
2813 if(stristr($adodb_column_object->type, 'BLOB')){
2814 return 'binary';
2816 if(!empty($adodb_column_object->auto_increment)) {
2817 return 'serial';
2819 $meta_type = $this->_dataDictionary->MetaType($adodb_column_object);
2820 $adodb_data_types = array(
2821 'C'=>'string', // Varchar, capped to 255 characters.
2822 'X' => 'text', // Larger varchar, capped to 4000 characters (to be compatible with Oracle).
2823 'XL' => 'text', // For Oracle, returns CLOB, otherwise the largest varchar size.
2825 'C2' => 'string', // Multibyte varchar
2826 'X2' => 'string', // Multibyte varchar (largest size)
2828 'B' => 'binary', // BLOB (binary large object)
2830 'D' => array('date'), // Date
2831 'T' => array('datetime', 'timestamp'), //Datetime or Timestamp
2832 'L' => 'boolean', // Integer field suitable for storing booleans (0 or 1)
2833 'R' => 'serial', // Serial Integer
2834 'I' => 'integer', // Integer (mapped to I4)
2835 'I1' => 'integer', // 1-byte integer
2836 'I2' => 'integer', // 2-byte integer
2837 'I4' => 'integer', // 4-byte integer
2838 'I8' => 'integer', // 8-byte integer
2839 'F' => 'float', // Floating point number
2840 'N' => 'decimal' // Numeric or decimal number
2843 $result = !isset($adodb_data_types[$meta_type]) ?
2844 'string' :
2845 (is_array($adodb_data_types[$meta_type]) ? $adodb_data_types[$meta_type][0] : $adodb_data_types[$meta_type]);
2847 if($result == 'text'){
2848 if(stristr($adodb_column_object->type, 'CHAR') | (isset($adodb_column_object->max_length) && $adodb_column_object->max_length > 0 &&$adodb_column_object->max_length < 256 )){
2849 return 'string';
2853 if($this->_getDatabaseType() == 'mysql'){
2854 if($result == 'integer' && stristr($adodb_column_object->type, 'TINYINT')){
2855 return 'boolean';
2857 }elseif($this->_getDatabaseType() == 'postgre'){
2858 if($adodb_column_object->type == 'timestamp' || $result == 'datetime'){
2859 $adodb_column_object->max_length = 19;
2861 }elseif($this->_getDatabaseType() == 'sqlite'){
2862 if($result == 'integer' && (int)$adodb_column_object->max_length === 1 && stristr($adodb_column_object->type, 'TINYINT')){
2863 return 'boolean';
2864 }elseif($result == 'integer' && stristr($adodb_column_object->type, 'DOUBLE')){
2865 return 'float';
2869 if($result == 'datetime' && substr($adodb_column_object->name,-3) == '_on'){
2870 $result = 'date';
2873 return $result;
2878 * This method retrieves current class name that will be used to map
2879 * your database to this object.
2881 function getClassForDatabaseTableMapping()
2883 $class_name = get_class($this);
2884 if(is_subclass_of($this,'akactiverecord') || is_subclass_of($this,'AkActiveRecord')){
2885 $parent_class = get_parent_class($this);
2886 while (substr(strtolower($parent_class),-12) != 'activerecord'){
2887 $class_name = $parent_class;
2888 $parent_class = get_parent_class($parent_class);
2892 $class_name = $this->_getModelName($class_name);
2893 // This is an Active Record Inheritance so we set current table to parent table.
2894 if(!empty($class_name) && strtolower($class_name) != 'activerecord'){
2895 $this->_inheritanceClassName = $class_name;
2896 @$this->setTableName(AkInflector::tableize($class_name), false);
2899 return $class_name;
2902 function getDisplayField()
2904 return empty($this->displayField) && $this->hasAttribute('name') ? 'name' : (isset($this->displayField) && $this->hasAttribute($this->displayField) ? $this->displayField : $this->getPrimaryKey());
2907 function setDisplayField($attribute_name)
2909 if($this->hasAttribute($attribute_name)){
2910 $this->displayField = $attribute_name;
2911 return true;
2912 }else {
2913 return false;
2920 /*/Database Reflection*/
2923 Localization
2924 ====================================================================
2927 function t($string, $array = null)
2929 return Ak::t($string, $array, AkInflector::underscore($this->getModelName()));
2932 function getInternationalizedColumns()
2934 static $cache;
2935 $model = $this->getModelName();
2936 $available_locales = $this->getAvailableLocales();
2937 if(empty($cache[$model])){
2938 $cache[$model] = array();
2939 foreach ($this->getColumnSettings() as $column_name=>$details){
2940 if(!empty($details['i18n'])){
2941 $_tmp_pos = strpos($column_name,'_');
2942 $column = substr($column_name,$_tmp_pos+1);
2943 $lang = substr($column_name,0,$_tmp_pos);
2944 if(in_array($lang, $available_locales)){
2945 $cache[$model][$column] = empty($cache[$model][$column]) ? array($lang) :
2946 array_merge($cache[$model][$column] ,array($lang));
2952 return $cache[$model];
2955 function getAvailableLocales()
2957 static $available_locales;
2958 if(empty($available_locales)){
2959 if(defined('AK_ACTIVE_RECORD_DEFAULT_LOCALES')){
2960 $available_locales = Ak::stringToArray(AK_ACTIVE_RECORD_DEFAULT_LOCALES);
2961 }else{
2962 $available_locales = Ak::langs();
2965 return $available_locales;
2968 function getCurrentLocale()
2970 static $current_locale;
2971 if(empty($current_locale)){
2972 $current_locale = Ak::lang();
2973 $available_locales = $this->getAvailableLocales();
2974 if(!in_array($current_locale, $available_locales)){
2975 $current_locale = array_shift($available_locales);
2978 return $current_locale;
2982 function getAttributeByLocale($attribute, $locale)
2984 $internationalizable_columns = $this->getInternationalizedColumns();
2985 if(!empty($internationalizable_columns[$attribute]) && is_array($internationalizable_columns[$attribute]) && in_array($locale, $internationalizable_columns[$attribute])){
2986 return $this->getAttribute($locale.'_'.$attribute);
2990 function getAttributeLocales($attribute)
2992 $attribute_locales = array();
2993 foreach ($this->getAvailableLocales() as $locale){
2994 if($this->hasColumn($locale.'_'.$attribute)){
2995 $attribute_locales[$locale] = $this->getAttributeByLocale($attribute, $locale);
2998 return $attribute_locales;
3001 function setAttributeByLocale($attribute, $value, $locale)
3003 $internationalizable_columns = $this->getInternationalizedColumns();
3005 if($this->_isInternationalizeCandidate($locale.'_'.$attribute) && !empty($internationalizable_columns[$attribute]) && is_array($internationalizable_columns[$attribute]) && in_array($locale, $internationalizable_columns[$attribute])){
3006 $this->setAttribute($locale.'_'.$attribute, $value);
3011 function setAttributeLocales($attribute, $values = array())
3013 foreach ($values as $locale=>$value){
3014 $this->setAttributeByLocale($attribute, $value, $locale);
3019 * @access private
3021 function _delocalizeAttribute($attribute)
3023 return $this->_isInternationalizeCandidate($attribute) ? substr($attribute,3) : $attribute;
3027 * @access private
3029 function _isInternationalizeCandidate($column_name)
3031 $pos = strpos($column_name,'_');
3032 return $pos === 2 && in_array(substr($column_name,0,$pos),$this->getAvailableLocales());
3036 * @access private
3038 function _addInternationalizedColumn($column_name)
3040 $this->_columnsSettings[$column_name]['i18n'] = true;
3045 * Adds an internationalized attribute to an array containing other locales for the same column name
3047 * Example:
3048 * es_title and en_title will be available user title = array('es'=>'...', 'en' => '...')
3050 * @access private
3052 function _groupInternationalizedAttribute($attribute, $value)
3054 if($this->_internationalize && $this->_isInternationalizeCandidate($attribute)){
3055 if(!empty($this->$attribute)){
3056 $_tmp_pos = strpos($attribute,'_');
3057 $column = substr($attribute,$_tmp_pos+1);
3058 $lang = substr($attribute,0,$_tmp_pos);
3059 $this->$column = empty($this->$column) ? array() : $this->$column;
3060 if(empty($this->$column) || (!empty($this->$column) && is_array($this->$column))){
3061 $this->$column = empty($this->$column) ? array($lang=>$value) : array_merge($this->$column,array($lang=>$value));
3067 /*/Localization*/
3073 Type Casting
3074 ====================================================================
3075 See also: Database Reflection.
3078 function getAttributesBeforeTypeCast()
3080 $attributes_array = array();
3081 $available_attributes = $this->getAvailableAttributes();
3082 foreach ($available_attributes as $attribute){
3083 $attribute_value = $this->getAttributeBeforeTypeCast($attribute['name']);
3084 if(!empty($attribute_value)){
3085 $attributes_array[$attribute['name']] = $attribute_value;
3088 return $attributes_array;
3092 function getAttributeBeforeTypeCast($attribute)
3094 if(isset($this->{$attribute.'_before_type_cast'})){
3095 return $this->{$attribute.'_before_type_cast'};
3097 return null;
3100 function quotedId()
3102 return $this->castAttributeForDatabase($this->getPrimaryKey(), $this->getId());
3106 * Specifies that the attribute by the name of attr_name should be serialized before saving to the database and unserialized after loading from the database. If class_name is specified, the serialized object must be of that class on retrieval, as a new instance of the object will be loaded with serialized values.
3108 function setSerializeAttribute($attr_name, $class_name = null)
3110 if($this->hasColumn($attr_name)){
3111 $this->_serializedAttributes[$attr_name] = $class_name;
3115 function getAvailableAttributesQuoted()
3117 return $this->getAttributesQuoted($this->getAttributes());
3121 function getAttributesQuoted($attributes_array)
3123 $set = array();
3124 $attributes_array = $this->getSanitizedConditionsArray($attributes_array);
3125 foreach (array_diff($attributes_array,array('')) as $k=>$v){
3126 $set[$k] = $k.'='.$v;
3129 return $set;
3132 function getColumnType($column_name)
3134 empty($this->_columns) ? $this->getColumns() : null;
3135 return empty($this->_columns[$column_name]['type']) ? false : $this->_columns[$column_name]['type'];
3138 function getColumnScale($column_name)
3140 empty($this->_columns) ? $this->getColumns() : null;
3141 return empty($this->_columns[$column_name]['scale']) ? false : $this->_columns[$column_name]['scale'];
3144 function castAttributeForDatabase($column_name, $value, $add_quotes = true)
3146 $result = '';
3147 switch ($this->getColumnType($column_name)) {
3148 case 'datetime':
3149 if(!empty($value)){
3150 $date_time = $this->_db->quote_datetime(Ak::getTimestamp($value));
3151 $result = $add_quotes ? $date_time : trim($date_time ,"'");
3152 }else{
3153 $result = 'null';
3155 break;
3157 case 'date':
3158 if(!empty($value)){
3159 $date = $this->_db->quote_date(Ak::getTimestamp($value));
3160 $result = $add_quotes ? $date : trim($date, "'");
3161 }else{
3162 $result = 'null';
3164 break;
3166 case 'boolean':
3167 $result = is_null($value) ? 'null' : (!empty($value) ? "'1'" : "'0'");
3168 break;
3170 case 'binary':
3171 if($this->_getDatabaseType() == 'postgre'){
3172 $result = is_null($value) ? 'null::bytea ' : " '".$this->_db->escape_blob($value)."'::bytea ";
3173 }else{
3174 $result = is_null($value) ? 'null' : ($add_quotes ? $this->_db->quote_string($value) : $value);
3176 break;
3178 case 'decimal':
3179 if(is_null($value)){
3180 $result = 'null';
3181 }else{
3182 if($scale = $this->getColumnScale($column_name)){
3183 $value = number_format($value, $scale, '.', '');
3185 $result = $add_quotes ? $this->_db->quote_string($value) : $value;
3187 break;
3189 case 'serial':
3190 case 'integer':
3191 $result = (is_null($value) || $value==='') ? 'null' : (integer)$value;
3192 break;
3194 case 'float':
3195 $result = (empty($value) && $value !== 0) ? 'null' : (is_numeric($value) ? $value : $this->_db->quote_string($value));
3196 $result = !empty($this->_columns[$column_name]['notNull']) && $result == 'null' && $this->_getDatabaseType() == 'sqlite' ? '0' : $result;
3197 break;
3199 default:
3200 $result = is_null($value) ? 'null' : ($add_quotes ? $this->_db->quote_string($value) : $value);
3201 break;
3204 // !! nullable vs. not nullable !!
3205 return empty($this->_columns[$column_name]['notNull']) ? ($result === '' ? "''" : $result) : ($result === 'null' ? '' : $result);
3208 function castAttributeFromDatabase($column_name, $value)
3210 if($this->hasColumn($column_name)){
3211 $column_type = $this->getColumnType($column_name);
3213 if($column_type){
3214 if('integer' == $column_type){
3215 return is_null($value) ? null : (integer)$value;
3216 //return is_null($value) ? null : $value; // maybe for bigint we can do this
3217 }elseif('boolean' == $column_type){
3218 if (is_null($value)) {
3219 return null;
3221 if ($this->_getDatabaseType()=='postgre'){
3222 return $value=='t' ? true : false;
3224 return (integer)$value === 1 ? true : false;
3225 }elseif(!empty($value) && 'date' == $column_type && strstr(trim($value),' ')){
3226 return substr($value,0,10) == '0000-00-00' ? null : str_replace(substr($value,strpos($value,' ')), '', $value);
3227 }elseif (!empty($value) && 'datetime' == $column_type && substr($value,0,10) == '0000-00-00'){
3228 return null;
3229 }elseif ('binary' == $column_type && $this->_getDatabaseType() == 'postgre'){
3230 $value = $this->_db->unescape_blob($value);
3231 $value = empty($value) || trim($value) == 'null' ? null : $value;
3235 return $value;
3240 * Joins date arguments into a single attribute. Like the array generated by the date_helper, so
3241 * array('published_on(1i)' => 2002, 'published_on(2i)' => 'January', 'published_on(3i)' => 24)
3242 * Will be converted to array('published_on'=>'2002-01-24')
3244 * @access private
3246 function _castDateParametersFromDateHelper_(&$params)
3248 if(empty($params)){
3249 return;
3251 $date_attributes = array();
3252 foreach ($params as $k=>$v) {
3253 if(preg_match('/^([A-Za-z0-9_]+)\(([1-5]{1})i\)$/',$k,$match)){
3254 $date_attributes[$match[1]][$match[2]] = $v;
3255 $this->$k = $v;
3256 unset($params[$k]);
3259 foreach ($date_attributes as $attribute=>$date){
3260 $params[$attribute] = trim(@$date[1].'-'.@$date[2].'-'.@$date[3].' '.@$date[4].':'.@$date[5].':'.@$date[6],' :-');
3265 * @access private
3267 function _addBlobQueryStack($column_name, $blob_value)
3269 $this->_BlobQueryStack[$column_name] = $blob_value;
3273 * @access private
3275 function _updateBlobFields($condition)
3277 if(!empty($this->_BlobQueryStack) && is_array($this->_BlobQueryStack)){
3278 foreach ($this->_BlobQueryStack as $column=>$value){
3279 $this->_db->UpdateBlob($this->getTableName(), $column, $value, $condition);
3281 $this->_BlobQueryStack = null;
3285 /*/Type Casting*/
3288 Optimistic Locking
3289 ====================================================================
3291 * Active Records support optimistic locking if the field <tt>lock_version</tt> is present. Each update to the
3292 * record increments the lock_version column and the locking facilities ensure that records instantiated twice
3293 * will let the last one saved return false on save() if the first was also updated. Example:
3295 * $p1 = new Person(1);
3296 * $p2 = new Person(1);
3298 * $p1->first_name = "Michael";
3299 * $p1->save();
3301 * $p2->first_name = "should fail";
3302 * $p2->save(); // Returns false
3304 * You're then responsible for dealing with the conflict by checking the return value of save(); and either rolling back, merging,
3305 * or otherwise apply the business logic needed to resolve the conflict.
3307 * You must ensure that your database schema defaults the lock_version column to 0.
3309 * This behavior can be turned off by setting <tt>AkActiveRecord::lock_optimistically = false</tt>.
3311 function isLockingEnabled()
3313 return (!isset($this->lock_optimistically) || $this->lock_optimistically !== false) && $this->hasColumn('lock_version');
3315 /*/Optimistic Locking*/
3319 Callbacks
3320 ====================================================================
3321 See also: Observers.
3323 * Callbacks are hooks into the life-cycle of an Active Record object that allows you to trigger logic
3324 * before or after an alteration of the object state. This can be used to make sure that associated and
3325 * dependent objects are deleted when destroy is called (by overwriting beforeDestroy) or to massage attributes
3326 * before they're validated (by overwriting beforeValidation). As an example of the callbacks initiated, consider
3327 * the AkActiveRecord->save() call:
3329 * - (-) save()
3330 * - (-) needsValidation()
3331 * - (1) beforeValidation()
3332 * - (2) beforeValidationOnCreate() / beforeValidationOnUpdate()
3333 * - (-) validate()
3334 * - (-) validateOnCreate()
3335 * - (4) afterValidation()
3336 * - (5) afterValidationOnCreate() / afterValidationOnUpdate()
3337 * - (6) beforeSave()
3338 * - (7) beforeCreate() / beforeUpdate()
3339 * - (-) create()
3340 * - (8) afterCreate() / afterUpdate()
3341 * - (9) afterSave()
3342 * - (10) afterDestroy()
3343 * - (11) beforeDestroy()
3346 * That's a total of 15 callbacks, which gives you immense power to react and prepare for each state in the
3347 * Active Record lifecycle.
3349 * Examples:
3350 * class CreditCard extends ActiveRecord
3352 * // Strip everything but digits, so the user can specify "555 234 34" or
3353 * // "5552-3434" or both will mean "55523434"
3354 * function beforeValidationOnCreate
3356 * if(!empty($this->number)){
3357 * $this->number = ereg_replace('[^0-9]*','',$this->number);
3362 * class Subscription extends ActiveRecord
3364 * // Note: This is not implemented yet
3365 * var $beforeCreate = 'recordSignup';
3367 * function recordSignup()
3369 * $this->signed_up_on = date("Y-m-d");
3373 * class Firm extends ActiveRecord
3375 * //Destroys the associated clients and people when the firm is destroyed
3376 * // Note: This is not implemented yet
3377 * var $beforeDestroy = array('destroyAssociatedPeople', 'destroyAssociatedClients');
3379 * function destroyAssociatedPeople()
3381 * $Person = new Person();
3382 * $Person->destroyAll("firm_id=>", $this->id);
3385 * function destroyAssociatedClients()
3387 * $Client = new Client();
3388 * $Client->destroyAll("client_of=>", $this->id);
3393 * == Canceling callbacks ==
3395 * If a before* callback returns false, all the later callbacks and the associated action are cancelled. If an after* callback returns
3396 * false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks
3397 * defined as methods on the model, which are called last.
3399 * Override this methods to hook Active Records
3401 * @access public
3404 function beforeCreate(){return true;}
3405 function beforeValidation(){return true;}
3406 function beforeValidationOnCreate(){return true;}
3407 function beforeValidationOnUpdate(){return true;}
3408 function beforeSave(){return true;}
3409 function beforeUpdate(){return true;}
3410 function afterUpdate(){return true;}
3411 function afterValidation(){return true;}
3412 function afterValidationOnCreate(){return true;}
3413 function afterValidationOnUpdate(){return true;}
3414 function afterCreate(){return true;}
3415 function afterDestroy(){return true;}
3416 function beforeDestroy(){return true;}
3417 function afterSave(){return true;}
3419 /*/Callbacks*/
3423 Transactions
3424 ====================================================================
3426 * Transaction support for database operations
3428 * Transactions are enabled automatically for Active record objects, But you can nest transactions within models.
3429 * This transactions are nested, and only the outermost will be executed
3431 * $User->transactionStart();
3432 * $User->create('username'=>'Bermi');
3433 * $Members->create('username'=>'Bermi');
3435 * if(!checkSomething()){
3436 * $User->transactionFail();
3439 * $User->transactionComplete();
3442 function transactionStart()
3444 return $this->_db->startTransaction();
3447 function transactionComplete()
3449 return $this->_db->stopTransaction();
3452 function transactionFail()
3454 $this->_db->failTransaction();
3455 return false;
3458 function transactionHasFailed()
3460 return $this->_db->hasTransactionFailed();
3463 /*/Transactions*/
3469 Validators
3470 ====================================================================
3471 See also: Error Handling.
3473 * Active Records implement validation by overwriting AkActiveRecord::validate (or the variations, validateOnCreate and
3474 * validateOnUpdate). Each of these methods can inspect the state of the object, which usually means ensuring
3475 * that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
3477 * Example:
3479 * class Person extends ActiveRecord
3481 * function validate()
3483 * $this->addErrorOnEmpty(array('first_name', 'last_name'));
3484 * if(!preg_match('/[0-9]{4,12}/', $this->phone_number)){
3485 * $this->addError("phone_number", "has invalid format");
3489 * function validateOnCreate() // is only run the first time a new object is saved
3491 * if(!isValidDiscount($this->membership_discount)){
3492 * $this->addError("membership_discount", "has expired");
3496 * function validateOnUpdate()
3498 * if($this->countChangedAttributes() == 0){
3499 * $this->addErrorToBase("No changes have occurred");
3504 * $Person = new Person(array("first_name" => "David", "phone_number" => "what?"));
3505 * $Person->save(); // => false (and doesn't do the save);
3506 * $Person->hasErrors(); // => false
3507 * $Person->countErrors(); // => 2
3508 * $Person->getErrorsOn("last_name"); // => "can't be empty"
3509 * $Person->getErrorsOn("phone_number"); // => "has invalid format"
3510 * $Person->yieldEachFullError(); // => "Last name can't be empty \n Phone number has invalid format"
3512 * $Person->setAttributes(array("last_name" => "Heinemeier", "phone_number" => "555-555"));
3513 * $Person->save(); // => true (and person is now saved in the database)
3515 * An "_errors" array is available for every Active Record.
3520 * Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
3522 * Model:
3523 * class Person extends ActiveRecord
3525 * function validate()
3527 * $this->validatesConfirmationOf('password');
3528 * $this->validatesConfirmationOf('email_address', "should match confirmation");
3532 * View:
3533 * <?=$form_helper->password_field("person", "password"); ?>
3534 * <?=$form_helper->password_field("person", "password_confirmation"); ?>
3536 * The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual.
3537 * It exists only as an in-memory variable for validating the password. This check is performed only if password_confirmation
3538 * is not null.
3541 function validatesConfirmationOf($attribute_names, $message = 'confirmation')
3543 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3544 $attribute_names = Ak::toArray($attribute_names);
3545 foreach ($attribute_names as $attribute_name){
3546 $attribute_accessor = $attribute_name.'_confirmation';
3547 if(isset($this->$attribute_accessor) && @$this->$attribute_accessor != @$this->$attribute_name){
3548 $this->addError($attribute_name, $message);
3554 * Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
3556 * class Person extends ActiveRecord
3558 * function validateOnCreate()
3560 * $this->validatesAcceptanceOf('terms_of_service');
3561 * $this->validatesAcceptanceOf('eula', "must be abided");
3565 * The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed only if
3566 * terms_of_service is not null.
3569 * @param accept 1
3570 * Specifies value that is considered accepted. The default value is a string "1", which makes it easy to relate to an HTML checkbox.
3572 function validatesAcceptanceOf($attribute_names, $message = 'accepted', $accept = 1)
3574 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3576 $attribute_names = Ak::toArray($attribute_names);
3577 foreach ($attribute_names as $attribute_name){
3578 if(@$this->$attribute_name != $accept){
3579 $this->addError($attribute_name, $message);
3585 * Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
3587 * class Book extends ActiveRecord
3589 * var $has_many = 'pages';
3590 * var $belongs_to = 'library';
3592 * function validate(){
3593 * $this->validatesAssociated(array('pages', 'library'));
3598 * Warning: If, after the above definition, you then wrote:
3600 * class Page extends ActiveRecord
3602 * var $belongs_to = 'book';
3603 * function validate(){
3604 * $this->validatesAssociated('book');
3608 * ...this would specify a circular dependency and cause infinite recursion.
3610 * NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
3611 * is both present and guaranteed to be valid, you also need to use validatesPresenceOf.
3613 function validatesAssociated($attribute_names, $message = 'invalid')
3615 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3616 $attribute_names = Ak::toArray($attribute_names);
3617 foreach ($attribute_names as $attribute_name){
3618 if(!empty($this->$attribute_name)){
3619 if(is_array($this->$attribute_name)){
3620 foreach(array_keys($this->$attribute_name) as $k){
3621 if(method_exists($this->{$attribute_name}[$k],'isValid') && !$this->{$attribute_name}[$k]->isValid()){
3622 $this->addError($attribute_name, $message);
3625 }elseif (method_exists($this->$attribute_name,'isValid') && !$this->$attribute_name->isValid()){
3626 $this->addError($attribute_name, $message);
3632 function isBlank($value = null)
3634 return trim((string)$value) == '';
3638 * Validates that the specified attributes are not blank (as defined by AkActiveRecord::isBlank()).
3640 function validatesPresenceOf($attribute_names, $message = 'blank')
3642 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3644 $attribute_names = Ak::toArray($attribute_names);
3645 foreach ($attribute_names as $attribute_name){
3646 $this->addErrorOnBlank($attribute_name, $message);
3651 * Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
3653 * class Person extends ActiveRecord
3655 * function validate()
3657 * $this->validatesLengthOf('first_name', array('maximum'=>30));
3658 * $this->validatesLengthOf('last_name', array('maximum'=>30,'message'=> "less than %d if you don't mind"));
3659 * $this->validatesLengthOf('last_name', array('within'=>array(7, 32)));
3660 * $this->validatesLengthOf('last_name', array('in'=>array(6, 20), 'too_long' => "pick a shorter name", 'too_short' => "pick a longer name"));
3661 * $this->validatesLengthOf('fav_bra_size', array('minimum'=>1, 'too_short'=>"please enter at least %d character"));
3662 * $this->validatesLengthOf('smurf_leader', array('is'=>4, 'message'=>"papa is spelled with %d characters... don't play me."));
3666 * NOTE: Be aware that $this->validatesLengthOf('field', array('is'=>5)); Will match a string containing 5 characters (Ie. "Spain"), an integer 5, and an array with 5 elements. You must supply additional checking to check for appropriate types.
3668 * Configuration options:
3669 * <tt>minimum</tt> - The minimum size of the attribute
3670 * <tt>maximum</tt> - The maximum size of the attribute
3671 * <tt>is</tt> - The exact size of the attribute
3672 * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
3673 * <tt>in</tt> - A synonym(or alias) for :within
3674 * <tt>allow_null</tt> - Attribute may be null; skip validation.
3676 * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default "is" "is too long (max is %d characters)")
3677 * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default "is" "is too short (min is %d characters)")
3678 * <tt>wrong_length</tt> - The error message if using the "is" method and the attribute is the wrong size (default "is" "is the wrong length (should be %d characters)")
3679 * <tt>message</tt> - The error message to use for a "minimum", "maximum", or "is" violation. An alias of the appropriate too_long/too_short/wrong_length message
3681 function validatesLengthOf($attribute_names, $options = array())
3683 // Merge given options with defaults.
3684 $default_options = array(
3685 'too_long' => $this->_defaultErrorMessages['too_long'],
3686 'too_short' => $this->_defaultErrorMessages['too_short'],
3687 'wrong_length' => $this->_defaultErrorMessages['wrong_length'],
3688 'allow_null' => false
3691 $range_options = array();
3692 foreach ($options as $k=>$v){
3693 if(in_array($k,array('minimum','maximum','is','in','within'))){
3694 $range_options[$k] = $v;
3695 $option = $k;
3696 $option_value = $v;
3700 // Ensure that one and only one range option is specified.
3701 switch (count($range_options)) {
3702 case 0:
3703 trigger_error(Ak::t('Range unspecified. Specify the "within", "maximum", "minimum, or "is" option.'), E_USER_ERROR);
3704 return false;
3705 break;
3706 case 1:
3707 $options = array_merge($default_options, $options);
3708 break;
3709 default:
3710 trigger_error(Ak::t('Too many range options specified. Choose only one.'), E_USER_ERROR);
3711 return false;
3712 break;
3716 switch ($option) {
3717 case 'within':
3718 case 'in':
3719 if(empty($option_value) || !is_array($option_value) || count($option_value) != 2 || !is_numeric($option_value[0]) || !is_numeric($option_value[1])){
3720 trigger_error(Ak::t('%option must be a Range (array(min, max))',array('%option',$option)), E_USER_ERROR);
3721 return false;
3723 $attribute_names = Ak::toArray($attribute_names);
3725 foreach ($attribute_names as $attribute_name){
3726 if((!empty($option['allow_null']) && !isset($this->$attribute_name)) || (Ak::size($this->$attribute_name)) < $option_value[0]){
3727 $this->addError($attribute_name, sprintf($options['too_short'], $option_value[0]));
3728 }elseif((!empty($option['allow_null']) && !isset($this->$attribute_name)) || (Ak::size($this->$attribute_name)) > $option_value[1]){
3729 $this->addError($attribute_name, sprintf($options['too_long'], $option_value[1]));
3732 break;
3734 case 'is':
3735 case 'minimum':
3736 case 'maximum':
3738 if(empty($option_value) || !is_numeric($option_value) || $option_value <= 0){
3739 trigger_error(Ak::t('%option must be a nonnegative Integer',array('%option',$option_value)), E_USER_ERROR);
3740 return false;
3743 // Declare different validations per option.
3744 $validity_checks = array('is' => "==", 'minimum' => ">=", 'maximum' => "<=");
3745 $message_options = array('is' => 'wrong_length', 'minimum' => 'too_short', 'maximum' => 'too_long');
3747 $message = sprintf(!empty($options['message']) ? $options['message'] : $options[$message_options[$option]],$option_value);
3749 $attribute_names = Ak::toArray($attribute_names);
3750 foreach ($attribute_names as $attribute_name){
3751 if((!$options['allow_null'] && !isset($this->$attribute_name)) ||
3752 eval("return !(".Ak::size(@$this->$attribute_name)." {$validity_checks[$option]} $option_value);")){
3753 $this->addError($attribute_name, $message);
3756 break;
3757 default:
3758 break;
3761 return true;
3764 function validatesSizeOf($attribute_names, $options = array())
3766 return validatesLengthOf($attribute_names, $options);
3770 * Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
3771 * can be named "davidhh".
3773 * class Person extends ActiveRecord
3775 * function validate()
3777 * $this->validatesUniquenessOf('passport_number');
3778 * $this->validatesUniquenessOf('user_name', array('scope' => "account_id"));
3782 * It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
3783 * making sure that a teacher can only be on the schedule once per semester for a particular class.
3785 * class TeacherSchedule extends ActiveRecord
3787 * function validate()
3789 * $this->validatesUniquenessOf('passport_number');
3790 * $this->validatesUniquenessOf('teacher_id', array('scope' => array("semester_id", "class_id"));
3795 * When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified
3796 * attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
3798 * Configuration options:
3799 * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
3800 * <tt>scope</tt> - Ensures that the uniqueness is restricted to a condition of "scope = record.scope"
3801 * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default).
3802 * <tt>if</tt> - Specifies a method to call or a string to evaluate to determine if the validation should
3803 * occur (e.g. 'if' => 'allowValidation', or 'if' => '$this->signup_step > 2'). The
3804 * method, or string should return or evaluate to a true or false value.
3806 function validatesUniquenessOf($attribute_names, $options = array())
3808 $default_options = array('case_sensitive'=>true, 'message'=>'taken');
3809 $options = array_merge($default_options, $options);
3811 if(!empty($options['if'])){
3812 if(method_exists($this,$options['if'])){
3813 if($this->{$options['if']}() === false){
3814 return true;
3816 }else {
3817 eval('$__eval_result = ('.rtrim($options['if'],';').');');
3818 if(empty($__eval_result)){
3819 return true;
3824 $message = isset($this->_defaultErrorMessages[$options['message']]) ? $this->t($this->_defaultErrorMessages[$options['message']]) : $options['message'];
3825 unset($options['message']);
3827 foreach ((array)$attribute_names as $attribute_name){
3828 $value = isset($this->$attribute_name) ? $this->$attribute_name : null;
3830 if($value === null || ($options['case_sensitive'] || !$this->hasColumn($attribute_name))){
3831 $condition_sql = $this->getTableName().'.'.$attribute_name.' '.$this->getAttributeCondition($value);
3832 $condition_params = array($value);
3833 }else{
3834 $condition_sql = 'LOWER('.$this->getTableName().'.'.$attribute_name.') '.$this->getAttributeCondition($value);
3835 $condition_params = array(is_array($value) ? array_map('utf8_strtolower',$value) : utf8_strtolower($value));
3838 if(!empty($options['scope'])){
3839 foreach ((array)$options['scope'] as $scope_item){
3840 $scope_value = $this->get($scope_item);
3841 $condition_sql .= ' AND '.$this->getTableName().'.'.$scope_item.' '.$this->getAttributeCondition($scope_value);
3842 $condition_params[] = $scope_value;
3846 if(!$this->isNewRecord()){
3847 $condition_sql .= ' AND '.$this->getTableName().'.'.$this->getPrimaryKey().' <> ?';
3848 $condition_params[] = $this->getId();
3850 array_unshift($condition_params,$condition_sql);
3851 if ($this->find('first', array('conditions' => $condition_params))){
3852 $this->addError($attribute_name, $message);
3860 * Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
3861 * provided.
3863 * <code>
3864 * class Person extends ActiveRecord
3866 * function validate()
3868 * $this->validatesFormatOf('email', "/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/");
3871 * </code>
3873 * A regular expression must be provided or else an exception will be raised.
3875 * There are some regular expressions bundled with the Akelos Framework.
3876 * You can override them by defining them as PHP constants (Ie. define('AK_EMAIL_REGULAR_EXPRESSION', '/^My custom email regex$/');). This must be done on your main configuration file.
3877 * This are predefined perl-like regular extensions.
3879 * * AK_NOT_EMPTY_REGULAR_EXPRESSION ---> /.+/
3880 * * AK_EMAIL_REGULAR_EXPRESSION ---> /^([a-z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-z0-9\-]+\.)+))([a-z]{2,4}|[0-9]{1,3})(\]?)$/i
3881 * * AK_NUMBER_REGULAR_EXPRESSION ---> /^[0-9]+$/
3882 * * AK_PHONE_REGULAR_EXPRESSION ---> /^([\+]?[(]?[\+]?[ ]?[0-9]{2,3}[)]?[ ]?)?[0-9 ()\-]{4,25}$/
3883 * * AK_DATE_REGULAR_EXPRESSION ---> /^(([0-9]{1,2}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{2,4})|([0-9]{2,4}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{1,2})){1}$/
3884 * * AK_IP4_REGULAR_EXPRESSION ---> /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/
3885 * * AK_POST_CODE_REGULAR_EXPRESSION ---> /^[0-9A-Za-z -]{2,7}$/
3887 * IMPORTANT: Predefined regular expressions may change in newer versions of the Framework, so is highly recommended to hardcode you own on regex on your validators.
3889 * Params:
3890 * <tt>$message</tt> - A custom error message (default is: "is invalid")
3891 * <tt>$regular_expression</tt> - The regular expression used to validate the format with (note: must be supplied!)
3893 function validatesFormatOf($attribute_names, $regular_expression, $message = 'invalid', $regex_function = 'preg_match')
3895 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3897 $attribute_names = Ak::toArray($attribute_names);
3898 foreach ($attribute_names as $attribute_name){
3899 if(!isset($this->$attribute_name) || !$regex_function($regular_expression, $this->$attribute_name)){
3900 $this->addError($attribute_name, $message);
3906 * Validates whether the value of the specified attribute is available in a particular array of elements.
3908 * class Person extends ActiveRecord
3910 * function validate()
3912 * $this->validatesInclusionOf('gender', array('male', 'female'), "woah! what are you then!??!!");
3913 * $this->validatesInclusionOf('age', range(0, 99));
3916 * Parameters:
3917 * <tt>$array_of_ possibilities</tt> - An array of available items
3918 * <tt>$message</tt> - Specifies a customer error message (default is: "is not included in the list")
3919 * <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)
3921 function validatesInclusionOf($attribute_names, $array_of_possibilities, $message = 'inclusion', $allow_null = false)
3923 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3925 $attribute_names = Ak::toArray($attribute_names);
3926 foreach ($attribute_names as $attribute_name){
3927 if($allow_null ? (@$this->$attribute_name != '' ? (!in_array($this->$attribute_name,$array_of_possibilities)) : @$this->$attribute_name === 0 ) : (isset($this->$attribute_name) ? !in_array(@$this->$attribute_name,$array_of_possibilities) : true )){
3928 $this->addError($attribute_name, $message);
3934 * Validates that the value of the specified attribute is not in a particular array of elements.
3936 * class Person extends ActiveRecord
3938 * function validate()
3940 * $this->validatesExclusionOf('username', array('admin', 'superuser'), "You don't belong here");
3941 * $this->validatesExclusionOf('age', range(30,60), "This site is only for under 30 and over 60");
3945 * Parameters:
3946 * <tt>$array_of_possibilities</tt> - An array of items that the value shouldn't be part of
3947 * <tt>$message</tt> - Specifies a customer error message (default is: "is reserved")
3948 * <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)
3950 function validatesExclusionOf($attribute_names, $array_of_possibilities, $message = 'exclusion', $allow_null = false)
3952 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3954 $attribute_names = Ak::toArray($attribute_names);
3955 foreach ($attribute_names as $attribute_name){
3957 if($allow_null ? (!empty($this->$attribute_name) ? (in_array(@$this->$attribute_name,$array_of_possibilities)) : false ) : (isset($this->$attribute_name) ? in_array(@$this->$attribute_name,$array_of_possibilities) : true )){
3958 $this->addError($attribute_name, $message);
3967 * Validates whether the value of the specified attribute is numeric.
3969 * class Person extends ActiveRecord
3971 * function validate()
3973 * $this->validatesNumericalityOf('value');
3977 * Parameters:
3978 * <tt>$message</tt> - A custom error message (default is: "is not a number")
3979 * <tt>$only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
3980 * <tt>$allow_null</tt> Skip validation if attribute is null (default is false).
3982 function validatesNumericalityOf($attribute_names, $message = 'not_a_number', $only_integer = false, $allow_null = false)
3984 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
3986 $attribute_names = Ak::toArray($attribute_names);
3987 foreach ($attribute_names as $attribute_name){
3988 if (isset($this->$attribute_name)){
3989 $value = $this->$attribute_name;
3990 if ($only_integer){
3991 $is_int = is_numeric($value) && (int)$value == $value;
3992 $has_error = !$is_int;
3993 }else{
3994 $has_error = !is_numeric($value);
3996 }else{
3997 $has_error = $allow_null ? false : true;
4000 if ($has_error){
4001 $this->addError($attribute_name, $message);
4009 * Returns true if no errors were added otherwise false.
4011 function isValid()
4013 $this->clearErrors();
4014 if($this->beforeValidation() && $this->notifyObservers('beforeValidation')){
4017 if($this->_set_default_attribute_values_automatically){
4018 //$this->_setDefaultAttributeValuesAutomatically();
4021 $this->validate();
4023 if($this->_automated_validators_enabled){
4024 //$this->_runAutomatedValidators();
4027 $this->afterValidation();
4028 $this->notifyObservers('afterValidation');
4030 if ($this->isNewRecord()){
4031 if($this->beforeValidationOnCreate()){
4032 $this->notifyObservers('beforeValidationOnCreate');
4033 $this->validateOnCreate();
4034 $this->afterValidationOnCreate();
4035 $this->notifyObservers('afterValidationOnCreate');
4037 }else{
4038 if($this->beforeValidationOnUpdate()){
4039 $this->notifyObservers('beforeValidationOnUpdate');
4040 $this->validateOnUpdate();
4041 $this->afterValidationOnUpdate();
4042 $this->notifyObservers('afterValidationOnUpdate');
4047 return !$this->hasErrors();
4051 * By default the Active Record will validate for the maximum length for database columns. You can
4052 * disable the automated validators by setting $this->_automated_validators_enabled to false.
4053 * Specific validators are (for now):
4054 * $this->_automated_max_length_validator = true; // true by default, but you can set it to false on your model
4055 * $this->_automated_not_null_validator = false; // disabled by default
4057 * @access private
4059 function _runAutomatedValidators()
4061 foreach ($this->_columns as $column_name=>$column_settings){
4062 if($this->_automated_max_length_validator &&
4063 empty($column_settings['primaryKey']) &&
4064 !empty($this->$column_name) &&
4065 !empty($column_settings['maxLength']) && $column_settings['maxLength'] > 0 &&
4066 strlen($this->$column_name) > $column_settings['maxLength']){
4067 $this->addError($column_name, sprintf($this->_defaultErrorMessages['too_long'], $column_settings['maxLength']));
4068 }elseif($this->_automated_not_null_validator && empty($column_settings['primaryKey']) && !empty($column_settings['notNull']) && (!isset($this->$column_name) || is_null($this->$column_name))){
4069 $this->addError($column_name,'empty');
4075 * $this->_set_default_attribute_values_automatically = true; // This enables automated attribute setting from database definition
4077 * @access private
4079 function _setDefaultAttributeValuesAutomatically()
4081 foreach ($this->_columns as $column_name=>$column_settings){
4082 if(empty($column_settings['primaryKey']) && isset($column_settings['hasDefault']) && $column_settings['hasDefault'] && (!isset($this->$column_name) || is_null($this->$column_name))){
4083 if(empty($column_settings['defaultValue'])){
4084 if($column_settings['type'] == 'integer' && empty($column_settings['notNull'])){
4085 $this->$column_name = 0;
4086 }elseif(($column_settings['type'] == 'string' || $column_settings['type'] == 'text') && empty($column_settings['notNull'])){
4087 $this->$column_name = '';
4089 }else {
4090 $this->$column_name = $column_settings['defaultValue'];
4097 * Overwrite this method for validation checks on all saves and use addError($field, $message); for invalid attributes.
4099 function validate()
4104 * Overwrite this method for validation checks used only on creation.
4106 function validateOnCreate()
4111 * Overwrite this method for validation checks used only on updates.
4113 function validateOnUpdate()
4117 /*/Validators*/
4121 Observers
4122 ====================================================================
4123 See also: Callbacks.
4127 * $state store the state of this observable object
4129 * @access private
4131 var $_observable_state;
4134 * @access private
4136 function _instantiateDefaultObserver()
4138 $default_observer_name = ucfirst($this->getModelName().'Observer');
4139 if(class_exists($default_observer_name)){
4140 //$Observer =& new $default_observer_name($this);
4141 Ak::singleton($default_observer_name, $this);
4146 * Calls the $method using the reference to each
4147 * registered observer.
4148 * @return true (this is used internally for triggering observers on default callbacks)
4150 function notifyObservers ($method = null)
4152 $observers =& $this->getObservers();
4153 $observer_count = count($observers);
4155 if(!empty($method)){
4156 $this->setObservableState($method);
4159 $model_name = $this->getModelName();
4160 for ($i=0; $i<$observer_count; $i++) {
4161 if(in_array($model_name, $observers[$i]->_observing)){
4162 if(method_exists($observers[$i], $method)){
4163 $observers[$i]->$method($this);
4164 }else{
4165 $observers[$i]->update($this->getObservableState(), &$this);
4167 }else{
4168 $observers[$i]->update($this->getObservableState(), &$this);
4171 $this->setObservableState('');
4173 return true;
4177 function setObservableState($state_message)
4179 $this->_observable_state = $state_message;
4182 function getObservableState()
4184 return $this->_observable_state;
4188 * Register the reference to an object object
4189 * @return void
4191 function &addObserver(&$observer)
4193 static $observers, $registered_observers;
4194 $observer_class_name = get_class($observer);
4195 if(!isset($registered_observers[$observer_class_name]) && func_num_args() == 1){
4196 $observers[] =& $observer;
4197 $registered_observers[$observer_class_name] = count($observers);
4199 return $observers;
4203 * Register the reference to an object object
4204 * @return void
4206 function &getObservers()
4208 $observers =& $this->addObserver(&$this, false);
4209 return $observers;
4212 /*/Observers*/
4218 Error Handling
4219 ====================================================================
4220 See also: Validators.
4225 * Returns the Errors array that holds all information about attribute error messages.
4227 function getErrors()
4229 return $this->_errors;
4233 * Adds an error to the base object instead of any particular attribute. This is used
4234 * to report errors that doesn't tie to any specific attribute, but rather to the object
4235 * as a whole. These error messages doesn't get prepended with any field name when iterating
4236 * with yieldEachFullError, so they should be complete sentences.
4238 function addErrorToBase($message)
4240 $this->addError($this->getModelName(), $message);
4244 * Returns errors assigned to base object through addToBase according to the normal rules of getErrorsOn($attribute).
4246 function getBaseErrors()
4248 $errors = $this->getErrors();
4249 return (array)@$errors[$this->getModelName()];
4254 * Adds an error message ($message) to the ($attribute), which will be returned on a call to <tt>getErrorsOn($attribute)</tt>
4255 * for the same attribute and ensure that this error object returns false when asked if <tt>hasErrors</tt>. More than one
4256 * error can be added to the same $attribute in which case an array will be returned on a call to <tt>getErrorsOn($attribute)</tt>.
4257 * If no $message is supplied, "invalid" is assumed.
4259 function addError($attribute, $message = 'invalid')
4261 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
4262 $this->_errors[$attribute][] = $message;
4266 * Will add an error message to each of the attributes in $attributes that is empty.
4268 function addErrorOnEmpty($attribute_names, $message = 'empty')
4270 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
4271 $attribute_names = Ak::toArray($attribute_names);
4272 foreach ($attribute_names as $attribute){
4273 if(empty($this->$attribute)){
4274 $this->addError($attribute, $message);
4280 * Will add an error message to each of the attributes in $attributes that is blank (using $this->isBlank).
4282 function addErrorOnBlank($attribute_names, $message = 'blank')
4284 $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
4285 $attribute_names = Ak::toArray($attribute_names);
4286 foreach ($attribute_names as $attribute){
4287 if($this->isBlank(@$this->$attribute)){
4288 $this->addError($attribute, $message);
4294 * Will add an error message to each of the attributes in $attributes that has a length outside of the passed boundary $range.
4295 * If the length is above the boundary, the too_long_message message will be used. If below, the too_short_message.
4297 function addErrorOnBoundaryBreaking($attribute_names, $range_begin, $range_end, $too_long_message = 'too_long', $too_short_message = 'too_short')
4299 $too_long_message = isset($this->_defaultErrorMessages[$too_long_message]) ? $this->_defaultErrorMessages[$too_long_message] : $too_long_message;
4300 $too_short_message = isset($this->_defaultErrorMessages[$too_short_message]) ? $this->_defaultErrorMessages[$too_short_message] : $too_short_message;
4302 $attribute_names = Ak::toArray($attribute_names);
4303 foreach ($attribute_names as $attribute){
4304 if(@$this->$attribute < $range_begin){
4305 $this->addError($attribute, $too_short_message);
4307 if(@$this->$attribute > $range_end){
4308 $this->addError($attribute, $too_long_message);
4314 function addErrorOnBoundryBreaking ($attributes, $range_begin, $range_end, $too_long_message = 'too_long', $too_short_message = 'too_short')
4316 $this->addErrorOnBoundaryBreaking($attributes, $range_begin, $range_end, $too_long_message, $too_short_message);
4320 * Returns true if the specified $attribute has errors associated with it.
4322 function isInvalid($attribute)
4324 return $this->getErrorsOn($attribute);
4328 * Returns false, if no errors are associated with the specified $attribute.
4329 * Returns the error message, if one error is associated with the specified $attribute.
4330 * Returns an array of error messages, if more than one error is associated with the specified $attribute.
4332 function getErrorsOn($attribute)
4334 if (empty($this->_errors[$attribute])){
4335 return false;
4336 }elseif (count($this->_errors[$attribute]) == 1){
4337 $k = array_keys($this->_errors[$attribute]);
4338 return $this->_errors[$attribute][$k[0]];
4339 }else{
4340 return $this->_errors[$attribute];
4346 * Yields each attribute and associated message per error added.
4348 function yieldEachError()
4350 foreach ($this->_errors as $errors){
4351 foreach ($errors as $error){
4352 $this->yieldError($error);
4357 function yieldError($message)
4359 $messages = is_array($message) ? $message : array($message);
4360 foreach ($messages as $message){
4361 echo "<div class='error'><p>$message</p></div>\n";
4367 * Yields each full error message added. So Person->addError("first_name", "can't be empty") will be returned
4368 * through iteration as "First name can't be empty".
4370 function yieldEachFullError()
4372 $full_messages = $this->getFullErrorMessages();
4373 foreach ($full_messages as $full_message){
4374 $this->yieldError($full_message);
4380 * Returns all the full error messages in an array.
4382 function getFullErrorMessages()
4384 $full_messages = array();
4386 foreach ($this->_errors as $attribute=>$errors){
4387 $full_messages[$attribute] = array();
4388 foreach ($errors as $error){
4389 $full_messages[$attribute][] = $this->t('%attribute_name %error', array(
4390 '%attribute_name'=>AkInflector::humanize($this->_delocalizeAttribute($attribute)),
4391 '%error'=>$error
4395 return $full_messages;
4399 * Returns true if no errors have been added.
4401 function hasErrors()
4403 return !empty($this->_errors);
4407 * Removes all the errors that have been added.
4409 function clearErrors()
4411 $this->_errors = array();
4415 * Returns the total number of errors added. Two errors added to the same attribute will be counted as such
4416 * with this as well.
4418 function countErrors()
4420 $error_count = 0;
4421 foreach ($this->_errors as $errors){
4422 $error_count = count($errors)+$error_count;
4425 return $error_count;
4429 function errorsToString($print = false)
4431 $result = "\n<div id='errors'>\n<ul class='error'>\n";
4432 foreach ($this->getFullErrorMessages() as $error){
4433 $result .= is_array($error) ? "<li class='error'>".join('</li><li class=\'error\'>',$error)."</li>\n" : "<li class='error'>$error</li>\n";
4435 $result .= "</ul>\n</div>\n";
4437 if($print){
4438 echo $result;
4440 return $result;
4443 /*/Error Handling*/
4448 Act as Behaviours
4449 ====================================================================
4450 See also: Acts as List, Acts as Tree, Acts as Nested Set.
4454 * actAs provides a method for extending Active Record models.
4456 * Example:
4457 * $this->actsAs('list', array('scope' => 'todo_list'));
4459 function actsAs($behaviour, $options = array())
4461 $class_name = $this->_getActAsClassName($behaviour);
4462 $underscored_place_holder = AkInflector::underscore($behaviour);
4463 $camelized_place_holder = AkInflector::camelize($underscored_place_holder);
4465 if($this->$underscored_place_holder =& $this->_getActAsInstance($class_name, $options)){
4466 $this->$camelized_place_holder =& $this->$underscored_place_holder;
4467 if($this->$underscored_place_holder->init($options)){
4468 $this->__ActsLikeAttributes[$underscored_place_holder] = $underscored_place_holder;
4474 * @access private
4476 function _getActAsClassName($behaviour)
4478 $class_name = AkInflector::camelize($behaviour);
4479 return file_exists(AK_LIB_DIR.DS.'AkActiveRecord'.DS.'AkActsAsBehaviours'.DS.'AkActsAs'.$class_name.'.php') && !class_exists('ActsAs'.$class_name) ?
4480 'AkActsAs'.$class_name : 'ActsAs'.$class_name;
4484 * @access private
4486 function &_getActAsInstance($class_name, $options)
4488 if(!class_exists($class_name)){
4489 if(substr($class_name,0,2) == 'Ak'){
4490 include_once(AK_LIB_DIR.DS.'AkActiveRecord'.DS.'AkActsAsBehaviours'.DS.$class_name.'.php');
4491 }else{
4492 include_once(AK_APP_PLUGINS_DIR.DS.AkInflector::underscore($class_name).DS.'lib'.DS.$class_name.'.php');
4495 if(!class_exists($class_name)){
4496 trigger_error(Ak::t('The class %class used for handling an "act_as %class" does not exist',array('%class'=>$class_name)), E_USER_ERROR);
4497 $false = false;
4498 return $false;
4499 }else{
4500 $ActAsInstance =& new $class_name($this, $options);
4501 return $ActAsInstance;
4506 * @access private
4508 function _loadActAsBehaviours()
4510 $this->act_as = !empty($this->acts_as) ? $this->acts_as : (empty($this->act_as) ? false : $this->act_as);
4511 if(!empty($this->act_as)){
4512 if(is_string($this->act_as)){
4513 $this->act_as = array_unique(array_diff(array_map('trim',explode(',',$this->act_as.',')), array('')));
4514 foreach ($this->act_as as $type){
4515 $this->actsAs($type);
4517 }elseif (is_array($this->act_as)){
4518 foreach ($this->act_as as $type=>$options){
4519 $this->actsAs($type, $options);
4526 * Returns a comma separated list of possible acts like (active record, nested set, list)....
4528 function actsLike()
4530 $result = 'active record';
4531 foreach ($this->__ActsLikeAttributes as $type){
4532 if(!empty($this->$type) && is_object($this->$type) && method_exists($this->{$type}, 'getType')){
4533 $result .= ','.$this->{$type}->getType();
4536 return $result;
4539 /*/Act as Behaviours*/
4542 Debugging
4543 ====================================================================
4547 function dbug()
4549 if(!$this->isConnected()){
4550 $this->setConnection();
4552 $this->_db->connection->debug = $this->_db->connection->debug ? false : true;
4553 $this->db_debug =& $this->_db->connection->debug;
4556 function toString($print = false)
4558 $result = '';
4559 if(!AK_CLI || (AK_ENVIRONMENT == 'testing' && !AK_CLI)){
4560 $result = "<h2>Details for ".AkInflector::humanize(AkInflector::underscore($this->getModelName()))." with ".$this->getPrimaryKey()." ".$this->getId()."</h2>\n<dl>\n";
4561 foreach ($this->getColumnNames() as $column=>$caption){
4562 $result .= "<dt>$caption</dt>\n<dd>".$this->getAttribute($column)."</dd>\n";
4564 $result .= "</dl>\n<hr />";
4565 if($print){
4566 echo $result;
4568 }elseif(AK_ENVIRONMENT == 'development'){
4569 $result = "\n".
4570 str_replace("\n"," ",var_export($this->getAttributes(),true));
4571 $result .= "\n";
4572 echo $result;
4573 return '';
4574 }elseif (AK_CLI){
4575 $result = "\n-------\n Details for ".AkInflector::humanize(AkInflector::underscore($this->getModelName()))." with ".$this->getPrimaryKey()." ".$this->getId()." ==\n\n/==\n";
4576 foreach ($this->getColumnNames() as $column=>$caption){
4577 $result .= "\t * $caption: ".$this->getAttribute($column)."\n";
4579 $result .= "\n\n-------\n";
4580 if($print){
4581 echo $result;
4584 return $result;
4587 function dbugging($trace_this_on_debug_mode = null)
4589 if(!empty($this->_db->debug) && !empty($trace_this_on_debug_mode)){
4590 $message = !is_scalar($trace_this_on_debug_mode) ? var_export($trace_this_on_debug_mode, true) : (string)$trace_this_on_debug_mode;
4591 Ak::trace($message);
4593 return !empty($this->_db->debug);
4598 function debug ($data = 'active_record_class', $_functions=0)
4600 if(!AK_DEBUG && !AK_DEV_MODE){
4601 return;
4604 $data = $data == 'active_record_class' ? (AK_PHP5 ? clone($this) : $this) : $data;
4606 if($_functions!=0) {
4607 $sf=1;
4608 } else {
4609 $sf=0 ;
4612 if (isset ($data)) {
4613 if (is_array($data) || is_object($data)) {
4615 if (count ($data)) {
4616 echo AK_CLI ? "/--\n" : "<ol>\n";
4617 while (list ($key,$value) = each ($data)) {
4618 if($key{0} == '_'){
4619 continue;
4621 $type=gettype($value);
4622 if ($type=="array") {
4623 AK_CLI ? printf ("\t* (%s) %s:\n",$type, $key) :
4624 printf ("<li>(%s) <b>%s</b>:\n",$type, $key);
4625 ob_start();
4626 Ak::debug ($value,$sf);
4627 $lines = explode("\n",ob_get_clean()."\n");
4628 foreach ($lines as $line){
4629 echo "\t".$line."\n";
4631 }elseif($type == "object"){
4632 if(method_exists($value,'hasColumn') && $value->hasColumn($key)){
4633 $value->toString(true);
4634 AK_CLI ? printf ("\t* (%s) %s:\n",$type, $key) :
4635 printf ("<li>(%s) <b>%s</b>:\n",$type, $key);
4636 ob_start();
4637 Ak::debug ($value,$sf);
4638 $lines = explode("\n",ob_get_clean()."\n");
4639 foreach ($lines as $line){
4640 echo "\t".$line."\n";
4643 }elseif (eregi ("function", $type)) {
4644 if ($sf) {
4645 AK_CLI ? printf ("\t* (%s) %s:\n",$type, $key, $value) :
4646 printf ("<li>(%s) <b>%s</b> </li>\n",$type, $key, $value);
4648 } else {
4649 if (!$value) {
4650 $value="(none)";
4652 AK_CLI ? printf ("\t* (%s) %s = %s\n",$type, $key, $value) :
4653 printf ("<li>(%s) <b>%s</b> = %s</li>\n",$type, $key, $value);
4656 echo AK_CLI ? "\n--/\n" : "</ol>fin.\n";
4657 } else {
4658 echo "(empty)";
4664 /*/Debugging*/
4669 Utilities
4670 ====================================================================
4673 * Selects and filters a search result to include only specified columns
4675 * $people_for_select = $People->select($People->find(),'name','email');
4677 * Now $people_for_select will hold an array with
4678 * array (
4679 * array ('name' => 'Jose','email' => 'jose@example.com'),
4680 * array ('name' => 'Alicia','email' => 'alicia@example.com'),
4681 * array ('name' => 'Hilario','email' => 'hilario@example.com'),
4682 * array ('name' => 'Bermi','email' => 'bermi@example.com')
4683 * );
4685 function select(&$source_array)
4687 $resulting_array = array();
4688 if(!empty($source_array) && is_array($source_array) && func_num_args() > 1) {
4689 (array)$args = array_filter(array_slice(func_get_args(),1),array($this,'hasColumn'));
4690 foreach ($source_array as $source_item){
4691 $item_fields = array();
4692 foreach ($args as $arg){
4693 $item_fields[$arg] =& $source_item->get($arg);
4695 $resulting_array[] =& $item_fields;
4698 return $resulting_array;
4703 * Collect is a function for selecting items from double depth array
4704 * like the ones returned by the AkActiveRecord. This comes useful when you just need some
4705 * fields for generating tables, select lists with only desired fields.
4707 * $people_for_select = Ak::select($People->find(),'id','email');
4709 * Returns something like:
4710 * array (
4711 * array ('10' => 'jose@example.com'),
4712 * array ('15' => 'alicia@example.com'),
4713 * array ('16' => 'hilario@example.com'),
4714 * array ('18' => 'bermi@example.com')
4715 * );
4717 function collect(&$source_array, $key_index, $value_index)
4719 $resulting_array = array();
4720 if(!empty($source_array) && is_array($source_array)) {
4721 foreach ($source_array as $source_item){
4722 $resulting_array[$source_item->get($key_index)] = $source_item->get($value_index);
4725 return $resulting_array;
4728 function toJson()
4730 return Ak::toJson($this->getAttributes());
4734 * converts to yaml-strings
4736 * examples:
4737 * User::toYaml($users->find('all'));
4738 * $Bermi->toYaml();
4740 * @param array of ActiveRecords[optional] $data
4742 function toYaml($data = null)
4744 return Ak::convert('active_record', 'yaml', empty($data) ? $this : $data);
4749 * Parses an special formated array as a list of keys and values
4751 * This function generates an array with values and keys from an array with numeric keys.
4753 * This allows to parse an array to a function in the following manner.
4754 * create('first_name->', 'Bermi', 'last_name->', 'Ferrer');
4755 * //Previous code will be the same that
4756 * create(array('first_name'=>'Bermi', 'last_name'=> 'Ferrer'));
4758 * Use this syntax only for quick testings, not for production environments. If the number of arguments varies, the result might be unpredictable.
4760 * This function syntax is disabled by default. You need to define('AK_ENABLE_AKELOS_ARGS', true)
4761 * if you need this functionality.
4763 * @deprecated
4765 function parseAkelosArgs(&$args)
4767 if(!AK_ENABLE_AKELOS_ARGS){
4768 $this->_castDateParametersFromDateHelper_($args);
4769 return ;
4771 $k = array_keys($args);
4772 if(isset($k[1]) && substr($args[$k[0]],-1) == '>'){
4773 $size = sizeOf($k);
4774 $params = array();
4775 for($i = 0; $i < $size; $i++ ) {
4776 $v = $args[$k[$i]];
4777 if(!isset($key) && is_string($args[$k[$i]]) && substr($v,-1) == '>'){
4778 $key = rtrim($v, '=-> ');
4779 }elseif(isset($key)) {
4780 $params[$key] = $v;
4781 unset($key);
4782 }else{
4783 $params[$k[$i]] = $v;
4786 if(!empty($params)){
4787 $args = $params;
4790 $this->_castDateParametersFromDateHelper_($args);
4793 * Gets an array from a string.
4795 * Acts like Php explode() function but uses any of this as valid separators ' AND ',' and ',' + ',' ',',',';'
4797 function getArrayFromAkString($string)
4799 if(is_array($string)){
4800 return $string;
4802 $string = str_replace(array(' AND ',' and ',' + ',' ',',',';'),array('|','|','|','','|','|'),trim($string));
4803 return strstr($string,'|') ? explode('|', $string) : array($string);
4805 /*/Utilities*/
4808 function getAttributeCondition($argument)
4810 if(is_array($argument)){
4811 return 'IN (?)';
4812 }elseif (is_null($argument)){
4813 return 'IS ?';
4814 }else{
4815 return '= ?';
4821 Calculations
4822 ====================================================================
4826 * @access private
4828 var $_calculation_options = array('conditions', 'joins', 'order', 'select', 'group', 'having', 'distinct', 'limit', 'offset');
4831 * Count operates using three different approaches.
4833 * * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
4834 * * Count by conditions or joins
4835 * * Count using options will find the row count matched by the options used.
4837 * The last approach, count using options, accepts an option hash as the only parameter. The options are:
4839 * * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array("user_name = ?", $username ). See conditions in the intro.
4840 * * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
4841 * * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
4842 * * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
4843 * * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join.
4844 * * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
4846 * Examples for counting all:
4847 * $Person->count(); // returns the total count of all people
4849 * Examples for count by +conditions+ and +joins+ (this has been deprecated):
4850 * $Person->count("age > 26"); // returns the number of people older than 26
4851 * $Person->find("age > 26 AND job.salary > 60000", "LEFT JOIN jobs on jobs.person_id = ".$Person->id); // returns the total number of rows matching the conditions and joins fetched by SELECT COUNT(*).
4853 * Examples for count with options:
4854 * $Person->count('conditions' => "age > 26");
4855 * $Person->count('conditions' => "age > 26 AND job.salary > 60000", 'joins' => "LEFT JOIN jobs on jobs.person_id = $Person->id"); // finds the number of rows matching the conditions and joins.
4856 * $Person->count('id', 'conditions' => "age > 26"); // Performs a COUNT(id)
4857 * $Person->count('all', 'conditions' => "age > 26"); // Performs a COUNT(*) ('all' is an alias for '*')
4859 * Note: $Person->count('all') will not work because it will use 'all' as the condition. Use $Person->count() instead.
4861 function count()
4863 $args = func_get_args();
4864 list($column_name, $options) = $this->_constructCountOptionsFromLegacyArgs($args);
4865 return $this->calculate('count', $column_name, $options);
4869 * Calculates average value on a given column. The value is returned as a float. See #calculate for examples with options.
4871 * $Person->average('age');
4873 function average($column_name, $options = array())
4875 return $this->calculate('avg', $column_name, $options);
4879 * Calculates the minimum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.
4881 * $Person->minimum('age');
4883 function minimum($column_name, $options = array())
4885 return $this->calculate('min', $column_name, $options);
4889 * Calculates the maximum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.
4891 * $Person->maximum('age');
4893 function maximum($column_name, $options = array())
4895 return $this->calculate('max', $column_name, $options);
4899 * Calculates the sum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.
4901 * $Person->sum('age');
4903 function sum($column_name, $options = array())
4905 return $this->calculate('sum', $column_name, $options);
4909 * This calculates aggregate values in the given column: Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
4910 * Options such as 'conditions', 'order', 'group', 'having', and 'joins' can be passed to customize the query.
4912 * There are two basic forms of output:
4913 * * Single aggregate value: The single value is type cast to integer for COUNT, float for AVG, and the given column's type for everything else.
4914 * * Grouped values: This returns an ordered hash of the values and groups them by the 'group' option. It takes a column name.
4916 * $values = $Person->maximum('age', array('group' => 'last_name'));
4917 * echo $values["Drake"]
4918 * => 43
4920 * Options:
4921 * * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array( "user_name = ?", username ). See conditions in the intro.
4922 * * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
4923 * The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
4924 * * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
4925 * * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
4926 * * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join.
4927 * * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
4929 * Examples:
4930 * $Person->calculate('count', 'all'); // The same as $Person->count();
4931 * $Person->average('age'); // SELECT AVG(age) FROM people...
4932 * $Person->minimum('age', array('conditions' => array('last_name != ?', 'Drake'))); // Selects the minimum age for everyone with a last name other than 'Drake'
4933 * $Person->minimum('age', array('having' => 'min(age) > 17', 'group' => 'last'_name)); // Selects the minimum age for any family without any minors
4935 function calculate($operation, $column_name, $options = array())
4937 $this->_validateCalculationOptions($options);
4938 $column_name = empty($options['select']) ? $column_name : $options['select'];
4939 $column_name = $column_name == 'all' ? '*' : $column_name;
4940 $column = $this->_getColumnFor($column_name);
4941 if (!empty($options['group'])){
4942 return $this->_executeGroupedCalculation($operation, $column_name, $column, $options);
4943 }else{
4944 return $this->_executeSimpleCalculation($operation, $column_name, $column, $options);
4947 return 0;
4951 * @access private
4953 function _constructCountOptionsFromLegacyArgs($args)
4955 $options = array();
4956 $column_name = 'all';
4959 We need to handle
4960 count()
4961 count(options=array())
4962 count($column_name='all', $options=array())
4963 count($conditions=null, $joins=null)
4965 if(count($args) > 2){
4966 trigger_error(Ak::t("Unexpected parameters passed to count(\$options=array())", E_USER_ERROR));
4967 }elseif(count($args) > 0){
4968 if(!empty($args[0]) && is_array($args[0])){
4969 $options = $args[0];
4970 }elseif(!empty($args[1]) && is_array($args[1])){
4971 $column_name = array_shift($args);
4972 $options = array_shift($args);
4973 }else{
4974 $options = array('conditions' => $args[0]);
4975 if(!empty($args[1])){
4976 $options = array_merge($options, array('joins' => $args[1]));
4980 return array($column_name, $options);
4985 * @access private
4987 function _constructCalculationSql($operation, $column_name, $options)
4989 $operation = strtolower($operation);
4990 $aggregate_alias = $this->_getColumnAliasFor($operation, $column_name);
4991 $use_workaround = $operation == 'count' && !empty($options['distinct']) && $this->_getDatabaseType() == 'sqlite';
4993 $sql = $use_workaround ?
4994 "SELECT COUNT(*) AS $aggregate_alias" : // A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
4995 "SELECT $operation(".(empty($options['distinct'])?'':'DISTINCT ')."$column_name) AS $aggregate_alias";
4998 $sql .= empty($options['group']) ? '' : ", {$options['group_field']} AS {$options['group_alias']}";
4999 $sql .= $use_workaround ? " FROM (SELECT DISTINCT {$column_name}" : '';
5000 $sql .= " FROM ".$this->getTableName()." ";
5002 $sql .= empty($options['joins']) ? '' : " {$options['joins']} ";
5004 empty($options['conditions']) ? null : $this->addConditions($sql, $options['conditions']);
5006 if (!empty($options['group'])){
5007 $sql .= " GROUP BY {$options['group_field']} ";
5008 $sql .= empty($options['having']) ? '' : " HAVING {$options['having']} ";
5011 $sql .= empty($options['order']) ? '' : " ORDER BY {$options['order']} ";
5012 $this->_db->addLimitAndOffset($sql, $options);
5013 $sql .= $use_workaround ? ')' : '';
5014 return $sql;
5019 * @access private
5021 function _executeSimpleCalculation($operation, $column_name, $column, $options)
5023 $value = $this->_db->selectValue($this->_constructCalculationSql($operation, $column_name, $options));
5024 return $this->_typeCastCalculatedValue($value, $column, $operation);
5028 * @access private
5030 function _executeGroupedCalculation($operation, $column_name, $column, $options)
5032 $group_field = $options['group'];
5033 $group_alias = $this->_getColumnAliasFor($group_field);
5034 $group_column = $this->_getColumnFor($group_field);
5035 $options = array_merge(array('group_field' => $group_field, 'group_alias' => $group_alias),$options);
5036 $sql = $this->_constructCalculationSql($operation, $column_name, $options);
5037 $calculated_data = $this->_db->select($sql);
5038 $aggregate_alias = $this->_getColumnAliasFor($operation, $column_name);
5040 $all = array();
5041 foreach ($calculated_data as $row){
5042 $key = $this->_typeCastCalculatedValue($row[$group_alias], $group_column);
5043 $all[$key] = $this->_typeCastCalculatedValue($row[$aggregate_alias], $column, $operation);
5045 return $all;
5049 * @access private
5051 function _validateCalculationOptions($options = array())
5053 $invalid_options = array_diff(array_keys($options),$this->_calculation_options);
5054 if(!empty($invalid_options)){
5055 trigger_error(Ak::t('%options are not valid calculation options.', array('%options'=>join(', ',$invalid_options))), E_USER_ERROR);
5060 * Converts a given key to the value that the database adapter returns as
5061 * as a usable column name.
5062 * users.id #=> users_id
5063 * sum(id) #=> sum_id
5064 * count(distinct users.id) #=> count_distinct_users_id
5065 * count(*) #=> count_all
5067 * @access private
5069 function _getColumnAliasFor()
5071 $args = func_get_args();
5072 $keys = strtolower(join(' ',(!empty($args) ? (is_array($args[0]) ? $args[0] : $args) : array())));
5073 return preg_replace(array('/\*/','/\W+/','/^ +/','/ +$/','/ +/'),array('all',' ','','','_'), $keys);
5077 * @access private
5079 function _getColumnFor($field)
5081 $field_name = ltrim(substr($field,strpos($field,'.')),'.');
5082 if(in_array($field_name,$this->getColumnNames())){
5083 return $field_name;
5085 return $field;
5089 * @access private
5091 function _typeCastCalculatedValue($value, $column, $operation = null)
5093 $operation = strtolower($operation);
5094 if($operation == 'count'){
5095 return intval($value);
5096 }elseif ($operation == 'avg'){
5097 return floatval($value);
5098 }else{
5099 return empty($column) ? $value : AkActiveRecord::castAttributeFromDatabase($column, $value);
5103 /*/Calculations*/
5105 function hasBeenModified()
5107 return Ak::objectHasBeenModified($this);
5111 * Just freeze the attributes hash, such that associations are still accessible even on destroyed records.
5113 * @todo implement freeze correctly for its intended use
5115 function freeze()
5117 return $this->_freeze = true;
5120 function isFrozen()
5122 return !empty($this->_freeze);
5126 * Alias for getModelName()
5128 function getType()
5130 return $this->getModelName();
5133 function &objectCache()
5135 static $cache;
5136 $args =& func_get_args();
5137 if(count($args) == 2){
5138 if(!isset($cache[$args[0]])){
5139 $cache[$args[0]] =& $args[1];
5141 }elseif(!isset($cache[$args[0]])){
5142 return false;
5144 return $cache[$args[0]];
5149 Connection adapters
5150 ====================================================================
5151 Right now Akelos uses phpAdodb for bd abstraction. This are functionalities not
5152 provided in phpAdodb and that will move to a separated driver for each db
5153 engine in a future
5155 function _extractValueFromDefault($default)
5157 if($this->_getDatabaseType() == 'postgre'){
5158 if(preg_match("/^'(.*)'::/", $default, $match)){
5159 return $match[1];
5161 // a postgre HACK; we dont know the column-type here
5162 if ($default=='true') {
5163 return true;
5165 if ($default=='false') {
5166 return false;
5169 return $default;