PageRenderTime 80ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/AkActiveRecord.php

http://akelosframework.googlecode.com/
PHP | 5018 lines | 3286 code | 556 blank | 1176 comment | 580 complexity | 47070d1ff38415bf2a32501b1638610c MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. // +----------------------------------------------------------------------+
  4. // | Akelos Framework - http://www.akelos.org |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 2002-2006, Akelos Media, S.L. & Bermi Ferrer Martinez |
  7. // | Released under the GNU Lesser General Public License, see LICENSE.txt|
  8. // +----------------------------------------------------------------------+
  9. /**
  10. * @package AkelosFramework
  11. * @subpackage AkActiveRecord
  12. * @author Bermi Ferrer <bermi a.t akelos c.om> 2004 - 2007
  13. * @author Kaste 2007
  14. * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
  15. * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
  16. */
  17. require_once(AK_LIB_DIR.DS.'AkActiveRecord'.DS.'AkAssociatedActiveRecord.php');
  18. // Akelos args is a short way to call functions that is only intended for fast prototyping
  19. defined('AK_ENABLE_AKELOS_ARGS') ? null : define('AK_ENABLE_AKELOS_ARGS', false);
  20. // Use setColumnName if available when using set('column_name', $value);
  21. defined('AK_ACTIVE_RECORD_INTERNATIONALIZE_MODELS_BY_DEFAULT') ? null : define('AK_ACTIVE_RECORD_INTERNATIONALIZE_MODELS_BY_DEFAULT', true);
  22. defined('AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS') ? null : define('AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS', true);
  23. defined('AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS') ? null : define('AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS', true);
  24. defined('AK_ACTIVE_RECORD_ENABLE_PERSISTENCE') ? null : define('AK_ACTIVE_RECORD_ENABLE_PERSISTENCE', AK_ENVIRONMENT != 'testing');
  25. defined('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA') ? null : define('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA', AK_ACTIVE_RECORD_ENABLE_PERSISTENCE && AK_ENVIRONMENT != 'development');
  26. defined('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE') ? null : define('AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE', 300);
  27. defined('AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES') ? null : define('AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES', true);
  28. defined('AK_ACTIVE_RECORD_SKIP_SETTING_ACTIVE_RECORD_DEFAULTS') ? null : define('AK_ACTIVE_RECORD_SKIP_SETTING_ACTIVE_RECORD_DEFAULTS', false);
  29. defined('AK_NOT_EMPTY_REGULAR_EXPRESSION') ? null : define('AK_NOT_EMPTY_REGULAR_EXPRESSION','/.+/');
  30. 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");
  31. defined('AK_NUMBER_REGULAR_EXPRESSION') ? null : define('AK_NUMBER_REGULAR_EXPRESSION',"/^[0-9]+$/");
  32. defined('AK_PHONE_REGULAR_EXPRESSION') ? null : define('AK_PHONE_REGULAR_EXPRESSION',"/^([\+]?[(]?[\+]?[ ]?[0-9]{2,3}[)]?[ ]?)?[0-9 ()\-]{4,25}$/");
  33. 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}$/");
  34. 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])$/");
  35. defined('AK_POST_CODE_REGULAR_EXPRESSION') ? null : define('AK_POST_CODE_REGULAR_EXPRESSION',"/^[0-9A-Za-z -]{2,9}$/");
  36. // Forces loading database schema on every call
  37. if(AK_DEV_MODE && isset($_SESSION['__activeRecordColumnsSettingsCache'])){
  38. unset($_SESSION['__activeRecordColumnsSettingsCache']);
  39. }
  40. ak_compat('array_combine');
  41. /**
  42. * Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with
  43. * which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
  44. * is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
  45. * database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
  46. *
  47. * See the mapping rules in table_name and the full example in README.txt for more insight.
  48. *
  49. * == Creation ==
  50. *
  51. * 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
  52. * you're receiving the data from somewhere else, like a HTTP request. It works like this:
  53. *
  54. * $user = new User(array('name' => 'David', 'occupation' => 'Code Artist'));
  55. * echo $user->name; // Will print "David"
  56. *
  57. * You can also use a parameter list initialization.:
  58. *
  59. * $user = new User('name->', 'David', 'occupation->', 'Code Artist');
  60. *
  61. * And of course you can just create a bare object and specify the attributes after the fact:
  62. *
  63. * $user = new User();
  64. * $user->name = 'David';
  65. * $user->occupation = 'Code Artist';
  66. *
  67. * == Conditions ==
  68. *
  69. * Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement.
  70. * The array form is to be used when the condition input is tainted and requires sanitization. The string form can
  71. * be used for statements that doesn't involve tainted data. Examples:
  72. *
  73. * class User extends AkActiveRecord
  74. * {
  75. * function authenticateUnsafely($user_name, $password)
  76. * {
  77. * return findFirst("user_name = '$user_name' AND password = '$password'");
  78. * }
  79. *
  80. * function authenticateSafely($user_name, $password)
  81. * {
  82. * return findFirst("user_name = ? AND password = ?", $user_name, $password);
  83. * }
  84. * }
  85. *
  86. * The <tt>authenticateUnsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
  87. * attacks if the <tt>$user_name</tt> and <tt>$password</tt> parameters come directly from a HTTP request. The <tt>authenticateSafely</tt> method,
  88. * 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
  89. * an attacker can't escape the query and fake the login (or worse).
  90. *
  91. * When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
  92. * question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
  93. * the question marks with symbols and supplying a hash with values for the matching symbol keys:
  94. *
  95. * $Company->findFirst(
  96. * "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
  97. * array(':id' => 3, ':name' => "37signals", ':division' => "First", ':accounting_date' => '2005-01-01')
  98. * );
  99. *
  100. * == Accessing attributes before they have been type casted ==
  101. *
  102. * Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first.
  103. * That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model
  104. * has a balance attribute, you can call $Account->balance_before_type_cast or $Account->id_before_type_cast.
  105. *
  106. * This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
  107. * the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn't what you
  108. * want.
  109. *
  110. * == Saving arrays, hashes, and other non-mappable objects in text columns ==
  111. *
  112. * Active Record can serialize any object in text columns. To do so, you must specify this with by setting the attribute serialize whith
  113. * a comma separated list of columns or an array.
  114. * This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
  115. *
  116. * class User extends AkActiveRecord
  117. * {
  118. * var $serialize = 'preferences';
  119. * }
  120. *
  121. * $User = new User(array('preferences'=>array("background" => "black", "display" => 'large')));
  122. * $User->find($user_id);
  123. * $User->preferences // array("background" => "black", "display" => 'large')
  124. *
  125. * == Single table inheritance ==
  126. *
  127. * Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed
  128. * by overwriting <tt>AkActiveRecord->_inheritanceColumn</tt>). This means that an inheritance looking like this:
  129. *
  130. * class Company extends AkActiveRecord{}
  131. * class Firm extends Company{}
  132. * class Client extends Company{}
  133. * class PriorityClient extends Client{}
  134. *
  135. * When you do $Firm->create('name =>', "akelos"), this record will be saved in the companies table with type = "Firm". You can then
  136. * fetch this row again using $Company->find('first', "name = '37signals'") and it will return a Firm object.
  137. *
  138. * 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
  139. * like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
  140. *
  141. * Note, all the attributes for all the cases are kept in the same table. Read more:
  142. * http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
  143. *
  144. * == Connection to multiple databases in different models ==
  145. *
  146. * Connections are usually created through AkActiveRecord->establishConnection and retrieved by AkActiveRecord->connection.
  147. * All classes inheriting from AkActiveRecord will use this connection. But you can also set a class-specific connection.
  148. * For example, if $Course is a AkActiveRecord, but resides in a different database you can just say $Course->establishConnection
  149. * and $Course and all its subclasses will use this connection instead.
  150. *
  151. * Active Records will automatically record creation and/or update timestamps of database objects
  152. * if fields of the names created_at/created_on or updated_at/updated_on are present.
  153. * Date only: created_on, updated_on
  154. * Date and time: created_at, updated_at
  155. *
  156. * This behavior can be turned off by setting <tt>$this->_recordTimestamps = false</tt>.
  157. */
  158. class AkActiveRecord extends AkAssociatedActiveRecord
  159. {
  160. //var $disableAutomatedAssociationLoading = true;
  161. var $_tableName;
  162. var $_db;
  163. var $_newRecord;
  164. var $_freeze;
  165. var $_dataDictionary;
  166. var $_primaryKey;
  167. var $_inheritanceColumn;
  168. var $_associations;
  169. var $_internationalize;
  170. var $_errors = array();
  171. var $_attributes = array();
  172. var $_protectedAttributes = array();
  173. var $_accessibleAttributes = array();
  174. var $_recordTimestamps = true;
  175. // Column description
  176. var $_columnNames = array();
  177. // Array of column objects for the table associated with this class.
  178. var $_columns = array();
  179. // Columns that can be edited/viewed
  180. var $_contentColumns = array();
  181. // Methods that will be dinamically loaded for the model (EXPERIMENTAL) This pretends to generate something similar to Ruby on Rails finders.
  182. // If you set array('findOneByUsernameAndPassword', 'findByCompany', 'findAllByExipringDate')
  183. // You'll get $User->findOneByUsernameAndPassword('admin', 'pass');
  184. var $_dynamicMethods = false;
  185. var $_combinedAttributes = array();
  186. var $_BlobQueryStack = null;
  187. var $_automated_max_length_validator = true;
  188. var $_automated_validators_enabled = true;
  189. var $_automated_not_null_validator = false;
  190. var $_set_default_attribute_values_automatically = true;
  191. // This is needed for enabling support for static active record instantation under php
  192. var $_activeRecordHasBeenInstantiated = true;
  193. var $__ActsLikeAttributes = array();
  194. var $__coreActsLikeAttributes = array('nested_set', 'list', 'tree');
  195. /**
  196. * Holds a hash with all the default error messages, such that they can be replaced by your own copy or localizations.
  197. */
  198. var $_defaultErrorMessages = array(
  199. 'inclusion' => "is not included in the list",
  200. 'exclusion' => "is reserved",
  201. 'invalid' => "is invalid",
  202. 'confirmation' => "doesn't match confirmation",
  203. 'accepted' => "must be accepted",
  204. 'empty' => "can't be empty",
  205. 'blank' => "can't be blank",
  206. 'too_long' => "is too long (max is %d characters)",
  207. 'too_short' => "is too short (min is %d characters)",
  208. 'wrong_length' => "is the wrong length (should be %d characters)",
  209. 'taken' => "has already been taken",
  210. 'not_a_number' => "is not a number"
  211. );
  212. var $__activeRecordObject = true;
  213. function __construct()
  214. {
  215. $attributes = (array)func_get_args();
  216. return $this->init($attributes);
  217. }
  218. function init($attributes = array())
  219. {
  220. AK_LOG_EVENTS ? ($this->Logger =& Ak::getLogger()) : null;
  221. $this->_internationalize = is_null($this->_internationalize) && AK_ACTIVE_RECORD_INTERNATIONALIZE_MODELS_BY_DEFAULT ? count($this->getAvaliableLocales()) > 1 : $this->_internationalize;
  222. @$this->_instatiateDefaultObserver();
  223. $this->setConnection();
  224. if(!empty($this->table_name)){
  225. $this->setTableName($this->table_name);
  226. }
  227. $this->_loadActAsBehaviours();
  228. if(!empty($this->combined_attributes)){
  229. foreach ($this->combined_attributes as $combined_attribute){
  230. $this->addCombinedAttributeConfiguration($combined_attribute);
  231. }
  232. }
  233. if(isset($attributes[0]) && is_array($attributes[0]) && count($attributes) === 1){
  234. $attributes = $attributes[0];
  235. $this->_newRecord = true;
  236. }
  237. // new AkActiveRecord(23); //Returns object with primary key 23
  238. if(isset($attributes[0]) && count($attributes) === 1 && $attributes[0] > 0){
  239. $record = $this->find($attributes[0]);
  240. if(!$record){
  241. return false;
  242. }else {
  243. $this->setAttributes($record->getAttributes(), true);
  244. }
  245. // This option is only used internally for loading found objects
  246. }elseif(isset($attributes[0]) && isset($attributes[1]) && $attributes[0] == 'attributes' && is_array($attributes[1])){
  247. foreach($attributes[1] as $k=>$v){
  248. $attributes[1][$k] = $this->castAttributeFromDatabase($k, $v);
  249. }
  250. $avoid_loading_associations = isset($attributes[1]['load_associations']) ? false : !empty($this->disableAutomatedAssociationLoading);
  251. $this->setAttributes($attributes[1], true);
  252. }else{
  253. $this->newRecord($attributes);
  254. }
  255. $this->_buildFinders();
  256. empty($avoid_loading_associations) ? $this->loadAssociations() : null;
  257. }
  258. function __destruct()
  259. {
  260. }
  261. /**
  262. * If this macro is used, only those attributed named in it will be accessible
  263. * for mass-assignment, such as new ModelName($attributes) and $this->attributes($attributes).
  264. * This is the more conservative choice for mass-assignment protection.
  265. * If you'd rather start from an all-open default and restrict attributes as needed,
  266. * have a look at AkActiveRecord::setProtectedAttributes().
  267. */
  268. function setAccessibleAttributes()
  269. {
  270. $args = func_get_args();
  271. $this->_accessibleAttributes = array_unique(array_merge((array)$this->_accessibleAttributes, $args));
  272. }
  273. /**
  274. * Attributes named in this macro are protected from mass-assignment, such as
  275. * new ModelName($attributes) and $this->attributes(attributes). Their assignment
  276. * will simply be ignored. Instead, you can use the direct writer methods to do assignment.
  277. * This is meant to protect sensitive attributes to be overwritten by URL/form hackers.
  278. *
  279. * Example:
  280. * <code>
  281. * class Customer extends AkActiveRecord
  282. * {
  283. * function Customer()
  284. * {
  285. * $this->setProtectedAttributes('credit_rating');
  286. * }
  287. * }
  288. *
  289. * $Customer = new Customer('name' => 'David', 'credit_rating' => 'Excellent');
  290. * $Customer->credit_rating // => null
  291. * $Customer->attributes(array('description' => 'Jolly fellow', 'credit_rating' => 'Superb'));
  292. * $Customer->credit_rating // => null
  293. *
  294. * $Customer->credit_rating = 'Average'
  295. * $Customer->credit_rating // => 'Average'
  296. * </code>
  297. */
  298. function setProtectedAttributes()
  299. {
  300. $args = func_get_args();
  301. $this->_protectedAttributes = array_unique(array_merge((array)$this->_protectedAttributes, $args));
  302. }
  303. /**
  304. * Returns true if a connection that?s accessible to this class have already been opened.
  305. */
  306. function isConnected()
  307. {
  308. return isset($this->_db);
  309. }
  310. /**
  311. * Returns the connection currently associated with the class. This can also be used to
  312. * "borrow" the connection to do database work unrelated to any of the specific Active Records.
  313. */
  314. function &getConnection()
  315. {
  316. return $this->_db;
  317. }
  318. /**
  319. * Set the connection for the class.
  320. */
  321. function setConnection($dns = null, $connection_id = null)
  322. {
  323. $this->_db =& Ak::db($dns, $connection_id);
  324. }
  325. /**
  326. * Returns an array of columns objects where the primary id, all columns ending in "_id" or "_count",
  327. * and columns used for single table inheritance has been removed.
  328. */
  329. function getContentColumns()
  330. {
  331. $inheritance_column = $this->getInheritanceColumn();
  332. $columns = $this->getColumns();
  333. foreach ($columns as $name=>$details){
  334. if((substr($name,-3) == '_id' || substr($name,-6) == '_count') ||
  335. !empty($details['primaryKey']) || ($inheritance_column !== false && $inheritance_column == $name)){
  336. unset($columns[$name]);
  337. }
  338. }
  339. return $columns;
  340. }
  341. /**
  342. * Creates an object, instantly saves it as a record (if the validation permits it), and returns it.
  343. * If the save fail under validations, the unsaved object is still returned.
  344. */
  345. function &create($attributes = null)
  346. {
  347. if(!isset($this->_activeRecordHasBeenInstantiated)){
  348. return Ak::handleStaticCall();
  349. }
  350. if(func_num_args() > 1){
  351. $attributes = func_get_args();
  352. }
  353. $model = $this->getModelName();
  354. $object =& new $model();
  355. $object->setAttributes($attributes);
  356. $object->save();
  357. return $object;
  358. }
  359. /**
  360. * Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
  361. *
  362. * $Product->countBySql("SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id");
  363. */
  364. function countBySql($sql)
  365. {
  366. if(!isset($this->_activeRecordHasBeenInstantiated)){
  367. return Ak::handleStaticCall();
  368. }
  369. if(!stristr($sql, 'COUNT') && stristr($sql, ' FROM ')){
  370. $sql = 'SELECT COUNT(*) '.substr($sql,strpos(str_replace(' from ',' FROM ', $sql),' FROM '));
  371. }
  372. if(!$this->isConnected()){
  373. $this->setConnection();
  374. }
  375. AK_LOG_EVENTS ? ($this->Logger->message($this->getModelName().' executing SQL: '.$sql)) : null;
  376. $rs = $this->_db->Execute($sql);
  377. return @(integer)$rs->fields[0];
  378. }
  379. /**
  380. * Increments the specified counter by one. So $DiscussionBoard->incrementCounter("post_count",
  381. * $discussion_board_id); would increment the "post_count" counter on the board responding to
  382. * $discussion_board_id. This is used for caching aggregate values, so that they doesn't need to
  383. * be computed every time. Especially important for looping over a collection where each element
  384. * require a number of aggregate values. Like the $DiscussionBoard that needs to list both the number of posts and comments.
  385. */
  386. function incrementCounter($counter_name, $id, $difference = 1)
  387. {
  388. $new_value = $this->getAttribute($counter_name) + $difference;
  389. if($this->updateAll($counter_name.' = '.$new_value, $this->getPrimaryKey().' = '.$this->castAttributeForDatabase($this->getPrimaryKey(), $id)) === 0){
  390. return false;
  391. }
  392. return $new_value;
  393. }
  394. /**
  395. * Works like AkActiveRecord::incrementCounter, but decrements instead.
  396. */
  397. function decrementCounter($counter_name, $id, $difference = 1)
  398. {
  399. $new_value = $this->getAttribute($counter_name) - $difference;
  400. if(!$this->updateAll($counter_name.' = '.$new_value, $this->getPrimaryKey().' = '.$this->castAttributeForDatabase($this->getPrimaryKey(), $id)) === 0){
  401. return false;
  402. }
  403. return $new_value;
  404. }
  405. /**
  406. * Finds the record from the passed id, instantly saves it with the passed attributes (if the validation permits it),
  407. * and returns it. If the save fail under validations, the unsaved object is still returned.
  408. */
  409. function update($id, $attributes)
  410. {
  411. if(!isset($this->_activeRecordHasBeenInstantiated)){
  412. return Ak::handleStaticCall();
  413. }
  414. if(is_array($id)){
  415. $results = array();
  416. foreach ($id as $idx=>$single_id){
  417. $results[] = $this->update($single_id, isset($attributes[$idx]) ? $attributes[$idx] : $attributes);
  418. }
  419. return $results;
  420. }else{
  421. $object =& $this->find($id);
  422. $object->updateAttributes($attributes);
  423. return $object;
  424. }
  425. }
  426. /**
  427. * Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
  428. * Note: Make sure that updates made with this method doesn't get subjected to validation checks.
  429. * Hence, attributes can be updated even if the full object isn't valid.
  430. */
  431. function updateAttribute($name, $value)
  432. {
  433. $this->setAttribute($name, $value);
  434. return $this->save(false);
  435. }
  436. /**
  437. * Updates all the attributes in from the passed array and saves the record. If the object is
  438. * invalid, the saving will fail and false will be returned.
  439. */
  440. function updateAttributes($attributes, $object = null)
  441. {
  442. isset($object) ? $object->setAttributes($attributes) : $this->setAttributes($attributes);
  443. return isset($object) ? $object->save() : $this->save();
  444. }
  445. /**
  446. * Updates all records with the SET-part of an SQL update statement in updates and returns an
  447. * integer with the number of rows updates. A subset of the records can be selected by specifying conditions. Example:
  448. * <code>$Billing->updateAll("category = 'authorized', approved = 1", "author = 'David'");</code>
  449. *
  450. * Important note: Condifitons are not sanitized yet so beware of accepting
  451. * variable conditions when using this function
  452. */
  453. function updateAll($updates, $conditions = null)
  454. {
  455. if(!isset($this->_activeRecordHasBeenInstantiated)){
  456. return Ak::handleStaticCall();
  457. }
  458. /**
  459. * @todo sanitize sql conditions
  460. */
  461. $sql = 'UPDATE '.$this->getTableName().' SET '.$updates;
  462. $sql .= isset($conditions) ? ' WHERE '.$conditions : '';
  463. $this->_executeSql($sql);
  464. return $this->_db->Affected_Rows();
  465. }
  466. /**
  467. * Deletes the record with the given id without instantiating an object first. If an array of
  468. * ids is provided, all of them are deleted.
  469. */
  470. function delete($id)
  471. {
  472. if(!isset($this->_activeRecordHasBeenInstantiated)){
  473. return Ak::handleStaticCall();
  474. }
  475. $id = func_num_args() > 1 ? func_get_args() : $id;
  476. return $this->deleteAll($this->getPrimaryKey().' IN ('.(is_array($id) ? join(', ',$id) : $id).')');
  477. }
  478. /**
  479. * Returns an array of names for the attributes available on this object sorted alphabetically.
  480. */
  481. function getAttributeNames()
  482. {
  483. if(!isset($this->_activeRecordHasBeenInstantiated)){
  484. return Ak::handleStaticCall();
  485. }
  486. $attributes = array_keys($this->getAvailableAttributes());
  487. $names = array_combine($attributes,array_map(array(&$this,'getAttributeCaption'), $attributes));
  488. natsort($names);
  489. return $names;
  490. }
  491. /**
  492. * Returns true if the specified attribute has been set by the user or by a database load and is neither null nor empty?
  493. */
  494. function isAttributePresent($attribute)
  495. {
  496. $value = $this->getAttribute($attribute);
  497. return !empty($value);
  498. }
  499. /**
  500. * Deletes all the records that matches the condition without instantiating the objects first
  501. * (and hence not calling the destroy method). Example:
  502. *
  503. * <code>$Post->destroyAll("person_id = 5 AND (category = 'Something' OR category = 'Else')");</code>
  504. *
  505. * Important note: Condifitons are not sanitized yet so beware of accepting
  506. * variable conditions when using this function
  507. */
  508. function deleteAll($conditions = null)
  509. {
  510. if(!isset($this->_activeRecordHasBeenInstantiated)){
  511. return Ak::handleStaticCall();
  512. }
  513. /**
  514. * @todo sanitize sql conditions
  515. */
  516. $sql = 'DELETE FROM '.$this->getTableName();
  517. $sql .= isset($conditions) ? ' WHERE '.$conditions : ($this->_getDatabaseType() == 'sqlite' ? ' WHERE 1' : ''); // (HACK) If where clause is not included sqlite_changes will not get the right result
  518. $this->_executeSql($sql);
  519. return $this->_db->Affected_Rows() > 0;
  520. }
  521. /**
  522. * Destroys the record with the given id by instantiating the object and calling destroy
  523. * (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.
  524. * Deletes the record in the database and freezes this instance to reflect that no changes should be
  525. * made (since they can't be persisted).
  526. */
  527. function destroy($id = null)
  528. {
  529. if(!isset($this->_activeRecordHasBeenInstantiated)){
  530. return Ak::handleStaticCall();
  531. }
  532. $this->transactionStart();
  533. $id = func_num_args() > 1 ? func_get_args() : $id;
  534. if(isset($id)){
  535. $id_arr = is_array($id) ? $id : array($id);
  536. if($objects = $this->find($id_arr)){
  537. $results = count($objects);
  538. $no_problems = true;
  539. for ($i=0; $results > $i; $i++){
  540. if(!$objects[$i]->destroy()){
  541. $no_problems = false;
  542. }
  543. }
  544. $this->transactionComplete();
  545. return $no_problems;
  546. }else {
  547. $this->transactionComplete();
  548. return false;
  549. }
  550. }else{
  551. if(!$this->isNewRecord()){
  552. if($this->beforeDestroy()){
  553. $this->notifyObservers('beforeDestroy');
  554. $sql = 'DELETE FROM '.$this->getTableName().' WHERE '.$this->getPrimaryKey().' = '.$this->_db->qstr($this->getId());
  555. $this->_executeSql($sql);
  556. $had_success = ($this->_db->Affected_Rows() > 0);
  557. if(!$had_success || ($had_success && !$this->afterDestroy())){
  558. $this->transactionFail();
  559. $had_success = false;
  560. }else{
  561. $had_success = $this->notifyObservers('afterDestroy') === false ? false : true;
  562. }
  563. $this->transactionComplete();
  564. $this->freeze();
  565. return $had_success;
  566. }else {
  567. $this->transactionFail();
  568. $this->transactionComplete();
  569. return false;
  570. }
  571. }
  572. }
  573. if(!$this->afterDestroy()){
  574. $this->transactionFail();
  575. }else{
  576. $this->notifyObservers('afterDestroy');
  577. }
  578. $this->transactionComplete();
  579. return false;
  580. }
  581. /**
  582. * Destroys the objects for all the records that matches the condition by instantiating
  583. * each object and calling the destroy method.
  584. *
  585. * Example:
  586. *
  587. * $Person->destroyAll("last_login < '2004-04-04'");
  588. */
  589. function destroyAll($conditions)
  590. {
  591. if($objects = $this->find('all',array('conditions'=>$conditions))){
  592. $results = count($objects);
  593. $no_problems = true;
  594. for ($i=0; $results > $i; $i++){
  595. if(!$objects[$i]->destroy()){
  596. $no_problems = false;
  597. }
  598. }
  599. return $no_problems;
  600. }else {
  601. return false;
  602. }
  603. }
  604. /**
  605. * Establishes the connection to the database. Accepts an array as input where the 'adapter'
  606. * key must be specified with the name of a database adapter (in lower-case) example for regular
  607. * databases (MySQL, Postgresql, etc):
  608. *
  609. * $AkActiveRecord->establishConnection(
  610. * array(
  611. * 'adapter' => "mysql",
  612. * 'host' => "localhost",
  613. * 'username' => "myuser",
  614. * 'password' => "mypass",
  615. * 'database' => "somedatabase"
  616. * ));
  617. *
  618. * Example for SQLite database:
  619. *
  620. * $AkActiveRecord->establishConnection(
  621. * array(
  622. * 'adapter' => "sqlite",
  623. * 'dbfile' => "path/to/dbfile"
  624. * )
  625. * )
  626. */
  627. function &establishConnection($spec = null)
  628. {
  629. if(isset($spec)){
  630. $dns = is_string($spec) ? $spec : '';
  631. if(!empty($spec['adapter'])){
  632. $dsn = $spec['adapter'] == 'sqlite' ?
  633. 'sqlite://'.urlencode($spec['dbfile']).'/' :
  634. $spec['adapter'].'://'.@$spec['username'].':'.@$spec['password'].'@'.@$spec['host'].'/'.@$spec['database'];
  635. }
  636. $dsn .= isset($spec['persist']) && $spec['persist'] === false ? '' : '?persist';
  637. return $this->setConnection($dns);
  638. }else{
  639. return false;
  640. }
  641. }
  642. /**
  643. * Just freeze the attributes hash, such that associations are still accessible even on destroyed records.
  644. *
  645. * @todo implement freeze correctly for its intended use
  646. */
  647. function freeze()
  648. {
  649. $this->_freeze = true;
  650. }
  651. function isFrozen()
  652. {
  653. return !empty($this->_freeze);
  654. }
  655. /**
  656. * Returns true if the given id represents the primary key of a record in the database, false otherwise. Example:
  657. *
  658. * $Person->exists(5);
  659. */
  660. function exists($id)
  661. {
  662. return $this->find('first',array('conditions' => array($this->getPrimaryKey().' = '.$id))) !== false;
  663. }
  664. /**
  665. * Find operates with three different retrieval approaches:
  666. * * Find by id: This can either be a specific id find(1), a list of ids find(1, 5, 6),
  667. * or an array of ids find(array(5, 6, 10)). If no record can be found for all of the listed ids,
  668. * then RecordNotFound will be raised.
  669. * * Find first: This will return the first record matched by the options used. These options
  670. * can either be specific conditions or merely an order.
  671. * If no record can matched, false is returned.
  672. * * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.
  673. *
  674. * All approaches accepts an $option array as their last parameter. The options are:
  675. *
  676. * 'conditions' => An SQL fragment like "administrator = 1" or array("user_name = ?" => $username). See conditions in the intro.
  677. * 'order' => An SQL fragment like "created_at DESC, name".
  678. * 'limit' => An integer determining the limit on the number of rows that should be returned.
  679. * 'offset' => An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
  680. * 'joins' => An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = $id". (Rarely needed).
  681. * 'include' => Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols
  682. * named refer to already defined associations. See eager loading under Associations.
  683. *
  684. * Examples for find by id:
  685. *
  686. * $Person->find(1); // returns the object for ID = 1
  687. * $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
  688. * $Person->find(array(7, 17)); // returns an array for objects with IDs in (7, 17)
  689. * $Person->find(array(1)); // returns an array for objects the object with ID = 1
  690. * $Person->find(1, array('conditions' => "administrator = 1", 'order' => "created_on DESC"));
  691. *
  692. * Examples for find first:
  693. *
  694. * $Person->find('first'); // returns the first object fetched by SELECT * FROM people
  695. * $Person->find('first', array('conditions' => array("user_name = ':user_name'", ':user_name' => $user_name)));
  696. * $Person->find('first', array('order' => "created_on DESC", 'offset' => 5));
  697. *
  698. * Examples for find all:
  699. *
  700. * $Person->find('all'); // returns an array of objects for all the rows fetched by SELECT * FROM people
  701. * $Person->find(); // Same as $Person->find('all');
  702. * $Person->find('all', array('conditions => array("category IN (categories)", 'categories' => join(','$categories)), 'limit' => 50));
  703. * $Person->find('all', array('offset' => 10, 'limit' => 10));
  704. * $Person->find('all', array('include' => array('account', 'friends'));
  705. *
  706. */
  707. function &find()
  708. {
  709. if(!isset($this->_activeRecordHasBeenInstantiated)){
  710. return Ak::handleStaticCall();
  711. }
  712. $num_args = func_num_args();
  713. if($num_args === 2 && func_get_arg(0) == 'set arguments'){
  714. $args = func_get_arg(1);
  715. $num_args = count($args);
  716. }
  717. $args = $num_args > 0 ? (!isset($args) ? func_get_args() : $args) : array('all');
  718. if($num_args === 1 && is_numeric($args[0]) && $args[0] > 0){
  719. $args[0] = (integer)$args[0]; //Cast query by Id
  720. }
  721. $options = $num_args > 0 && (is_array($args[$num_args-1]) && isset($args[0][0]) && !is_numeric($args[0][0])) ? array_pop($args) : array();
  722. //$options = func_get_arg(func_num_args()-1);
  723. if(!empty($options['conditions']) && is_array($options['conditions'])){
  724. if (isset($options['conditions'][0]) && strstr($options['conditions'][0], '?') && count($options['conditions']) > 1){
  725. $pattern = array_shift($options['conditions']);
  726. $options['bind'] = array_values($options['conditions']);
  727. $options['conditions'] = $pattern;
  728. }elseif (isset($options['conditions'][0])){
  729. $pattern = array_shift($options['conditions']);
  730. $options['conditions'] = str_replace(array_keys($options['conditions']), array_values($this->getSanitizedConditionsArray($options['conditions'])),$pattern);
  731. }else{
  732. $options['conditions'] = join(' AND ',(array)$this->getAttributesQuoted($options['conditions']));
  733. }
  734. }
  735. if ($num_args === 2 && !empty($args[0]) && !empty($args[1]) && is_string($args[0]) && ($args[0] == 'all' || $args[0] == 'first') && is_string($args[1])){
  736. if (!is_array($args[1]) && $args[1] > 0 && $args[0] == 'first'){
  737. $num_args = 1;
  738. $args = array($args[1]);
  739. $options = array();
  740. }else{
  741. $options['conditions'] = $args[1];
  742. $args = array($args[0]);
  743. }
  744. }elseif ($num_args === 1 && isset($args[0]) && is_string($args[0]) && $args[0] != 'all' && $args[0] != 'first'){
  745. $options = array('conditions'=> $args[0]);
  746. $args = array('first');
  747. }
  748. if(!empty($options['conditions']) && is_numeric($options['conditions']) && $options['conditions'] > 0){
  749. unset($options['conditions']);
  750. }
  751. if($num_args > 1){
  752. if(!empty($args[0]) && is_string($args[0]) && strstr($args[0],'?')){
  753. $options = array_merge(array('conditions' => array_shift($args)), $options);
  754. $options['bind'] = $args;
  755. $args = array('all');
  756. }elseif (!empty($args[1]) && is_string($args[1]) && strstr($args[1],'?')){
  757. $_tmp_mode = array_shift($args);
  758. $options = array_merge(array('conditions' => array_shift($args)),$options);
  759. $options['bind'] = $args;
  760. $args = array($_tmp_mode);
  761. }
  762. }
  763. switch ($args[0]) {
  764. case 'first':
  765. $options = array_merge($options, array((!empty($options['include']) && $this->hasAssociations() ?'virtual_limit':'limit')=>1));
  766. $result =& $this->find('all', $options);
  767. if(!empty($result) && is_array($result)){
  768. $_result =& $result[0];
  769. }else{
  770. $_result = false;
  771. }
  772. return $_result;
  773. break;
  774. case 'all':
  775. $limit = isset($options['limit']) ? $options['limit'] : null;
  776. $offset = isset($options['offset']) ? $options['offset'] : null;
  777. if((empty($options['conditions']) && empty($options['order']) && is_null($offset) && $this->_getDatabaseType() == 'postgre' ? 1 : 0)){
  778. $options['order'] = $this->getPrimaryKey();
  779. }
  780. $sql = $this->constructFinderSql($options);
  781. if(!empty($options['bind']) && is_array($options['bind']) && strstr($sql,'?')){
  782. $sql = array_merge(array($sql),$options['bind']);
  783. }
  784. if((!empty($options['include']) && $this->hasAssociations())){
  785. $result =& $this->findWithAssociations($options, $limit, $offset);
  786. }else{
  787. $result =& $this->findBySql($sql, $limit, $offset);
  788. }
  789. if(!empty($result) && is_array($result)){
  790. $_result =& $result;
  791. }else{
  792. $_result = false;
  793. }
  794. return $_result;
  795. break;
  796. default:
  797. $ids = array_unique(isset($args[0]) ? (is_array($args[0]) ? $args[0] : (array)$args) : array());
  798. $num_ids = count($ids);
  799. $num_args = count($args);
  800. if(isset($ids[$num_ids-1]) && is_array($ids[$num_ids-1])){
  801. $options = array_merge($options, array_pop($ids));
  802. $num_ids--;
  803. }
  804. if($num_args === 1 && !$args[0] > 0){
  805. $options['conditions'] = $args[0];
  806. }
  807. $conditions = !empty($options['conditions']) ? ' AND '.$options['conditions'] : '';
  808. if(empty($options) && !empty($args[0]) && !empty($args[1]) && is_array($args[0]) && is_array($args[1])){
  809. $options = array_pop($args);
  810. }
  811. switch ($num_ids){
  812. case 0 :
  813. trigger_error($this->t('Couldn\'t find %object_name without an ID%conditions',array('%object_name'=>$this->getModelName(),'%conditions'=>$conditions)), E_USER_ERROR);
  814. break;
  815. case 1 :
  816. $table_name = !empty($options['include']) && $this->hasAssociations() ? '__owner' : $this->getTableName();
  817. $result =& $this->find('first', array_merge($options, array('conditions' => $table_name.'.'.$this->getPrimaryKey().' = '.$ids[0].$conditions)));
  818. if(is_array($args[0]) && $result !== false){
  819. //This is a dirty hack for avoiding PHP4 pass by reference error
  820. $result_for_ref = array(&$result);
  821. $_result =& $result_for_ref;
  822. }else{
  823. $_result =& $result;
  824. }
  825. return $_result;
  826. break;
  827. default:
  828. $ids_condition = $this->getPrimaryKey().' IN ('.join(', ',$ids).')';
  829. if(!empty($options['conditions']) && is_array($options['conditions'])){
  830. $options['conditions'][0] = $ids_condition.' AND '.$options['conditions'][0];
  831. }elseif(!empty($options['conditions'])){
  832. $options['conditions'] = $ids_condition.' AND '.$options['conditions'];
  833. }else{
  834. $without_conditions = true;
  835. $options['conditions'] = $ids_condition;
  836. }
  837. $result =& $this->find('all', $options);
  838. if(is_array($result) && (count($result) == $num_ids || empty($without_conditions))){
  839. if($result === false){
  840. $_result = false;
  841. }else{
  842. $_result =& $result;
  843. }
  844. return $_result;
  845. }else{
  846. $result = false;
  847. return $result;
  848. }
  849. break;
  850. }
  851. break;
  852. }
  853. $result = false;
  854. return $result;
  855. }
  856. function &findFirst()
  857. {
  858. if(!isset($this->_activeRecordHasBeenInstantiated)){
  859. return Ak::handleStaticCall();
  860. }
  861. $args = func_get_args();
  862. $result =& Ak::call_user_func_array(array(&$this,'find'), array_merge(array('first'),$args));
  863. return $result;
  864. }
  865. function &findAll()
  866. {
  867. if(!isset($this->_activeRecordHasBeenInstantiated)){
  868. return Ak::handleStaticCall();
  869. }
  870. $args = func_get_args();
  871. $result =& Ak::call_user_func_array(array(&$this,'find'), array_merge(array('all'),$args));
  872. return $result;
  873. }
  874. function &objectCache()
  875. {
  876. static $cache;
  877. $args =& func_get_args();
  878. if(count($args) == 2){
  879. if(!isset($cache[$args[0]])){
  880. $cache[$args[0]] =& $args[1];
  881. }
  882. }elseif(!isset($cache[$args[0]])){
  883. return false;
  884. }
  885. return $cache[$args[0]];
  886. }
  887. /**
  888. * Gets an array from a string.
  889. *
  890. * Acts like Php explode() function but uses any of this as valid separators ' AND ',' and ',' + ',' ',',',';'
  891. */
  892. function getArrayFromAkString($string)
  893. {
  894. if(is_array($string)){
  895. return $string;
  896. }
  897. $string = str_replace(array(' AND ',' and ',' + ',' ',',',';'),array('|','|','|','','|','|'),trim($string));
  898. return strstr($string,'|') ? explode('|', $string) : array($string);
  899. }
  900. // Gets the column name for use with single table inheritance ? can be overridden in subclasses.
  901. function getInheritanceColumn()
  902. {
  903. return empty($this->_inheritanceColumn) ? ($this->hasColumn('type') ? 'type' : false ) : $this->_inheritanceColumn;
  904. }
  905. // Defines the column name for use with single table inheritance ? can be overridden in subclasses.
  906. function setInheritanceColumn($column_name)
  907. {
  908. if(!$this->hasColumn($column_name)){
  909. 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);
  910. return false;
  911. }elseif($this->getColumnType($column_name) != 'string'){
  912. 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);
  913. return false;
  914. }else{
  915. $this->_inheritanceColumn = $column_name;
  916. return true;
  917. }
  918. }
  919. function getColumnsWithRegexBoundaries()
  920. {
  921. $columns = array_keys($this->getColumns());
  922. foreach ($columns as $k=>$column){
  923. $columns[$k] = '/([^\.])\b('.$column.')\b/';
  924. }
  925. return $columns;
  926. }
  927. //SELECT t.code as codigo , c.description as descripcion FROM technical_listings as t LEFT OUTER JOIN categories as c ON c.id = t.category_id
  928. /**
  929. * Works like find_all, but requires a complete SQL string. Examples:
  930. * $Post->findBySql("SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id");
  931. * $Post->findBySql(array("SELECT * FROM posts WHERE author = ? AND created_on > ?", $author_id, $start_date));
  932. */
  933. function &findBySql($sql, $limit = null, $offset = null, $bindings = null)
  934. {
  935. if(!isset($this->_activeRecordHasBeenInstantiated)){
  936. return Ak::handleStaticCall();
  937. }
  938. if(is_array($sql)){
  939. $sql_query = array_shift($sql);
  940. $bindings = is_array($sql) && count($sql) > 0 ? $sql : array($sql);
  941. $sql = $sql_query;
  942. }
  943. $this->setConnection();
  944. AK_LOG_EVENTS ? $this->_startSqlBlockLog() : null;
  945. $objects = array();
  946. if(is_integer($limit)){
  947. if(is_integer($offset)){
  948. $results = !empty($bindings) ? $this->_db->SelectLimit($sql, $limit, $offset, $bindings) : $this->_db->SelectLimit($sql, $limit, $offset);
  949. }else {
  950. $results = !empty($bindings) ? $this->_db->SelectLimit($sql, $limit, -1, $bindings) : $this->_db->SelectLimit($sql, $limit);
  951. }
  952. }else{
  953. $results = !empty($bindings) ? $this->_db->Execute($sql, $bindings) : $this->_db->Execute($sql);
  954. }
  955. AK_LOG_EVENTS ? $this->_endSqlBlockLog() : null;
  956. if(!$results){
  957. AK_DEBUG ? trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE) : null;
  958. }else{
  959. $objects = array();
  960. while ($record = $results->FetchRow()) {
  961. $objects[] =& $this->instantiate($this->getOnlyAvailableAtrributes($record), false);
  962. }
  963. }
  964. return $objects;
  965. }
  966. /**
  967. * This function pretends to emulate ror finders until AkActiveRecord::addMethod becomes stable on future PHP versions.
  968. * @todo use PHP5 __call method for handling the magic finder methods like findFirstByUnsenameAndPassword('bermi','pass')
  969. */
  970. function &findFirstBy()
  971. {
  972. if(!isset($this->_activeRecordHasBeenInstantiated)){
  973. return Ak::handleStaticCall();
  974. }
  975. $args = func_get_args();
  976. if($args[0] != 'first'){
  977. array_unshift($args,'first');
  978. }
  979. $result =& Ak::call_user_func_array(array(&$this,'findBy'), $args);
  980. return $result;
  981. }
  982. function &findLastBy()
  983. {
  984. if(!isset($this->_activeRecordHasBeenInstantiated)){
  985. return Ak::handleStaticCall();
  986. }
  987. $args = func_get_args();
  988. $options = array_pop($args);
  989. if(!is_array($options)){
  990. array_push($args, $options);
  991. $options = array();
  992. }
  993. $options['order'] = $this->getPrimaryKey().' DESC';
  994. array_push($args, $options);
  995. $result =& Ak::call_user_func_array(array(&$this,'findFirstBy'), $args);
  996. return $result;
  997. }
  998. function &findAllBy()
  999. {
  1000. if(!isset($this->_activeRecordHasBeenInstantiated)){
  1001. return Ak::handleStaticCall();
  1002. }
  1003. $args = func_get_args();
  1004. if($args[0] == 'first'){
  1005. array_shift($args);
  1006. }
  1007. $result =& Ak::call_user_func_array(array(&$this,'findBy'), $args);
  1008. return $result;
  1009. }
  1010. function &findBy()
  1011. {
  1012. if(!isset($this->_activeRecordHasBeenInstantiated)){
  1013. return Ak::handleStaticCall();
  1014. }
  1015. $args = func_get_args();
  1016. $sql = array_shift($args);
  1017. if($sql == 'all' || $sql == 'first'){
  1018. $fetch = $sql;
  1019. $sql = array_shift($args);
  1020. }else{
  1021. $fetch = 'all';
  1022. }
  1023. $options = array_pop($args);
  1024. if(!is_array($options)){
  1025. array_push($args, $options);
  1026. $options = array();
  1027. }
  1028. $query_values = $args;
  1029. $query_arguments_count = count($query_values);
  1030. $sql = str_replace(array('(',')','||','|','&&','&',' '),array(' ( ',' ) ',' OR ',' OR ',' AND ',' AND ',' '),$sql);
  1031. $operators = array('AND','and','(',')','&','&&','NOT','<>','OR','|','||');
  1032. $pieces = explode(' ',$sql);
  1033. $pieces = array_diff($pieces,array(' ',''));
  1034. $params = array_diff($pieces,$operators);
  1035. $operators = array_diff($pieces,$params);
  1036. $new_sql = '';
  1037. $parameter_count = 0;
  1038. $requested_args = array();
  1039. foreach ($pieces as $piece){
  1040. if(in_array($piece,$params) && $this->hasColumn($piece)){
  1041. $new_sql .= $piece.' = ? ';
  1042. $requested_args[$parameter_count] = $piece;
  1043. $parameter_count++;
  1044. }elseif (!in_array($piece,$operators)){
  1045. if(strstr($piece,':')){
  1046. $_tmp_parts = explode(':',$piece);
  1047. if($this->hasColumn($_tmp_parts[0])){
  1048. switch (strtolower($_tmp_parts[1])) {
  1049. case 'like':
  1050. case '%like%':
  1051. case 'is':
  1052. case 'has':
  1053. case 'contains':
  1054. $query_values[$parameter_count] = '%'.$query_values[$parameter_count].'%';
  1055. $new_sql .= $_tmp_parts[0]." LIKE ? ";
  1056. break;
  1057. case 'like_left':
  1058. case 'like%':
  1059. case 'begins':
  1060. case 'begins_with':
  1061. case 'starts':
  1062. case 'starts_with':
  1063. $query_values[$parameter_count] = $query_values[$parameter_count].'%';
  1064. $new_sql .= $_tmp_parts[0]." LIKE ? ";
  1065. break;
  1066. case 'like_right':
  1067. case '%like':
  1068. case 'ends':
  1069. case 'ends_with':
  1070. case 'finishes':
  1071. case 'finishes_with':
  1072. $query_values[$parameter_count] = '%'.$query_values[$parameter_count];
  1073. $new_sql .= $_tmp_parts[0]." LIKE ? ";
  1074. break;
  1075. default:
  1076. $query_values[$parameter_count] = $query_values[$parameter_count];
  1077. $new_sql .= $_tmp_parts[0].' '.$_tmp_parts[1].' ? ';
  1078. break;
  1079. }
  1080. $requested_args[$parameter_count] = $_tmp_parts[0];
  1081. $parameter_count++;
  1082. }else {
  1083. $new_sql .= $_tmp_parts[0];
  1084. }
  1085. }else{
  1086. $new_sql .= $piece.' ';
  1087. }
  1088. }else{
  1089. $new_sql .= $piece.' ';
  1090. }
  1091. }
  1092. if($query_arguments_count != count($requested_args)){
  1093. trigger_error(Ak::t('Argument list did not match expected set. Requested arguments are:').join(', ',$requested_args),E_USER_ERROR);
  1094. $false = false;
  1095. return $false;
  1096. }
  1097. $true_bool_values = array(true,1,'true','True','TRUE','1','y','Y','yes','Yes','YES','s','Si','SI','V','v','T','t');
  1098. foreach ($requested_args as $k=>$v){
  1099. switch ($this->getColumnType($v)) {
  1100. case 'boolean':
  1101. $query_values[$k] = in_array($query_values[$k],$true_bool_values) ? 1 : 0;
  1102. break;
  1103. case 'date':
  1104. case 'datetime':
  1105. $query_values[$k] = str_replace('/','-', $this->castAttributeForDatabase($k,$query_values[$k],false));
  1106. break;
  1107. default:
  1108. break;
  1109. }
  1110. }
  1111. $_find_arguments = array();
  1112. $_find_arguments[] = $fetch;
  1113. $_find_arguments[] = $new_sql;
  1114. foreach ($query_values as $value){
  1115. $_find_arguments[] = $value;
  1116. }
  1117. $_find_arguments[] = $options;
  1118. $_result =& $this->find('set arguments', $_find_arguments);
  1119. $result =& $_result; // Pass by reference hack
  1120. return $result;
  1121. }
  1122. /**
  1123. * Finder methods must instantiate through this method to work with the single-table inheritance model and
  1124. * eager loading associations.
  1125. * that makes it possible to create objects of different types from the same table.
  1126. */
  1127. function &instantiate($record, $set_as_new = true)
  1128. {
  1129. $inheritance_column = $this->getInheritanceColumn();
  1130. if(!empty($record[$inheritance_column])){
  1131. $inheritance_column = $record[$inheritance_column];
  1132. $inheritance_model_name = AkInflector::camelize($inheritance_column);
  1133. @require_once(AkInflector::toModelFilename($inheritance_model_name));
  1134. if(!class_exists($inheritance_model_name)){
  1135. trigger_error($this->t("The single-table inheritance mechanism failed to locate the subclass: '%class_name'. ".
  1136. "This error is raised because the column '%column' is reserved for storing the class in case of inheritance. ".
  1137. "Please rename this column if you didn't intend it to be used for storing the inheritance class ".
  1138. "or overwrite #{self.to_s}.inheritance_column to use another column for that information.",
  1139. array('%class_name'=>$inheritance_model_name, '%column'=>$this->getInheritanceColumn())),E_USER_ERROR);
  1140. }
  1141. }
  1142. $model_name = isset($inheritance_model_name) ? $inheritance_model_name : $this->getModelName();
  1143. $object =& new $model_name('attributes', $record);
  1144. $object->_newRecord = $set_as_new;
  1145. (AK_CLI && AK_ENVIRONMENT == 'development') ? $object ->toString() : null;
  1146. return $object;
  1147. }
  1148. function constructFinderSql($options, $select_from_prefix = 'default')
  1149. {
  1150. $sql = isset($options['select_prefix']) ? $options['select_prefix'] : ($select_from_prefix == 'default' ? 'SELECT * FROM '.$this->getTableName() : $select_from_prefix);
  1151. $sql .= !empty($options['joins']) ? ' '.$options['joins'] : '';
  1152. if(isset($options['conditions'])){
  1153. $this->addConditions($sql, $options['conditions']);
  1154. }elseif ($this->getInheritanceColumn() !== false){
  1155. $this->addConditions($sql, array());
  1156. }
  1157. // Create an alias for order
  1158. if(empty($options['order']) && !empty($options['sort'])){
  1159. $options['order'] = $options['sort'];
  1160. }
  1161. $sql .= !empty($options['order']) ? ' ORDER BY '.$options['order'] : '';
  1162. return $sql;
  1163. }
  1164. /**
  1165. * Adds a sanitized version of $conditions to the $sql string. Note that the passed $sql string is changed.
  1166. */
  1167. function addConditions(&$sql, $conditions = null)
  1168. {
  1169. $concat = empty($sql) ? '' : ' WHERE ';
  1170. if(!empty($conditions)){
  1171. $sql .= $concat.$conditions;
  1172. $concat = ' AND ';
  1173. }
  1174. if($this->descendsFromActiveRecord($this) && $this->getInheritanceColumn() !== false){
  1175. $type_condition = $this->typeCondition();
  1176. $sql .= !empty($type_condition) ? $concat.$type_condition : '';
  1177. }
  1178. return $sql;
  1179. }
  1180. /**
  1181. * Gets a sanitized version of the input array. Each element will be escaped
  1182. */
  1183. function getSanitizedConditionsArray($conditions_array)
  1184. {
  1185. $result = array();
  1186. foreach ($conditions_array as $k=>$v){
  1187. $k = str_replace(':','',$k); // Used for Oracle type bindings
  1188. if($this->hasColumn($k)){
  1189. $v = $this->castAttributeForDatabase($k, $v);
  1190. $result[$k] = $v;
  1191. }
  1192. }
  1193. return $result;
  1194. }
  1195. /**
  1196. * This functions is used to get the conditions from an AkRequest object
  1197. */
  1198. function getConditions($conditions, $prefix = '', $model_name = null)
  1199. {
  1200. $model_name = isset($model_name) ? $model_name : $this->getModelName();
  1201. $model_conditions = !empty($conditions[$model_name]) ? $conditions[$model_name] : $conditions;
  1202. if(is_a($this->$model_name)){
  1203. $model_instance =& $this->$model_name;
  1204. }else{
  1205. $model_instance =& $this;
  1206. }
  1207. $new_conditions = array();
  1208. if(is_array($model_conditions)){
  1209. foreach ($model_conditions as $col=>$value){
  1210. if($model_instance->hasColumn($col)){
  1211. $new_conditions[$prefix.$col] = $value;
  1212. }
  1213. }
  1214. }
  1215. return $new_conditions;
  1216. }
  1217. function descendsFromActiveRecord(&$object)
  1218. {
  1219. if(substr(strtolower(get_parent_class($object)),-12) == 'activerecord'){
  1220. return true;
  1221. }
  1222. if(!method_exists($object, 'getInheritanceColumn')){
  1223. return false;
  1224. }
  1225. $inheritance_column = $object->getInheritanceColumn();
  1226. return !empty($inheritance_column);
  1227. }
  1228. function typeCondition()
  1229. {
  1230. $inheritance_column = $this->getInheritanceColumn();
  1231. $type_condition = array();
  1232. $table_name = $this->getTableName();
  1233. $available_types = array_merge(array($this->getModelName()),$this->getSubclasses());
  1234. foreach ($available_types as $subclass){
  1235. $type_condition[] = ' '.$table_name.'.'.$inheritance_column.' = \''.AkInflector::demodulize($subclass).'\' ';
  1236. }
  1237. return empty($type_condition) ? '' : '('.join('OR',$type_condition).') ';
  1238. }
  1239. function getSubclasses()
  1240. {
  1241. $current_class = get_class($this);
  1242. $subclasses = array();
  1243. $classes = get_declared_classes();
  1244. while ($class = array_shift($classes)) {
  1245. $parent_class = get_parent_class($class);
  1246. if($parent_class == $current_class || in_array($parent_class,$subclasses)){
  1247. $subclasses[] = $class;
  1248. }elseif(!empty($parent_class)){
  1249. $classes[] = $parent_class;
  1250. }
  1251. }
  1252. $subclasses = array_unique(array_map(array(&$this,'_getModelName'),$subclasses));
  1253. return $subclasses;
  1254. }
  1255. function _quoteColumnName($column_name)
  1256. {
  1257. return $this->_db->nameQuote.$column_name.$this->_db->nameQuote;
  1258. }
  1259. /**
  1260. * Parses an special formated array as a list of keys and values
  1261. *
  1262. * This function generates an array with values and keys from an array with numeric keys.
  1263. *
  1264. * This allows to parse an array to a function in the following manner.
  1265. * create('first_name->', 'Bermi', 'last_name->', 'Ferrer');
  1266. * //Previous code will be the same that
  1267. * create(array('first_name'=>'Bermi', 'last_name'=> 'Ferrer'));
  1268. *
  1269. * Use this syntax only for quick testings, not for production environments. If the number of arguments varies, the result might be unpredictable.
  1270. *
  1271. * This function syntax is disabled by default. You need to define('AK_ENABLE_AKELOS_ARGS', true)
  1272. * if you need this functionality.
  1273. *
  1274. * @deprecated
  1275. */
  1276. function parseAkelosArgs(&$args)
  1277. {
  1278. if(!AK_ENABLE_AKELOS_ARGS){
  1279. return ;
  1280. }
  1281. $k = array_keys($args);
  1282. if(isset($k[1]) && substr($args[$k[0]],-1) == '>'){
  1283. $size = sizeOf($k);
  1284. $params = array();
  1285. for($i = 0; $i < $size; $i++ ) {
  1286. $v = $args[$k[$i]];
  1287. if(!isset($key) && is_string($args[$k[$i]]) && substr($v,-1) == '>'){
  1288. $key = rtrim($v, '=-> ');
  1289. }elseif(isset($key)) {
  1290. $params[$key] = $v;
  1291. unset($key);
  1292. }else{
  1293. $params[$k[$i]] = $v;
  1294. }
  1295. }
  1296. if(!empty($params)){
  1297. $args = $params;
  1298. }
  1299. }
  1300. $this->_castDateParametersFromDateHelper_($args);
  1301. }
  1302. /**
  1303. * Joins date arguments into a single attribute. Like the array generated by the date_helper, so
  1304. * array('published_on(1i)' => 2002, 'published_on(2i)' => 'January', 'published_on(3i)' => 24)
  1305. * Will be converted to array('published_on'=>'2002-01-24')
  1306. */
  1307. function _castDateParametersFromDateHelper_(&$params)
  1308. {
  1309. if(empty($params)){
  1310. return;
  1311. }
  1312. $date_attributes = array();
  1313. foreach ($params as $k=>$v) {
  1314. if(preg_match('/^([A-Za-z0-9_]+)\(([1-5]{1})i\)$/',$k,$match)){
  1315. $date_attributes[$match[1]][$match[2]] = $v;
  1316. unset($params[$k]);
  1317. }
  1318. }
  1319. foreach ($date_attributes as $attribute=>$date){
  1320. $params[$attribute] = Ak::getDate(Ak::getTimestamp(trim(@$date[1].'-'.@$date[2].'-'.@$date[3].' '.@$date[4].':'.@$date[5],' :-')));
  1321. }
  1322. }
  1323. // EXPERIMENTAL: Will allow to create finders when PHP includes aggregate_methods as a stable feature on PHP4, for PHP5 we might use __call
  1324. function _buildFinders($finderFunctions = array('find','findFirst'))
  1325. {
  1326. if(!$this->_dynamicMethods){
  1327. return;
  1328. }
  1329. $columns = !is_array($this->_dynamicMethods) ? array_keys($this->getColumns()) : $this->_dynamicMethods;
  1330. $class_name = 'ak_'.md5(serialize($columns));
  1331. if(!class_exists($class_name)){
  1332. $permutations = Ak::permute($columns);
  1333. $implementations = '';
  1334. foreach ($finderFunctions as $finderFunction){
  1335. foreach ($permutations as $permutation){
  1336. $permutation = array_map(array('AkInflector','camelize'),$permutation);
  1337. foreach ($permutation as $k=>$v){
  1338. $method_name = $finderFunction.'By'.join($permutation,'And');
  1339. $implementation = 'function &'.$method_name.'(';
  1340. $first_param = '';
  1341. $params = '';
  1342. $i = 1;
  1343. foreach ($permutation as $column){
  1344. $column = AkInflector::underscore($column);
  1345. $params .= "$$column, ";
  1346. $first_param .= "$column ";
  1347. $i++;
  1348. }
  1349. $implementation .= trim($params,' ,')."){\n";
  1350. $implementation .= '$options = func_num_args() == '.$i.' ? func_get_arg('.($i-1).') : array();'."\n";
  1351. $implementation .= 'return $this->'.$finderFunction.'By(\''.$first_param.'\', '.trim($params,' ,').", \$options);\n }\n";
  1352. $implementations[$method_name] = $implementation;
  1353. array_shift($permutation);
  1354. }
  1355. }
  1356. }
  1357. eval('class '.$class_name.' { '.join("\n",$implementations).' } ');
  1358. }
  1359. aggregate_methods(&$this, $class_name);
  1360. }
  1361. /**
  1362. * New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved
  1363. * (pass an array with key names matching the associated table column names).
  1364. * In both instances, valid attribute keys are determined by the column names of the associated table ? hence you can't
  1365. * have attributes that aren't part of the table columns.
  1366. */
  1367. function newRecord($attributes)
  1368. {
  1369. $this->_newRecord = true;
  1370. if(AK_ACTIVE_RECORD_SKIP_SETTING_ACTIVE_RECORD_DEFAULTS && empty($attributes)){
  1371. return;
  1372. }
  1373. if(isset($attributes) && !is_array($attributes)){
  1374. $attributes = func_get_args();
  1375. }
  1376. $this->setAttributes($this->attributesFromColumnDefinition(),true);
  1377. $this->setAttributes($attributes);
  1378. }
  1379. function setAttribute($attribute, $value, $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS, $compose_after_set = true)
  1380. {
  1381. if($attribute[0] == '_'){
  1382. return false;
  1383. }
  1384. if($this->isFrozen()){
  1385. return false;
  1386. }
  1387. if($inspect_for_callback_child_method === true && method_exists($this,'set'.AkInflector::camelize($attribute))){
  1388. static $watchdog;
  1389. $watchdog[$attribute] = @$watchdog[$attribute]+1;
  1390. if($watchdog[$attribute] == 5000){
  1391. if((!defined('AK_ACTIVE_RECORD_PROTECT_SET_RECURSION')) || defined('AK_ACTIVE_RECORD_PROTECT_SET_RECURSION') && AK_ACTIVE_RECORD_PROTECT_SET_RECURSION){
  1392. trigger_error(Ak::t('You are calling recursivelly 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);
  1393. return false;
  1394. }
  1395. }
  1396. $this->{$attribute.'_before_type_cast'} = $value;
  1397. return $this->{'set'.AkInflector::camelize($attribute)}($value);
  1398. }
  1399. if($this->hasAttribute($attribute)){
  1400. $this->{$attribute.'_before_type_cast'} = $value;
  1401. $this->$attribute = $value;
  1402. if($compose_after_set && !empty($this->_combinedAttributes) && !$this->requiredForCombination($attribute)){
  1403. $combined_attributes = $this->_getCombinedAttributesWhereThisAttributeIsUsed($attribute);
  1404. foreach ($combined_attributes as $combined_attribute){
  1405. $this->composeCombinedAttribute($combined_attribute);
  1406. }
  1407. }
  1408. if ($compose_after_set && $this->isCombinedAttribute($attribute)){
  1409. $this->decomposeCombinedAttribute($attribute);
  1410. }
  1411. }elseif(substr($attribute,-12) == 'confirmation' && $this->hasAttribute(substr($attribute,0,-13))){
  1412. $this->$attribute = $value;
  1413. }
  1414. if($this->_internationalize){
  1415. if(is_array($value)){
  1416. $this->setAttributeLocales($attribute, $value);
  1417. }elseif(is_string($inspect_for_callback_child_method)){
  1418. $this->setAttributeByLocale($attribute, $value, $inspect_for_callback_child_method);
  1419. }else{
  1420. $this->_groupInternationalizedAttribute($attribute, $value);
  1421. }
  1422. }
  1423. return true;
  1424. }
  1425. function set($attribute, $value = null, $inspect_for_callback_child_method = true, $compose_after_set = true)
  1426. {
  1427. if(is_array($attribute)){
  1428. return $this->setAttributes($attribute);
  1429. }
  1430. return $this->setAttribute($attribute, $value, $inspect_for_callback_child_method, $compose_after_set);
  1431. }
  1432. function getAttribute($attribute, $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS)
  1433. {
  1434. if($attribute[0] == '_'){
  1435. return false;
  1436. }
  1437. if($inspect_for_callback_child_method === true && method_exists($this,'get'.AkInflector::camelize($attribute))){
  1438. static $watchdog;
  1439. $watchdog[@$attribute] = @$watchdog[$attribute]+1;
  1440. if($watchdog[$attribute] == 66){
  1441. if((!defined('AK_ACTIVE_RECORD_PROTECT_GET_RECURSION')) || defined('AK_ACTIVE_RECORD_PROTECT_GET_RECURSION') && AK_ACTIVE_RECORD_PROTECT_GET_RECURSION){
  1442. 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);
  1443. return false;
  1444. }
  1445. }
  1446. $value = $this->{'get'.AkInflector::camelize($attribute)}();
  1447. return $this->getInheritanceColumn() === $attribute ? AkInflector::demodulize($value) : $value;
  1448. }
  1449. if(isset($this->$attribute) || (!isset($this->$attribute) && $this->isCombinedAttribute($attribute))){
  1450. if($this->hasAttribute($attribute)){
  1451. if (!empty($this->_combinedAttributes) && $this->isCombinedAttribute($attribute)){
  1452. $this->composeCombinedAttribute($attribute);
  1453. }
  1454. return isset($this->$attribute) ? $this->$attribute : null;
  1455. }elseif($this->_internationalize && $this->_isInternationalizeCandidate($attribute)){
  1456. if(!empty($this->$attribute) && is_string($this->$attribute)){
  1457. return $this->$attribute;
  1458. }
  1459. $current_locale = $this->getCurrentLocale();
  1460. if(!empty($this->$attribute[$current_locale]) && is_array($this->$attribute)){
  1461. return $this->$attribute[$current_locale];
  1462. }
  1463. return $this->getAttribute($current_locale.'_'.$attribute);
  1464. }
  1465. }
  1466. if($this->_internationalize){
  1467. return $this->getAttributeByLocale($attribute, is_bool($inspect_for_callback_child_method) ? $this->getCurrentLocale() : $inspect_for_callback_child_method);
  1468. }
  1469. return null;
  1470. }
  1471. function get($attribute = null, $inspect_for_callback_child_method = true)
  1472. {
  1473. return !isset($attribute) ? $this->getAttributes($inspect_for_callback_child_method) : $this->getAttribute($attribute, $inspect_for_callback_child_method);
  1474. }
  1475. /**
  1476. * Returns an array of all the attributes with their names as keys and clones of their objects as values in case they are objects.
  1477. */
  1478. function getAttributes()
  1479. {
  1480. $attributes = array();
  1481. $available_attributes = $this->getAvailableAttributes();
  1482. foreach ($available_attributes as $available_attribute){
  1483. $attribute = $this->getAttribute($available_attribute['name']);
  1484. $attributes[$available_attribute['name']] = AK_PHP5 && is_object($attribute) ? clone($attribute) : $attribute;
  1485. }
  1486. if($this->_internationalize){
  1487. $current_locale = $this->getCurrentLocale();
  1488. foreach ($this->getInternationalizedColumns() as $column=>$languages){
  1489. if(empty($attributes[$column]) && isset($attributes[$current_locale.'_'.$column]) && in_array($current_locale,$languages)){
  1490. $attributes[$column] = $attributes[$current_locale.'_'.$column];
  1491. }
  1492. }
  1493. }
  1494. return $attributes;
  1495. }
  1496. /**
  1497. * Allows you to set all the attributes at once by passing in an array with
  1498. * keys matching the attribute names (which again matches the column names).
  1499. * Sensitive attributes can be protected from this form of mass-assignment by
  1500. * using the $this->setProtectedAttributes method. Or you can alternatively
  1501. * specify which attributes can be accessed in with the $this->setAccessibleAttributes method.
  1502. * Then all the attributes not included in that won?t be allowed to be mass-assigned.
  1503. */
  1504. function setAttributes($attributes, $override_attribute_protection = false)
  1505. {
  1506. $this->parseAkelosArgs($attributes);
  1507. if(!$override_attribute_protection){
  1508. $attributes = $this->removeAttributesProtectedFromMassAssignment($attributes);
  1509. }
  1510. if(!empty($attributes) && is_array($attributes)){
  1511. foreach ($attributes as $k=>$v){
  1512. $this->setAttribute($k, $v);
  1513. }
  1514. }
  1515. }
  1516. function removeAttributesProtectedFromMassAssignment($attributes)
  1517. {
  1518. if(!empty($this->_accessibleAttributes) && is_array($this->_accessibleAttributes) && is_array($attributes)){
  1519. foreach (array_keys($attributes) as $k){
  1520. if(!in_array($k,$this->_accessibleAttributes)){
  1521. unset($attributes[$k]);
  1522. }
  1523. }
  1524. }elseif (!empty($this->_protectedAttributes) && is_array($this->_protectedAttributes) && is_array($attributes)){
  1525. foreach (array_keys($attributes) as $k){
  1526. if(in_array($k,$this->_protectedAttributes)){
  1527. unset($attributes[$k]);
  1528. }
  1529. }
  1530. }
  1531. return $attributes;
  1532. }
  1533. /**
  1534. * The Akelos Framework has a handy way to represent combined fields.
  1535. * You can add a new attribute to your models using a printf patter to glue
  1536. * multiple parameters in a single one.
  1537. *
  1538. * For example, If we set...
  1539. * $this->addCombinedAttributeConfiguration('name', "%s %s", 'first_name', 'last_name');
  1540. * $this->addCombinedAttributeConfiguration('date', "%04d-%02d-%02d", 'year', 'month', 'day');
  1541. * $this->setAttributes('first_name=>','John','last_name=>','Smith','year=>',2005,'month=>',9,'day=>',27);
  1542. *
  1543. * $this->name // will have "John Smith" as value and
  1544. * $this->date // will be 2005-09-27
  1545. *
  1546. * On the other hand if you do
  1547. *
  1548. * $this->setAttribute('date', '2008-11-30');
  1549. *
  1550. * All the 'year', 'month' and 'day' getters will be fired (if they exist) the following attributes will be set
  1551. *
  1552. * $this->year // will be 2008
  1553. * $this->month // will be 11 and
  1554. * $this->day // will be 27
  1555. *
  1556. * Sometimes you might need a pattern for composing and another for decomposing attributes. In this case you can specify
  1557. * an array as the pattern values, where first element will be the composing pattern and second element will be used
  1558. * for decomposing.
  1559. *
  1560. * You can also specify a callback method from this object function instead of a pattern. You can also assign a callback
  1561. * for composing and another for decomposing by passing their names as an array like on the patterns.
  1562. *
  1563. * <?php
  1564. * class User extends AkActiveRecord
  1565. * {
  1566. * function User()
  1567. * {
  1568. * // You can use a multiple patterns array where "%s, %s" will be used for combining fields and "%[^,], %s" will be used
  1569. * // for decomposing fields. (as you can see you can also use regular expressions on your patterns)
  1570. * $User->addCombinedAttributeConfiguration('name', array("%s, %s","%[^,], %s"), 'last_name', 'first_name');
  1571. *
  1572. * //Here we set email_link so compose_email_link() will be triggered for building up the field and parse_email_link will
  1573. * // be used for getting the fields out
  1574. * $User->addCombinedAttributeConfiguration('email_link', array("compose_email_link","parse_email_link"), 'email', 'name');
  1575. *
  1576. * // We need to tell the ActiveRecord to load it's magic (see the example below for a simpler solution)
  1577. * $attributes = (array)func_get_args();
  1578. * return $this->init($attributes);
  1579. *
  1580. * }
  1581. * function compose_email_link()
  1582. * {
  1583. * $args = func_get_arg(0);
  1584. * return "<a href=\'mailto:{$args[\'email\']}\'>{$args[\'name\']}</a>";
  1585. * }
  1586. * function parse_email_link($email_link)
  1587. * {
  1588. * $results = sscanf($email_link, "<a href=\'mailto:%[^\']\'>%[^<]</a>");
  1589. * return array(\'email\'=>$results[0],\'name\'=>$results[1]);
  1590. * }
  1591. *
  1592. * }
  1593. * ?>
  1594. *
  1595. * You can also simplify your live by declaring the combined attributes as a class variable like:
  1596. * <?php
  1597. * class User extends ActiveRecord
  1598. * {
  1599. * var $combined_attributes array(
  1600. * array('name', array("%s, %s","%[^,], %s"), 'last_name', 'first_name')
  1601. * array('email_link', array("compose_email_link","parse_email_link"), 'email', 'name')
  1602. * );
  1603. *
  1604. * // ....
  1605. * }
  1606. * ?>
  1607. *
  1608. * This way you can get rid calling the parent constructor
  1609. *
  1610. * @param $attribute
  1611. * @param $mapping
  1612. */
  1613. function addCombinedAttributeConfiguration($attribute)
  1614. {
  1615. $args = is_array($attribute) ? $attribute : func_get_args();
  1616. $columns = array_slice($args,2);
  1617. $invalid_columns = array();
  1618. foreach ($columns as $colum){
  1619. if(!$this->hasAttribute($colum)){
  1620. $invalid_columns[] = $colum;
  1621. }
  1622. }
  1623. if(!empty($invalid_columns)){
  1624. trigger_error(Ak::t('There was an error while setting the composed field "%field_name", the following mapping column/s "%columns" do not exist',
  1625. array('%field_name'=>$args[0],'%columns'=>join(', ',$invalid_columns))), E_USER_ERROR);
  1626. }else{
  1627. $attribute = array_shift($args);
  1628. $this->_combinedAttributes[$attribute] = $args;
  1629. $this->composeCombinedAttribute($attribute);
  1630. }
  1631. }
  1632. /**
  1633. * Use a printf pattern to glue sub-attributes into an attribute. Sub-attribute getters will are fired (if they exist).
  1634. */
  1635. function composeCombinedAttributes()
  1636. {
  1637. if(!empty($this->_combinedAttributes)){
  1638. $attributes = array_keys($this->_combinedAttributes);
  1639. foreach ($attributes as $attribute){
  1640. $this->composeCombinedAttribute($attribute);
  1641. }
  1642. }
  1643. }
  1644. function composeCombinedAttribute($combined_attribute)
  1645. {
  1646. if($this->isCombinedAttribute($combined_attribute)){
  1647. $config = $this->_combinedAttributes[$combined_attribute];
  1648. $pattern = array_shift($config);
  1649. $pattern = is_array($pattern) ? $pattern[0] : $pattern;
  1650. $got = array();
  1651. foreach ($config as $attribute){
  1652. if(isset($this->$attribute)){
  1653. $got[$attribute] = $this->getAttribute($attribute);
  1654. }
  1655. }
  1656. if(count($got) === count($config)){
  1657. $this->$combined_attribute = method_exists($this, $pattern) ? $this->{$pattern}($got) : vsprintf($pattern, $got);
  1658. }
  1659. }
  1660. }
  1661. function _getCombinedAttributesWhereThisAttributeIsUsed($attribute)
  1662. {
  1663. $result = array();
  1664. foreach ($this->_combinedAttributes as $combined_attribute=>$settings){
  1665. if(in_array($attribute,$settings)){
  1666. $result[] = $combined_attribute;
  1667. }
  1668. }
  1669. return $result;
  1670. }
  1671. function requiredForCombination($attribute)
  1672. {
  1673. foreach ($this->_combinedAttributes as $settings){
  1674. if(in_array($attribute,$settings)){
  1675. return true;
  1676. }
  1677. }
  1678. return false;
  1679. }
  1680. function hasCombinedAttributes()
  1681. {
  1682. return count($this->getCombinedSubattributes()) === 0 ? false :true;
  1683. }
  1684. function getCombinedSubattributes($attribute)
  1685. {
  1686. $result = array();
  1687. if(is_array($this->_combinedAttributes[$attribute])){
  1688. $attributes = $this->_combinedAttributes[$attribute];
  1689. array_shift($attributes);
  1690. foreach ($attributes as $attribute_to_check){
  1691. if(isset($this->_combinedAttributes[$attribute_to_check])){
  1692. $result[] = $attribute_to_check;
  1693. }
  1694. }
  1695. }
  1696. return $result;
  1697. }
  1698. /**
  1699. * Use a scanf pattern match to break an attribute down into it's sub-attributes.
  1700. */
  1701. function decomposeCombinedAttributes()
  1702. {
  1703. if(!empty($this->_combinedAttributes)){
  1704. $attributes = array_keys($this->_combinedAttributes);
  1705. foreach ($attributes as $attribute){
  1706. $this->decomposeCombinedAttribute($attribute);
  1707. }
  1708. }
  1709. }
  1710. function decomposeCombinedAttribute($combined_attribute, $used_on_combined_fields = false)
  1711. {
  1712. if(isset($this->$combined_attribute) && $this->isCombinedAttribute($combined_attribute)){
  1713. $config = $this->_combinedAttributes[$combined_attribute];
  1714. $pattern = array_shift($config);
  1715. $pattern = is_array($pattern) ? $pattern[1] : $pattern;
  1716. if(method_exists($this, $pattern)){
  1717. $pieces = $this->{$pattern}($this->$combined_attribute);
  1718. if(is_array($pieces)){
  1719. foreach ($pieces as $k=>$v){
  1720. $is_combined = $this->isCombinedAttribute($k);
  1721. if($is_combined){
  1722. $this->decomposeCombinedAttribute($k);
  1723. }
  1724. $this->setAttribute($k, $v, true, !$is_combined);
  1725. }
  1726. if($is_combined && !$used_on_combined_fields){
  1727. $combined_attributes_contained_on_this_attribute = $this->getCombinedSubattributes($combined_attribute);
  1728. if(count($combined_attributes_contained_on_this_attribute)){
  1729. $this->decomposeCombinedAttribute($combined_attribute, true);
  1730. }
  1731. }
  1732. }
  1733. }else{
  1734. $got = sscanf($this->$combined_attribute, $pattern);
  1735. for ($x=0; $x<count($got); $x++){
  1736. $attribute = $config[$x];
  1737. $is_combined = $this->isCombinedAttribute($attribute);
  1738. if($is_combined){
  1739. $this->decomposeCombinedAttribute($attribute);
  1740. }
  1741. $this->setAttribute($attribute, $got[$x], true, !$is_combined);
  1742. }
  1743. }
  1744. }
  1745. }
  1746. /**
  1747. * Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.
  1748. */
  1749. function cloneRecord()
  1750. {
  1751. $model_name = $this->getModelName();
  1752. $attributes = $this->getAttributesBeforeTypeCast();
  1753. if(isset($attributes[$this->getPrimaryKey()])){
  1754. unset($attributes[$this->getPrimaryKey()]);
  1755. }
  1756. return new $model_name($attributes);
  1757. }
  1758. /**
  1759. * Initializes the attribute to zero if null and subtracts one. Only makes sense for number-based attributes. Returns attribute value.
  1760. */
  1761. function decrementAttribute($attribute)
  1762. {
  1763. if(!isset($this->$attribute)){
  1764. $this->setAttribute($attribute, 0);
  1765. return 0;
  1766. }else {
  1767. $value = $this->getAttribute($attribute) -1;
  1768. $this->setAttribute($attribute, $value);
  1769. return $value;
  1770. }
  1771. }
  1772. /**
  1773. * Decrements the attribute and saves the record.
  1774. */
  1775. function decrementAndSaveAttribute($attribute)
  1776. {
  1777. $value = $this->decrementAttribute($attribute);
  1778. if($this->updateAttribute($attribute, $value)){
  1779. return $value;
  1780. }
  1781. return false;
  1782. }
  1783. /**
  1784. * Initializes the attribute to zero if null and adds one. Only makes sense for number-based attributes. Returns attribute value.
  1785. */
  1786. function incrementAttribute($attribute)
  1787. {
  1788. if(!isset($this->$attribute)){
  1789. $this->setAttribute($attribute, 0);
  1790. return 0;
  1791. }else {
  1792. $value = $this->getAttribute($attribute) +1;
  1793. $this->setAttribute($attribute, $value);
  1794. return $value;
  1795. }
  1796. }
  1797. /**
  1798. * Increments the attribute and saves the record.
  1799. */
  1800. function incrementAndSaveAttribute($attribute)
  1801. {
  1802. $value = $this->incrementAttribute($attribute);
  1803. if($this->updateAttribute($attribute, $value)){
  1804. return $value;
  1805. }
  1806. return false;
  1807. }
  1808. /**
  1809. * Returns true if this object hasn't been saved yet that is, a record for the object doesn't exist yet.
  1810. */
  1811. function isNewRecord()
  1812. {
  1813. if(!isset($this->_newRecord) && !isset($this->{$this->getPrimaryKey()})){
  1814. $this->_newRecord = true;
  1815. }
  1816. return $this->_newRecord;
  1817. }
  1818. /**
  1819. * This function is usefull in case you need to know if attribtes have been assigned to an object.
  1820. */
  1821. function hasAttributesDefined()
  1822. {
  1823. $attributes = join('',$this->getAttributes());
  1824. return empty($attributes);
  1825. }
  1826. /**
  1827. * Reloads the attributes of this object from the database.
  1828. */
  1829. function reload()
  1830. {
  1831. /**
  1832. * @todo clear cache
  1833. */
  1834. if($object = $this->find($this->getId())){
  1835. $this->setAttributes($object->getAttributes(), true);
  1836. return true;
  1837. }else {
  1838. return false;
  1839. }
  1840. }
  1841. /**
  1842. * - No record exists: Creates a new record with values matching those of the object attributes.
  1843. * - A record does exist: Updates the record with values matching those of the object attributes.
  1844. */
  1845. function save($validate = true)
  1846. {
  1847. if($this->isFrozen()){
  1848. return false;
  1849. }
  1850. $result = false;
  1851. $this->transactionStart();
  1852. if($this->beforeSave() && $this->notifyObservers('beforeSave')){
  1853. $result = $this->createOrUpdate($validate);
  1854. if(!$this->transactionHasFailed()){
  1855. if(!$this->afterSave()){
  1856. $this->transactionFail();
  1857. }else{
  1858. if(!$this->notifyObservers('afterSave')){
  1859. $this->transactionFail();
  1860. }
  1861. }
  1862. }
  1863. }else{
  1864. $this->transactionFail();
  1865. }
  1866. $result = $this->transactionHasFailed() ? false : $result;
  1867. $this->transactionComplete();
  1868. return $result;
  1869. }
  1870. function createOrUpdate($validate = true)
  1871. {
  1872. if($validate && !$this->isValid() || !($this->isNewRecord() ? $this->afterValidationOnCreate() : $this->afterValidationOnUpdate())){
  1873. $this->transactionFail();
  1874. return false;
  1875. }
  1876. return $this->isNewRecord() ? $this->_create() : $this->_update();
  1877. }
  1878. /**
  1879. * Turns an attribute that?s currently true into false and vice versa. Returns attribute value.
  1880. */
  1881. function toggleAttribute($attribute)
  1882. {
  1883. $value = $this->getAttribute($attribute);
  1884. $new_value = $value ? false : true;
  1885. $this->setAttribute($attribute, $new_value);
  1886. return $new_value;
  1887. }
  1888. /**
  1889. * Toggles the attribute and saves the record.
  1890. */
  1891. function toggleAttributeAndSave($attribute)
  1892. {
  1893. $value = $this->toggleAttribute($attribute);
  1894. if($this->updateAttribute($attribute, $value)){
  1895. return $value;
  1896. }
  1897. return null;
  1898. }
  1899. /**
  1900. * 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.
  1901. */
  1902. function getId()
  1903. {
  1904. return $this->{$this->getPrimaryKey()};
  1905. }
  1906. function quotedId()
  1907. {
  1908. return $this->castAttributeForDatabase($this->getPrimaryKey(), $this->getId());
  1909. }
  1910. function setId($value)
  1911. {
  1912. if($this->isFrozen()){
  1913. return false;
  1914. }
  1915. $pk = $this->getPrimaryKey();
  1916. $this->$pk = $value;
  1917. return true;
  1918. }
  1919. function getAttributesBeforeTypeCast()
  1920. {
  1921. $attributes_array = array();
  1922. $available_attributes = $this->getAvailableAttributes();
  1923. foreach ($available_attributes as $attribute){
  1924. $attribute_value = $this->getAttributeBeforeTypeCast($attribute['name']);
  1925. if(!empty($attribute_value)){
  1926. $attributes_array[$attribute['name']] = $attribute_value;
  1927. }
  1928. }
  1929. return $attributes_array;
  1930. }
  1931. function getAttributeBeforeTypeCast($attribute)
  1932. {
  1933. if(isset($this->{$attribute.'_before_type_cast'})){
  1934. return $this->{$attribute.'_before_type_cast'};
  1935. }
  1936. return null;
  1937. }
  1938. /**
  1939. * unused function; misleading named attributesFromColumnDefinition
  1940. */
  1941. function filterForeignAndProtectedAttributes($attributes)
  1942. {
  1943. $filtered_attributes = array();
  1944. if(is_array($attributes)){
  1945. foreach ($attributes as $k=>$v){
  1946. if($this->hasAttribute($k) && !in_array($k, $this->_protectedAttributes)){
  1947. $filtered_attributes[$k] = $v;
  1948. }
  1949. }
  1950. }
  1951. return $filtered_attributes;
  1952. }
  1953. /**
  1954. * Initializes the attributes array with keys matching the columns from the linked table and
  1955. * the values matching the corresponding default value of that column, so
  1956. * that a new instance, or one populated from a passed-in array, still has all the attributes
  1957. * that instances loaded from the database would.
  1958. */
  1959. function attributesFromColumnDefinition()
  1960. {
  1961. $attributes = array();
  1962. foreach ((array)$this->getColumns() as $column_name=>$column_settings){
  1963. if (!isset($column_settings['primaryKey']) && isset($column_settings['hasDefault'])) {
  1964. $attributes[$column_name] = $column_settings['defaultValue'];
  1965. } else {
  1966. $attributes[$column_name] = null;
  1967. }
  1968. }
  1969. return $attributes;
  1970. }
  1971. /**
  1972. * Returns the primary key field.
  1973. */
  1974. function getPrimaryKey()
  1975. {
  1976. if(!isset($this->_primaryKey)){
  1977. $this->setPrimaryKey();
  1978. }
  1979. return $this->_primaryKey;
  1980. }
  1981. /**
  1982. * Defines the primary key field ? can be overridden in subclasses.
  1983. */
  1984. function setPrimaryKey($primary_key = 'id')
  1985. {
  1986. if(!$this->hasColumn($primary_key)){
  1987. 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);
  1988. }else {
  1989. $this->_primaryKey = $primary_key;
  1990. }
  1991. }
  1992. /**
  1993. * 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.
  1994. */
  1995. function setSerializeAttribute($attr_name, $class_name = null)
  1996. {
  1997. if($this->hasColumn($attr_name)){
  1998. $this->_serializedAttributes[$attr_name] = $class_name;
  1999. }
  2000. }
  2001. /**
  2002. * Returns an array of all the attributes that have been specified for serialization as keys and the objects as values.
  2003. */
  2004. function getSerializedAttributes()
  2005. {
  2006. return isset($this->_serializedAttributes) ? $this->_serializedAttributes : array();
  2007. }
  2008. function t($string, $array = null)
  2009. {
  2010. return Ak::t($string, $array, AkInflector::underscore($this->getModelName()));
  2011. }
  2012. function getAvailableCombinedAttributes()
  2013. {
  2014. $combined_attributes = array();
  2015. foreach ($this->_combinedAttributes as $attribute=>$details){
  2016. $combined_attributes[$attribute] = array('name'=>$attribute, 'type'=>'string', 'path' => array_shift($details), 'uses'=>$details);
  2017. }
  2018. return !empty($this->_combinedAttributes) && is_array($this->_combinedAttributes) ? $combined_attributes : array();
  2019. }
  2020. function getAvailableAttributes()
  2021. {
  2022. return array_merge($this->getColumns(), $this->getAvailableCombinedAttributes());
  2023. }
  2024. function getColumnNames()
  2025. {
  2026. if(empty($this->_columnNames)){
  2027. $columns = $this->getColumns();
  2028. foreach ($columns as $column_name=>$details){
  2029. $this->_columnNames[$column_name] = isset($details->columnName) ? $this->t($details->columnName) : $this->getAttributeCaption($column_name);
  2030. }
  2031. }
  2032. return $this->_columnNames;
  2033. }
  2034. function getAttributeCaption($attribute)
  2035. {
  2036. return $this->t(AkInflector::humanize($attribute));
  2037. }
  2038. /**#@+
  2039. * Database reflection methods
  2040. */
  2041. function getTableName($modify_for_associations = true)
  2042. {
  2043. if(!isset($this->_tableName)){
  2044. // We check if we are on a inheritance Table Model
  2045. $this->getClassForDatabaseTableMapping();
  2046. if(!isset($this->_tableName)){
  2047. $this->setTableName();
  2048. }
  2049. }
  2050. if($modify_for_associations && isset($this->_associationTablePrefixes[$this->_tableName])){
  2051. return $this->_associationTablePrefixes[$this->_tableName];
  2052. }
  2053. return $this->_tableName;
  2054. }
  2055. function setTableName($table_name = null, $check_for_existence = AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES, $check_mode = false)
  2056. {
  2057. static $available_tables;
  2058. if(empty($table_name)){
  2059. $table_name = AkInflector::tableize($this->getModelName());
  2060. }
  2061. if($check_for_existence){
  2062. if(!isset($available_tables) || $check_mode){
  2063. if(!isset($this->_db)){
  2064. $this->setConnection();
  2065. }
  2066. if(empty($_SESSION['__activeRecordColumnsSettingsCache']['available_tables']) ||
  2067. !AK_ACTIVE_RECORD_ENABLE_PERSISTENCE){
  2068. $_SESSION['__activeRecordColumnsSettingsCache']['available_tables'] = $this->_db->MetaTables();
  2069. }
  2070. $available_tables = $_SESSION['__activeRecordColumnsSettingsCache']['available_tables'];
  2071. }
  2072. if(!in_array($table_name,(array)$available_tables)){
  2073. if(!$check_mode){
  2074. trigger_error(Ak::t('Unable to set "%table_name" table for the model "%model".'.
  2075. ' There is no "%table_name" available into current database layout.'.
  2076. ' Set AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES constant to false in order to'.
  2077. ' avoid table name validation',array('%table_name'=>$table_name,'%model'=>$this->getModelName())),E_USER_WARNING);
  2078. }
  2079. return false;
  2080. }
  2081. }
  2082. $this->_tableName = $table_name;
  2083. return true;
  2084. }
  2085. /**
  2086. * Gets information from the database engine about a single table
  2087. */
  2088. function _databaseTableInternals($table)
  2089. {
  2090. if(empty($_SESSION['__activeRecordColumnsSettingsCache']['database_table_'.$table.'_internals']) || !AK_ACTIVE_RECORD_ENABLE_PERSISTENCE){
  2091. $_SESSION['__activeRecordColumnsSettingsCache']['database_table_'.$table.'_internals'] = $this->_db->MetaColumns($table);
  2092. }
  2093. $cache[$table] = $_SESSION['__activeRecordColumnsSettingsCache']['database_table_'.$table.'_internals'];
  2094. return $cache[$table];
  2095. }
  2096. function _getDatabaseType()
  2097. {
  2098. if(strstr($this->_db->databaseType,'mysql')){
  2099. return 'mysql';
  2100. }elseif(strstr($this->_db->databaseType,'sqlite')){
  2101. return 'sqlite';
  2102. }elseif(strstr($this->_db->databaseType,'post')){
  2103. return 'postgre';
  2104. }else{
  2105. return 'unknown';
  2106. }
  2107. }
  2108. /**
  2109. * If is the first time we use a model this function will run the installer for the model if it exists
  2110. */
  2111. function _runCurrentModelInstallerIfExists(&$column_objects)
  2112. {
  2113. static $installed_models = array();
  2114. if(!defined('AK_AVOID_AUTOMATIC_ACTIVE_RECORD_INSTALLERS') && !in_array($this->getModelName(), $installed_models)){
  2115. $installed_models[] = $this->getModelName();
  2116. require_once(AK_LIB_DIR.DS.'AkInstaller.php');
  2117. $installer_name = $this->getModelName().'Installer';
  2118. $installer_file = AK_APP_DIR.DS.'installers'.DS.AkInflector::underscore($installer_name).'.php';
  2119. if(file_exists($installer_file)){
  2120. require_once($installer_file);
  2121. if(class_exists($installer_name)){
  2122. $Installer = new $installer_name();
  2123. if(method_exists($Installer,'install')){
  2124. $Installer->install();
  2125. $column_objects = $this->_databaseTableInternals($this->getTableName());
  2126. return !empty($column_objects);
  2127. }
  2128. }
  2129. }
  2130. }
  2131. return false;
  2132. }
  2133. /**
  2134. * Returns an array of column objects for the table associated with this class.
  2135. */
  2136. function getColumns()
  2137. {
  2138. if(empty($this->_columns)){
  2139. $this->_columns = $this->getColumnSettings();
  2140. }
  2141. return $this->_columns;
  2142. }
  2143. function getColumnSettings()
  2144. {
  2145. if(empty($this->_columnsSettings)){
  2146. $this->loadColumnsSettings();
  2147. $this->initiateColumnsToNull();
  2148. }
  2149. return isset($this->_columnsSettings) ? $this->_columnsSettings : array();
  2150. }
  2151. function loadColumnsSettings()
  2152. {
  2153. if(is_null($this->_db)){
  2154. $this->setConnection();
  2155. }
  2156. $this->_columnsSettings = $this->_getPersistedTableColumnSettings();
  2157. if(empty($this->_columnsSettings) || !AK_ACTIVE_RECORD_ENABLE_PERSISTENCE){
  2158. if(empty($this->_dataDictionary)){
  2159. $this->_dataDictionary =& NewDataDictionary($this->_db);
  2160. }
  2161. $column_objects = $this->_databaseTableInternals($this->getTableName());
  2162. if( !isset($this->_avoidTableNameValidation) &&
  2163. !is_array($column_objects) &&
  2164. !$this->_runCurrentModelInstallerIfExists($column_objects)){
  2165. trigger_error(Ak::t('Ooops! Could not fetch details for the table %table_name.', array('%table_name'=>$this->getTableName())), E_USER_ERROR);
  2166. return false;
  2167. }elseif(is_array($column_objects)){
  2168. foreach (array_keys($column_objects) as $k){
  2169. $this->setColumnSettings($column_objects[$k]->name, $column_objects[$k]);
  2170. }
  2171. }
  2172. if(!empty($this->_columnsSettings)){
  2173. $this->_persistTableColumnSettings();
  2174. }
  2175. }
  2176. return isset($this->_columnsSettings) ? $this->_columnsSettings : array();
  2177. }
  2178. function setColumnSettings($column_name, $column_object)
  2179. {
  2180. $this->_columnsSettings[$column_name] = array();
  2181. $this->_columnsSettings[$column_name]['name'] = $column_object->name;
  2182. if($this->_internationalize && $this->_isInternationalizeCandidate($column_object->name)){
  2183. $this->_addInternationalizedColumn($column_object->name);
  2184. }
  2185. $this->_columnsSettings[$column_name]['type'] = $this->getAkelosDataType($column_object);
  2186. if(!empty($column_object->primary_key)){
  2187. $this->_primaryKey = empty($this->_primaryKey) ? $column_object->name : $this->_primaryKey;
  2188. $this->_columnsSettings[$column_name]['primaryKey'] = true;
  2189. }
  2190. if(!empty($column_object->auto_increment)){
  2191. $this->_columnsSettings[$column_name]['autoIncrement'] = true;
  2192. }
  2193. if(!empty($column_object->has_default)){
  2194. $this->_columnsSettings[$column_name]['hasDefault'] = true;
  2195. }
  2196. if(!empty($column_object->not_null)){
  2197. $this->_columnsSettings[$column_name]['notNull'] = true;
  2198. }
  2199. if(!empty($column_object->max_length) && $column_object->max_length > 0){
  2200. $this->_columnsSettings[$column_name]['maxLength'] = $column_object->max_length;
  2201. }
  2202. if(isset($column_object->default_value)){
  2203. $this->_columnsSettings[$column_name]['defaultValue'] = $column_object->default_value;
  2204. }
  2205. }
  2206. /**
  2207. * Resets all the cached information about columns, which will cause they to be reloaded on the next request.
  2208. */
  2209. function resetColumnInformation()
  2210. {
  2211. if(isset($_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName()])){
  2212. unset($_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName()]);
  2213. }
  2214. $this->_clearPersitedColumnSettings();
  2215. $this->_columnNames = $this->_columns = $this->_columnsSettings = $this->_contentColumns = array();
  2216. }
  2217. function _getColumnsSettings()
  2218. {
  2219. return $_SESSION['__activeRecordColumnsSettingsCache'];
  2220. }
  2221. function _getModelColumnSettings()
  2222. {
  2223. return $_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName()];
  2224. }
  2225. function _persistTableColumnSettings()
  2226. {
  2227. $_SESSION['__activeRecordColumnsSettingsCache'][$this->getModelName().'_column_settings'] = $this->_columnsSettings;
  2228. }
  2229. function _getPersistedTableColumnSettings()
  2230. {
  2231. $model_name = $this->getModelName();
  2232. if(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA && !isset($_SESSION['__activeRecordColumnsSettingsCache']) && AK_CACHE_HANDLER > 0){
  2233. $this->_loadPersistedColumnSetings();
  2234. }
  2235. return isset($_SESSION['__activeRecordColumnsSettingsCache'][$model_name.'_column_settings']) ?
  2236. $_SESSION['__activeRecordColumnsSettingsCache'][$model_name.'_column_settings'] : false;
  2237. }
  2238. function _clearPersitedColumnSettings()
  2239. {
  2240. if(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA && AK_CACHE_HANDLER > 0){
  2241. $Cache =& Ak::cache();
  2242. $Cache->init(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE);
  2243. $Cache->clean('AkActiveRecord');
  2244. }
  2245. }
  2246. function _savePersitedColumnSettings()
  2247. {
  2248. if(isset($_SESSION['__activeRecordColumnsSettingsCache'])){
  2249. $Cache =& Ak::cache();
  2250. $Cache->init(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE);
  2251. $Cache->save(serialize($_SESSION['__activeRecordColumnsSettingsCache']), 'active_record_db_cache', 'AkActiveRecord');
  2252. }
  2253. }
  2254. function _loadPersistedColumnSetings()
  2255. {
  2256. if(!isset($_SESSION['__activeRecordColumnsSettingsCache'])){
  2257. $Cache =& Ak::cache();
  2258. $Cache->init(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA_LIFE);
  2259. if($serialized_column_settings = $Cache->get('active_record_db_cache', 'AkActiveRecord') && !empty($serialized_column_settings)){
  2260. $_SESSION['__activeRecordColumnsSettingsCache'] = @unserialize($serialized_column_settings);
  2261. }elseif(AK_ACTIVE_RECORD_CACHE_DATABASE_SCHEMA){
  2262. register_shutdown_function(array($this,'_savePersitedColumnSettings'));
  2263. }
  2264. }else{
  2265. $_SESSION['__activeRecordColumnsSettingsCache'] = array();
  2266. }
  2267. }
  2268. /**#@-*/
  2269. /**#@+
  2270. * Active Record localization support methods
  2271. */
  2272. function _isInternationalizeCandidate($column_name)
  2273. {
  2274. $pos = strpos($column_name,'_');
  2275. return $pos === 2 && in_array(substr($column_name,0,$pos),$this->getAvaliableLocales());
  2276. }
  2277. function _addInternationalizedColumn($column_name)
  2278. {
  2279. $this->_columnsSettings[$column_name]['i18n'] = true;
  2280. }
  2281. function getInternationalizedColumns()
  2282. {
  2283. static $cache;
  2284. $model = $this->getModelName();
  2285. $available_locales = $this->getAvaliableLocales();
  2286. if(empty($cache[$model])){
  2287. $cache[$model] = array();
  2288. foreach ($this->getColumnSettings() as $column_name=>$details){
  2289. if(!empty($details['i18n'])){
  2290. $_tmp_pos = strpos($column_name,'_');
  2291. $column = substr($column_name,$_tmp_pos+1);
  2292. $lang = substr($column_name,0,$_tmp_pos);
  2293. if(in_array($lang, $available_locales)){
  2294. $cache[$model][$column] = empty($cache[$model][$column]) ? array($lang) :
  2295. array_merge($cache[$model][$column] ,array($lang));
  2296. }
  2297. }
  2298. }
  2299. }
  2300. return $cache[$model];
  2301. }
  2302. function getAvaliableLocales()
  2303. {
  2304. static $available_locales;
  2305. if(empty($available_locales)){
  2306. if(defined('AK_ACTIVE_RECORD_DEFAULT_LOCALES')){
  2307. $available_locales = Ak::stringToArray(AK_ACTIVE_RECORD_DEFAULT_LOCALES);
  2308. }else{
  2309. $available_locales = Ak::langs();
  2310. }
  2311. }
  2312. return $available_locales;
  2313. }
  2314. function getCurrentLocale()
  2315. {
  2316. static $current_locale;
  2317. if(empty($current_locale)){
  2318. $current_locale = Ak::lang();
  2319. $available_locales = $this->getAvaliableLocales();
  2320. if(!in_array($current_locale, $available_locales)){
  2321. $current_locale = array_shift($available_locales);
  2322. }
  2323. }
  2324. return $current_locale;
  2325. }
  2326. function getAttributeByLocale($attribute, $locale)
  2327. {
  2328. $internationalizable_columns = $this->getInternationalizedColumns();
  2329. if(!empty($internationalizable_columns[$attribute]) && is_array($internationalizable_columns[$attribute]) && in_array($locale, $internationalizable_columns[$attribute])){
  2330. return $this->getAttribute($locale.'_'.$attribute);
  2331. }
  2332. }
  2333. function getAttributeLocales($attribute)
  2334. {
  2335. $attribute_locales = array();
  2336. foreach ($this->getAvaliableLocales() as $locale){
  2337. if($this->hasColumn($locale.'_'.$attribute)){
  2338. $attribute_locales[$locale] = $this->getAttributeByLocale($attribute, $locale);
  2339. }
  2340. }
  2341. return $attribute_locales;
  2342. }
  2343. function setAttributeByLocale($attribute, $value, $locale)
  2344. {
  2345. $internationalizable_columns = $this->getInternationalizedColumns();
  2346. if($this->_isInternationalizeCandidate($locale.'_'.$attribute) && !empty($internationalizable_columns[$attribute]) && is_array($internationalizable_columns[$attribute]) && in_array($locale, $internationalizable_columns[$attribute])){
  2347. $this->setAttribute($locale.'_'.$attribute, $value);
  2348. }
  2349. }
  2350. function setAttributeLocales($attribute, $values = array())
  2351. {
  2352. foreach ($values as $locale=>$value){
  2353. $this->setAttributeByLocale($attribute, $value, $locale);
  2354. }
  2355. }
  2356. function _delocalizeAttribute($attribute)
  2357. {
  2358. return $this->_isInternationalizeCandidate($attribute) ? substr($attribute,3) : $attribute;
  2359. }
  2360. /**#@-*/
  2361. /**
  2362. * Adds an internationalized attribute to an array containing other locales for the same column name
  2363. *
  2364. * Example:
  2365. * es_title and en_title will be available unser title = array('es'=>'...', 'en' => '...')
  2366. */
  2367. function _groupInternationalizedAttribute($attribute, $value)
  2368. {
  2369. if($this->_internationalize && $this->_isInternationalizeCandidate($attribute)){
  2370. if(!empty($this->$attribute)){
  2371. $_tmp_pos = strpos($attribute,'_');
  2372. $column = substr($attribute,$_tmp_pos+1);
  2373. $lang = substr($attribute,0,$_tmp_pos);
  2374. $this->$column = empty($this->$column) ? array() : $this->$column;
  2375. if(empty($this->$column) || (!empty($this->$column) && is_array($this->$column))){
  2376. $this->$column = empty($this->$column) ? array($lang=>$value) : array_merge($this->$column,array($lang=>$value));
  2377. }
  2378. }
  2379. }
  2380. }
  2381. function initiateAttributeToNull($attribute)
  2382. {
  2383. if(!isset($this->$attribute)){
  2384. $this->$attribute = null;
  2385. }
  2386. }
  2387. function initiateColumnsToNull()
  2388. {
  2389. if(isset($this->_columnsSettings) && is_array($this->_columnsSettings)){
  2390. array_map(array(&$this,'initiateAttributeToNull'),array_keys($this->_columnsSettings));
  2391. }
  2392. }
  2393. /**
  2394. * Akelos data types are mapped to phpAdodb data types
  2395. *
  2396. * Returns the Akelos data type for an Adodb Column Object
  2397. *
  2398. * 'C'=>'string', // Varchar, capped to 255 characters.
  2399. * 'X' => 'text' // Larger varchar, capped to 4000 characters (to be compatible with Oracle).
  2400. * 'XL' => 'text' // For Oracle, returns CLOB, otherwise the largest varchar size.
  2401. *
  2402. * 'C2' => 'string', // Multibyte varchar
  2403. * 'X2' => 'string', // Multibyte varchar (largest size)
  2404. *
  2405. * 'B' => 'binary', // BLOB (binary large object)
  2406. *
  2407. * 'D' => array('date', 'datetime'), // Date (some databases do not support this, and we return a datetime type)
  2408. * 'T' => array('datetime', 'timestamp'), //Datetime or Timestamp
  2409. * 'L' => 'boolean', // Integer field suitable for storing booleans (0 or 1)
  2410. * 'I' => // Integer (mapped to I4)
  2411. * 'I1' => 'integer', // 1-byte integer
  2412. * 'I2' => 'integer', // 2-byte integer
  2413. * 'I4' => 'integer', // 4-byte integer
  2414. * 'I8' => 'integer', // 8-byte integer
  2415. * 'F' => 'float', // Floating point number
  2416. * 'N' => 'integer' // Numeric or decimal number
  2417. *
  2418. * @return string One of this 'string','text','integer','float','datetime','timestamp',
  2419. * 'time', 'name','date', 'binary', 'boolean'
  2420. */
  2421. function getAkelosDataType(&$adodb_column_object)
  2422. {
  2423. $config_var_name = AkInflector::variablize($adodb_column_object->name.'_data_type');
  2424. if(!empty($this->{$config_var_name})){
  2425. return $this->{$config_var_name};
  2426. }
  2427. if(stristr($adodb_column_object->type, 'BLOB')){
  2428. return 'binary';
  2429. }
  2430. if(!empty($adodb_column_object->auto_increment)) {
  2431. return 'serial';
  2432. }
  2433. $meta_type = $this->_dataDictionary->MetaType($adodb_column_object);
  2434. $adodb_data_types = array(
  2435. 'C'=>'string', // Varchar, capped to 255 characters.
  2436. 'X' => 'text', // Larger varchar, capped to 4000 characters (to be compatible with Oracle).
  2437. 'XL' => 'text', // For Oracle, returns CLOB, otherwise the largest varchar size.
  2438. 'C2' => 'string', // Multibyte varchar
  2439. 'X2' => 'string', // Multibyte varchar (largest size)
  2440. 'B' => 'binary', // BLOB (binary large object)
  2441. 'D' => array('datetime', 'date'), // Date (some databases do not support this, so we return a datetime type)
  2442. 'T' => array('datetime', 'timestamp'), //Datetime or Timestamp
  2443. 'L' => 'boolean', // Integer field suitable for storing booleans (0 or 1)
  2444. 'R' => 'serial', // Serial Integer
  2445. 'I' => 'integer', // Integer (mapped to I4)
  2446. 'I1' => 'integer', // 1-byte integer
  2447. 'I2' => 'integer', // 2-byte integer
  2448. 'I4' => 'integer', // 4-byte integer
  2449. 'I8' => 'integer', // 8-byte integer
  2450. 'F' => 'float', // Floating point number
  2451. 'N' => 'integer' // Numeric or decimal number
  2452. );
  2453. $result = !isset($adodb_data_types[$meta_type]) ?
  2454. 'string' :
  2455. (is_array($adodb_data_types[$meta_type]) ? $adodb_data_types[$meta_type][0] : $adodb_data_types[$meta_type]);
  2456. if($result == 'text'){
  2457. 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 )){
  2458. return 'string';
  2459. }
  2460. }
  2461. if($this->_getDatabaseType() == 'mysql'){
  2462. if($result == 'integer' && (int)$adodb_column_object->max_length === 1 &&
  2463. stristr($adodb_column_object->type, 'TINYINT')){
  2464. return 'boolean';
  2465. }
  2466. }elseif($this->_getDatabaseType() == 'postgre'){
  2467. if($adodb_column_object->type == 'timestamp' || $result == 'datetime'){
  2468. $adodb_column_object->max_length = 19;
  2469. }
  2470. if($result == 'boolean' && (int)$adodb_column_object->max_length !== 1 && stristr($adodb_column_object->type, 'NUMERIC')){
  2471. return 'integer';
  2472. }
  2473. }elseif($this->_getDatabaseType() == 'sqlite'){
  2474. if($result == 'integer' && (int)$adodb_column_object->max_length === 1 && stristr($adodb_column_object->type, 'TINYINT')){
  2475. return 'boolean';
  2476. }elseif($result == 'integer' && stristr($adodb_column_object->type, 'DOUBLE')){
  2477. return 'float';
  2478. }
  2479. }
  2480. if($result == 'datetime' && substr($adodb_column_object->name,-3) == '_on'){
  2481. $result = 'date';
  2482. }
  2483. return $result;
  2484. }
  2485. /**
  2486. * This method retrieves current class name that will be used to map
  2487. * your database to this object.
  2488. */
  2489. function getClassForDatabaseTableMapping()
  2490. {
  2491. $class_name = get_class($this);
  2492. if(is_subclass_of($this,'akactiverecord') || is_subclass_of($this,'AkActiveRecord')){
  2493. $parent_class = get_parent_class($this);
  2494. while (substr(strtolower($parent_class),-12) != 'activerecord'){
  2495. $class_name = $parent_class;
  2496. $parent_class = get_parent_class($parent_class);
  2497. }
  2498. }
  2499. $class_name = $this->_getModelName($class_name);
  2500. // This is an Active Record Inheritance so we set current table to parent table.
  2501. if(!empty($class_name) && strtolower($class_name) != 'activerecord'){
  2502. $this->_inheritanceClassName = $class_name;
  2503. @$this->setTableName(AkInflector::tableize($class_name), false);
  2504. }
  2505. return $class_name;
  2506. }
  2507. function getDisplayField()
  2508. {
  2509. return empty($this->displayField) && $this->hasAttribute('name') ? 'name' : (isset($this->displayField) && $this->hasAttribute($this->displayField) ? $this->displayField : $this->getPrimaryKey());
  2510. }
  2511. function setDisplayField($attribute_name)
  2512. {
  2513. if($this->hasAttribute($attribute_name)){
  2514. $this->displayField = $attribute_name;
  2515. return true;
  2516. }else {
  2517. return false;
  2518. }
  2519. }
  2520. /**
  2521. * Returns true if given attribute exists for this Model.
  2522. *
  2523. * @param string $attribute
  2524. * @return boolean
  2525. */
  2526. function hasAttribute ($attribute)
  2527. {
  2528. empty($this->_columns) ? $this->getColumns() : $this->_columns;
  2529. return isset($this->_columns[$attribute]) || (!empty($this->_combinedAttributes) && $this->isCombinedAttribute($attribute));
  2530. }
  2531. /**
  2532. * Returns true if given attribute is a combined attribute for this Model.
  2533. *
  2534. * @param string $attribute
  2535. * @return boolean
  2536. */
  2537. function isCombinedAttribute ($attribute)
  2538. {
  2539. return !empty($this->_combinedAttributes) && isset($this->_combinedAttributes[$attribute]);
  2540. }
  2541. /**
  2542. * Returns true if given attribute exists for this Model.
  2543. *
  2544. * @param string $name Name of table to look in
  2545. * @return boolean
  2546. */
  2547. function hasColumn($column)
  2548. {
  2549. empty($this->_columns) ? $this->getColumns() : $this->_columns;
  2550. return isset($this->_columns[$column]);
  2551. }
  2552. function debug ($data = 'active_record_class', $_functions=0)
  2553. {
  2554. if(!AK_DEBUG && !AK_DEV_MODE){
  2555. return;
  2556. }
  2557. $data = $data == 'active_record_class' ? (AK_PHP5 ? clone($this) : $this) : $data;
  2558. if($_functions!=0) {
  2559. $sf=1;
  2560. } else {
  2561. $sf=0 ;
  2562. }
  2563. if (isset ($data)) {
  2564. if (is_array($data) || is_object($data)) {
  2565. if (count ($data)) {
  2566. echo AK_CLI ? "/--\n" : "<ol>\n";
  2567. while (list ($key,$value) = each ($data)) {
  2568. if($key{0} == '_'){
  2569. continue;
  2570. }
  2571. $type=gettype($value);
  2572. if ($type=="array") {
  2573. AK_CLI ? printf ("\t* (%s) %s:\n",$type, $key) :
  2574. printf ("<li>(%s) <b>%s</b>:\n",$type, $key);
  2575. ob_start();
  2576. Ak::debug ($value,$sf);
  2577. $lines = explode("\n",ob_get_clean()."\n");
  2578. foreach ($lines as $line){
  2579. echo "\t".$line."\n";
  2580. }
  2581. }elseif($type == "object"){
  2582. if(method_exists($value,'hasColumn') && $value->hasColumn($key)){
  2583. $value->toString(true);
  2584. AK_CLI ? printf ("\t* (%s) %s:\n",$type, $key) :
  2585. printf ("<li>(%s) <b>%s</b>:\n",$type, $key);
  2586. ob_start();
  2587. Ak::debug ($value,$sf);
  2588. $lines = explode("\n",ob_get_clean()."\n");
  2589. foreach ($lines as $line){
  2590. echo "\t".$line."\n";
  2591. }
  2592. }
  2593. }elseif (eregi ("function", $type)) {
  2594. if ($sf) {
  2595. AK_CLI ? printf ("\t* (%s) %s:\n",$type, $key, $value) :
  2596. printf ("<li>(%s) <b>%s</b> </li>\n",$type, $key, $value);
  2597. }
  2598. } else {
  2599. if (!$value) {
  2600. $value="(none)";
  2601. }
  2602. AK_CLI ? printf ("\t* (%s) %s = %s\n",$type, $key, $value) :
  2603. printf ("<li>(%s) <b>%s</b> = %s</li>\n",$type, $key, $value);
  2604. }
  2605. }
  2606. echo AK_CLI ? "\n--/\n" : "</ol>fin.\n";
  2607. } else {
  2608. echo "(empty)";
  2609. }
  2610. }
  2611. }
  2612. }
  2613. function getOnlyAvailableAtrributes($attributes)
  2614. {
  2615. $table_name = $this->getTableName();
  2616. $ret_attributes = array();
  2617. if(!empty($attributes) && is_array($attributes)){
  2618. $available_attributes = $this->getAvailableAttributes();
  2619. $keys = array_keys($attributes);
  2620. $size = sizeOf($keys);
  2621. for ($i=0; $i < $size; $i++){
  2622. $k = str_replace($table_name.'.','',$keys[$i]);
  2623. if(isset($available_attributes[$k]['name'][$k])){
  2624. $ret_attributes[$k] =& $attributes[$keys[$i]];
  2625. }
  2626. }
  2627. }
  2628. return $ret_attributes;
  2629. }
  2630. function getColumnsForAtrributes($attributes)
  2631. {
  2632. $ret_attributes = array();
  2633. $table_name = $this->getTableName();
  2634. if(!empty($attributes) && is_array($attributes)){
  2635. $columns = $this->getColumns();
  2636. foreach ($attributes as $k=>$v){
  2637. $k = str_replace($table_name.'.','',$k);
  2638. if(isset($columns[$k]['name'][$k])){
  2639. $ret_attributes[$k] = $v;
  2640. }
  2641. }
  2642. }
  2643. return $ret_attributes;
  2644. }
  2645. function getAvailableAttributesQuoted()
  2646. {
  2647. return $this->getAttributesQuoted($this->getAttributes());
  2648. }
  2649. function getAttributesQuoted($attributes_array)
  2650. {
  2651. $set = array();
  2652. $attributes_array = $this->getSanitizedConditionsArray($attributes_array);
  2653. foreach (array_diff($attributes_array,array('')) as $k=>$v){
  2654. $set[$k] = $k.'='.$v;
  2655. }
  2656. return $set;
  2657. }
  2658. function getColumnType($column_name)
  2659. {
  2660. empty($this->_columns) ? $this->getColumns() : null;
  2661. return empty($this->_columns[$column_name]['type']) ? false : $this->_columns[$column_name]['type'];
  2662. }
  2663. function castAttributeForDatabase($column_name, $value, $add_quotes = true)
  2664. {
  2665. $result = '';//$add_quotes ? "''" : ''; // $result = $add_quotes ? $this->_db->qstr('') : '';
  2666. switch ($this->getColumnType($column_name)) {
  2667. case 'datetime':
  2668. if(!empty($value)){
  2669. $date_time = $this->_db->DBTimeStamp($this->getValueForDateColumn($column_name, $value));
  2670. $result = $add_quotes ? $date_time : trim($date_time ,"'");
  2671. }else{
  2672. $result = 'null';
  2673. }
  2674. break;
  2675. case 'date':
  2676. if(!empty($value)){
  2677. $date = $this->_db->DBDate($this->getValueForDateColumn($column_name, $value));
  2678. $result = $add_quotes ? $date : trim($date, "'");
  2679. }else{
  2680. $result = 'null';
  2681. }
  2682. break;
  2683. case 'boolean':
  2684. $result = !empty($value) ? '1' : '0';
  2685. break;
  2686. case 'binary':
  2687. if($this->_getDatabaseType() == 'postgre'){
  2688. $result = " '".$this->_db->BlobEncode($value)."'::bytea ";
  2689. }else{
  2690. $result = $add_quotes ? $this->_db->qstr($value) : $value;
  2691. }
  2692. break;
  2693. case 'serial':
  2694. case 'integer':
  2695. case 'float':
  2696. $result = (empty($value) && @$value !== 0) ? 'null' : (is_numeric($value) ? $value : $this->_db->qstr($value));
  2697. $result = !empty($this->_columns[$column_name]['notNull']) && $result == 'null' && $this->_getDatabaseType() == 'sqlite' ? '0' : $result;
  2698. break;
  2699. default:
  2700. $result = $add_quotes ? $this->_db->qstr($value) : $value;
  2701. break;
  2702. }
  2703. return empty($this->_columns[$column_name]['notNull']) ? ($result === '' ? "''" : $result) : ($result == 'null' ? '' : $result);
  2704. }
  2705. function castAttributeFromDatabase($column_name, $value)
  2706. {
  2707. if($this->hasColumn($column_name)){
  2708. $column_type = $this->getColumnType($column_name);
  2709. if($column_type){
  2710. if(!empty($value) && 'date' == $column_type && strstr(trim($value),' ')){
  2711. return substr($value,0,10) == '0000-00-00' ? null : str_replace(substr($value,strpos($value,' ')), '', $value);
  2712. }elseif (!empty($value) && 'datetime' == $column_type && substr($value,0,10) == '0000-00-00'){
  2713. return null;
  2714. }elseif ('binary' == $column_type && $this->_getDatabaseType() == 'postgre'){
  2715. return $this->_db->BlobDecode($value);
  2716. }elseif('boolean' == $column_type){
  2717. return (integer)$value === 1 ? true : false;
  2718. }
  2719. }
  2720. }
  2721. return $value;
  2722. }
  2723. function _addBlobQueryStack($column_name, $blob_value)
  2724. {
  2725. $this->_BlobQueryStack[$column_name] = $blob_value;
  2726. }
  2727. function _updateBlobFields($condition)
  2728. {
  2729. if(!empty($this->_BlobQueryStack) && is_array($this->_BlobQueryStack)){
  2730. foreach ($this->_BlobQueryStack as $column=>$value){
  2731. $this->_db->UpdateBlob($this->getTableName(), $column, $value, $condition);
  2732. }
  2733. $this->_BlobQueryStack = null;
  2734. }
  2735. }
  2736. function getAttributeCondition($argument)
  2737. {
  2738. if(is_array($argument)){
  2739. return 'IN (?)';
  2740. }elseif (is_null($argument)){
  2741. return 'IS ?';
  2742. }else{
  2743. return '= ?';
  2744. }
  2745. }
  2746. function getValueForDateColumn($column_name, $value)
  2747. {
  2748. if(!$this->isNewRecord()){
  2749. if(($column_name == 'updated_on' || $column_name == 'updated_at') && empty($value)){
  2750. return null;
  2751. }
  2752. }elseif(($column_name == 'created_on' || $column_name == 'created_at') && empty($value)){
  2753. return Ak::time();
  2754. }elseif($column_name == 'expires_on' || $column_name == 'expires_at'){
  2755. return empty($value) ? Ak::getTimestamp('9999-12-31 23:59:59') : Ak::getTimestamp($value);
  2756. }
  2757. return Ak::getTimestamp($value);
  2758. }
  2759. /**
  2760. * Updates the associated record with values matching those of the instance attributes.
  2761. * Must be called as a result of a call to createOrUpdate.
  2762. */
  2763. function _update()
  2764. {
  2765. if($this->isFrozen()){
  2766. $this->transactionFail();
  2767. return false;
  2768. }
  2769. if($this->beforeUpdate()){
  2770. $this->notifyObservers('beforeUpdate');
  2771. if($this->_recordTimestamps){
  2772. if ($this->hasColumn('updated_at')){
  2773. $this->setAttribute('updated_at', Ak::getDate());
  2774. }
  2775. if ($this->hasColumn('updated_on')){
  2776. $this->setAttribute('updated_on', Ak::getDate(null, 'Y-m-d'));
  2777. }
  2778. }
  2779. $lock_check = '';
  2780. if ($this->isLockingEnabled()){
  2781. $previous_value = $this->lock_version;
  2782. $this->setAttribute('lock_version', $previous_value + 1);
  2783. $lock_check = ' AND lock_version = '.$previous_value;
  2784. }
  2785. $quoted_attributes = $this->getAvailableAttributesQuoted();
  2786. if(!empty($quoted_attributes)){
  2787. $sql = 'UPDATE '.$this->getTableName().' '.
  2788. 'SET '.join(', ', $quoted_attributes) .' '.
  2789. 'WHERE '.$this->getPrimaryKey().'='.$this->quotedId().$lock_check;
  2790. }
  2791. if(!$this->_executeSql($sql, false)){
  2792. $this->transactionFail();
  2793. AK_DEBUG ? trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE) : null;
  2794. }
  2795. if ($this->isLockingEnabled()){
  2796. if($this->_db->Affected_Rows() != 1){
  2797. $this->setAttribute('lock_version', $previous_value);
  2798. $this->transactionFail();
  2799. trigger_error(Ak::t('Attempted to update a stale object'), E_USER_NOTICE);
  2800. return false;
  2801. }
  2802. }
  2803. if(!$this->transactionHasFailed()){
  2804. if($this->afterUpdate()){
  2805. $this->notifyObservers('afterUpdate');
  2806. }else {
  2807. $this->transactionFail();
  2808. }
  2809. }
  2810. }else{
  2811. $this->transactionFail();
  2812. }
  2813. return $this;
  2814. }
  2815. /////////////////// OPTIMISTIC LOCKING //////////////////////////////
  2816. /**
  2817. * Active Records support optimistic locking if the field <tt>lock_version</tt> is present. Each update to the
  2818. * record increments the lock_version column and the locking facilities ensure that records instantiated twice
  2819. * will let the last one saved return false on save() if the first was also updated. Example:
  2820. *
  2821. * $p1 = new Person(1);
  2822. * $p2 = new Person(1);
  2823. *
  2824. * $p1->first_name = "Michael";
  2825. * $p1->save();
  2826. *
  2827. * $p2->first_name = "should fail";
  2828. * $p2->save(); // Returns false
  2829. *
  2830. * You're then responsible for dealing with the conflict by checking the return value of save(); and either rolling back, merging,
  2831. * or otherwise apply the business logic needed to resolve the conflict.
  2832. *
  2833. * You must ensure that your database schema defaults the lock_version column to 0.
  2834. *
  2835. * This behavior can be turned off by setting <tt>AkActiveRecord::lock_optimistically = false</tt>.
  2836. */
  2837. function isLockingEnabled()
  2838. {
  2839. return ((isset($this->lock_optimistically) && $this->lock_optimistically !== false) || !isset($this->lock_optimistically)) && $this->hasColumn('lock_version');
  2840. }
  2841. /**
  2842. * Creates a new record with values matching those of the instance attributes.
  2843. * Must be called as a result of a call to createOrUpdate.
  2844. */
  2845. function _create()
  2846. {
  2847. if($this->isFrozen()){
  2848. $this->transactionFail();
  2849. return false;
  2850. }
  2851. if($this->beforeCreate()){
  2852. $this->notifyObservers('beforeCreate');
  2853. if($this->_recordTimestamps){
  2854. if ($this->hasColumn('created_at')){
  2855. $this->setAttribute('created_at', Ak::getDate());
  2856. }
  2857. if ($this->hasColumn('created_on')){
  2858. $this->setAttribute('created_on', Ak::getDate(null, 'Y-m-d'));
  2859. }
  2860. if(isset($this->expires_on)){
  2861. if(isset($this->expires_at) && $this->hasColumn('expires_at')){
  2862. $this->setAttribute('expires_at',Ak::getDate(strtotime($this->expires_at) + (defined('AK_TIME_DIFFERENCE') ? AK_TIME_DIFFERENCE*60 : 0)));
  2863. }elseif(isset($this->expires_on) && $this->hasColumn('expires_on')){
  2864. $this->setAttribute('expires_on',Ak::getDate(strtotime($this->expires_on) + (defined('AK_TIME_DIFFERENCE') ? AK_TIME_DIFFERENCE*60 : 0), 'Y-m-d'));
  2865. }
  2866. }
  2867. }
  2868. $attributes = $this->getColumnsForAtrributes($this->getAttributes());
  2869. if($this->isLockingEnabled()){
  2870. $attributes['lock_version'] = 1;
  2871. $this->setAttribute('lock_version',1);
  2872. }
  2873. $pk = $this->getPrimaryKey();
  2874. $table = $this->getTableName();
  2875. foreach ($attributes as $column=>$value){
  2876. $attributes[$column] = $this->castAttributeForDatabase($column,$value);
  2877. }
  2878. /**
  2879. * @todo sanitize attributes
  2880. * 'beforeValidationOnCreate', 'afterValidationOnCreate'
  2881. */
  2882. if(!isset($this->_generateSequence) || (isset($this->_generateSequence) && $this->_generateSequence !== false)){
  2883. if((empty($attributes[$pk]) || (!empty($attributes[$pk]) && (integer)$attributes[$pk] > 0 ))){
  2884. if($this->_getDatabaseType() != 'mysql'){
  2885. $table_details = $this->_databaseTableInternals('seq_'.$table);
  2886. if(!isset($table_details['ID'])){
  2887. $this->_db->CreateSequence('seq_'.$table);
  2888. }
  2889. $attributes[$pk] = $this->_db->GenID('seq_'.$table);
  2890. }
  2891. }
  2892. }
  2893. $__attributes = $attributes;
  2894. $attributes = array_diff($attributes, array('',"''"));
  2895. $sql = 'INSERT INTO '.$table.' '.
  2896. '('.join(', ',array_keys($attributes)).') '.
  2897. 'VALUES ('.join(',',array_values($attributes)).')';
  2898. if(!$this->_executeSql($sql, false)){
  2899. AK_DEBUG ? trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE) : null;
  2900. }
  2901. $id = !empty($attributes[$pk]) ? $attributes[$pk] : $this->_db->Insert_ID($table, $pk);
  2902. $this->setId($id);
  2903. if(!$this->transactionHasFailed()){
  2904. $this->_newRecord = false;
  2905. if(!$this->afterCreate()){
  2906. $this->transactionFail();
  2907. }else{
  2908. $this->notifyObservers('afterCreate');
  2909. }
  2910. }
  2911. }else{
  2912. $this->transactionFail();
  2913. }
  2914. return $this;
  2915. }
  2916. /**#@+
  2917. *
  2918. * @todo Investigate a way for setting up callbacks using attributes without causing to much overhead.
  2919. *
  2920. * Callbacks are hooks into the lifecycle of an Active Record object that allows you to trigger logic
  2921. * before or after an alteration of the object state. This can be used to make sure that associated and
  2922. * dependent objects are deleted when destroy is called (by overwriting beforeDestroy) or to massage attributes
  2923. * before they're validated (by overwriting beforeValidation). As an example of the callbacks initiated, consider
  2924. * the AkActiveRecord->save() call:
  2925. *
  2926. * - (-) save()
  2927. * - (-) needsValidation()
  2928. * - (1) beforeValidation()
  2929. * - (2) beforeValidationOnCreate() / beforeValidationOnUpdate()
  2930. * - (-) validate()
  2931. * - (-) validateOnCreate()
  2932. * - (4) afterValidation()
  2933. * - (5) afterValidationOnCreate() / afterValidationOnUpdate()
  2934. * - (6) beforeSave()
  2935. * - (7) beforeCreate() / beforeUpdate()
  2936. * - (-) create()
  2937. * - (8) afterCreate() / afterUpdate()
  2938. * - (9) afterSave()
  2939. * - (10) afterDestroy()
  2940. * - (11) beforeDestroy()
  2941. *
  2942. *
  2943. * That's a total of 15 callbacks, which gives you immense power to react and prepare for each state in the
  2944. * Active Record lifecycle.
  2945. *
  2946. * Examples:
  2947. * class CreditCard extends AkActiveRecord
  2948. * {
  2949. * // Strip everything but digits, so the user can specify "555 234 34" or
  2950. * // "5552-3434" or both will mean "55523434"
  2951. * function beforeValidationOnCreate
  2952. * {
  2953. * if(!empty($this->number)){
  2954. * $this->number = ereg_replace('[^0-9]*','',$this->number);
  2955. * }
  2956. * }
  2957. * }
  2958. *
  2959. * class Subscription extends AkActiveRecord
  2960. * {
  2961. * // Note: This is not implemented yet
  2962. * var $beforeCreate = 'recordSignup';
  2963. *
  2964. * function recordSignup()
  2965. * {
  2966. * $this->signed_up_on = date("Y-m-d");
  2967. * }
  2968. * }
  2969. *
  2970. * class Firm extends AkActiveRecord
  2971. * {
  2972. * //Destroys the associated clients and people when the firm is destroyed
  2973. * // Note: This is not implemented yet
  2974. * var $beforeDestroy = array('destroyAssociatedPeople', 'destroyAssociatedClients');
  2975. *
  2976. * function destroyAssociatedPeople()
  2977. * {
  2978. * $Person = new Person();
  2979. * $Person->destroyAll("firm_id=>", $this->id);
  2980. * }
  2981. *
  2982. * function destroyAssociatedClients()
  2983. * {
  2984. * $Client = new Client();
  2985. * $Client->destroyAll("client_of=>", $this->id);
  2986. * }
  2987. * }
  2988. *
  2989. *
  2990. * == Cancelling callbacks ==
  2991. *
  2992. * If a before* callback returns false, all the later callbacks and the associated action are cancelled. If an after* callback returns
  2993. * false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks
  2994. * defined as methods on the model, which are called last.
  2995. *
  2996. * Override this methods to hook Active Records
  2997. *
  2998. * @access public
  2999. */
  3000. function beforeCreate(){return true;}
  3001. function beforeValidation(){return true;}
  3002. function beforeValidationOnCreate(){return true;}
  3003. function beforeValidationOnUpdate(){return true;}
  3004. function beforeSave(){return true;}
  3005. function beforeUpdate(){return true;}
  3006. function afterUpdate(){return true;}
  3007. function afterValidation(){return true;}
  3008. function afterValidationOnCreate(){return true;}
  3009. function afterValidationOnUpdate(){return true;}
  3010. function afterCreate(){return true;}
  3011. function afterDestroy(){return true;}
  3012. function beforeDestroy(){return true;}
  3013. function afterSave(){return true;}
  3014. /**#@-*/
  3015. function toString($print = false)
  3016. {
  3017. $result = '';
  3018. if(!AK_CLI || (AK_ENVIRONMENT == 'testing' && !AK_CLI)){
  3019. $result = "<h2>Details for ".AkInflector::humanize(AkInflector::underscore($this->getModelName()))." with ".$this->getPrimaryKey()." ".$this->getId()."</h2>\n<dl>\n";
  3020. foreach ($this->getColumnNames() as $column=>$caption){
  3021. $result .= "<dt>$caption</dt>\n<dd>".$this->getAttribute($column)."</dd>\n";
  3022. }
  3023. $result .= "</dl>\n<hr />";
  3024. if($print){
  3025. echo $result;
  3026. }
  3027. }elseif(AK_ENVIRONMENT == 'development'){
  3028. $result = "\n".
  3029. str_replace("\n"," ",var_export($this->getAttributes(),true));
  3030. $result .= "\n";
  3031. echo $result;
  3032. return '';
  3033. }elseif (AK_CLI){
  3034. $result = "\n-------\n Details for ".AkInflector::humanize(AkInflector::underscore($this->getModelName()))." with ".$this->getPrimaryKey()." ".$this->getId()." ==\n\n/==\n";
  3035. foreach ($this->getColumnNames() as $column=>$caption){
  3036. $result .= "\t * $caption: ".$this->getAttribute($column)."\n";
  3037. }
  3038. $result .= "\n\n-------\n";
  3039. if($print){
  3040. echo $result;
  3041. }
  3042. }
  3043. return $result;
  3044. }
  3045. function toJson()
  3046. {
  3047. return Ak::toJson($this->getAttributes());
  3048. }
  3049. /**#@+
  3050. * Transaction support for database operations
  3051. *
  3052. * Transactions are enabled automatically for Active record objects, But you can nest transactions within models.
  3053. * This transactions are nested, and only the othermost will be executed
  3054. *
  3055. * $User->transactionStart();
  3056. * $User->create('username'=>'Bermi');
  3057. * $Members->create('username'=>'Bermi');
  3058. *
  3059. * if(!checkSomething()){
  3060. * $User->transactionFail();
  3061. * }
  3062. *
  3063. * $User->transactionComplete();
  3064. */
  3065. function transactionStart()
  3066. {
  3067. if(!$this->isConnected()){
  3068. $this->setConnection();
  3069. }
  3070. return $this->_db->StartTrans();
  3071. }
  3072. function transactionComplete()
  3073. {
  3074. return $this->_db->CompleteTrans();
  3075. }
  3076. function transactionFail()
  3077. {
  3078. return $this->_db->FailTrans();
  3079. }
  3080. function transactionHasFailed()
  3081. {
  3082. return $this->_db->HasFailedTrans();
  3083. }
  3084. /**#@-*/
  3085. ////////////////////////////////////////////////////////////////////
  3086. ////////// VALIDATION ////////////////////////////////
  3087. ////////////////////////////////////////////////////////////////////
  3088. /**
  3089. * Active Records implement validation by overwriting AkActiveRecord::validate (or the variations, validateOnCreate and
  3090. * validateOnUpdate). Each of these methods can inspect the state of the object, which usually means ensuring
  3091. * that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
  3092. *
  3093. * Example:
  3094. *
  3095. * class Person extends AkActiveRecord
  3096. * {
  3097. * function validate()
  3098. * {
  3099. * $this->addErrorOnEmpty(array('first_name', 'last_name'));
  3100. * if(!preg_match('/[0-9]{4,12}/', $this->phone_number)){
  3101. * $this->addError("phone_number", "has invalid format");
  3102. * }
  3103. * }
  3104. *
  3105. * function validateOnCreate() // is only run the first time a new object is saved
  3106. * {
  3107. * if(!isValidDiscount($this->membership_discount)){
  3108. * $this->addError("membership_discount", "has expired");
  3109. * }
  3110. * }
  3111. *
  3112. * function validateOnUpdate()
  3113. * {
  3114. * if($this->countChangedAttributes() == 0){
  3115. * $this->addErrorToBase("No changes have occurred");
  3116. * }
  3117. * }
  3118. * }
  3119. *
  3120. * $Person = new Person(array("first_name" => "David", "phone_number" => "what?"));
  3121. * $Person->save(); // => false (and doesn't do the save);
  3122. * $Person->hasErrors(); // => false
  3123. * $Person->countErrors(); // => 2
  3124. * $Person->getErrorsOn("last_name"); // => "can't be empty"
  3125. * $Person->getErrorsOn("phone_number"); // => "has invalid format"
  3126. * $Person->yieldEachFullError(); // => "Last name can't be empty \n Phone number has invalid format"
  3127. *
  3128. * $Person->setAttributes(array("last_name" => "Heinemeier", "phone_number" => "555-555"));
  3129. * $Person->save(); // => true (and person is now saved in the database)
  3130. *
  3131. * An "Errors" object is automatically created for every Active Record.
  3132. *
  3133. */
  3134. /**
  3135. * Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
  3136. *
  3137. * Model:
  3138. * class Person extends AkActiveRecord
  3139. * {
  3140. * function validate()
  3141. * {
  3142. * $this->validatesConfirmationOf('password');
  3143. * $this->validatesConfirmationOf('email_address', "should match confirmation");
  3144. * }
  3145. * }
  3146. *
  3147. * View:
  3148. * <?=$form_helper->password_field("person", "password"); ?>
  3149. * <?=$form_helper->password_field("person", "password_confirmation"); ?>
  3150. *
  3151. * The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual.
  3152. * It exists only as an in-memory variable for validating the password. This check is performed only if password_confirmation
  3153. * is not null.
  3154. *
  3155. */
  3156. function validatesConfirmationOf($attribute_names, $message = 'confirmation')
  3157. {
  3158. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3159. $attribute_names = Ak::toArray($attribute_names);
  3160. foreach ($attribute_names as $attribute_name){
  3161. $attribute_accessor = $attribute_name.'_confirmation';
  3162. if(isset($this->$attribute_accessor) && @$this->$attribute_accessor != @$this->$attribute_name){
  3163. $this->addError($attribute_name, $message);
  3164. }
  3165. }
  3166. }
  3167. /**
  3168. * Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
  3169. *
  3170. * class Person extends AkActiveRecord
  3171. * {
  3172. * function validateOnCreate()
  3173. * {
  3174. * $this->validatesAcceptanceOf('terms_of_service');
  3175. * $this->validatesAcceptanceOf('eula', "must be abided");
  3176. * }
  3177. * }
  3178. *
  3179. * The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed only if
  3180. * terms_of_service is not null.
  3181. *
  3182. *
  3183. * @param accept 1
  3184. * Specifies value that is considered accepted. The default value is a string "1", which makes it easy to relate to an HTML checkbox.
  3185. */
  3186. function validatesAcceptanceOf($attribute_names, $message = 'accepted', $accept = 1)
  3187. {
  3188. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3189. $attribute_names = Ak::toArray($attribute_names);
  3190. foreach ($attribute_names as $attribute_name){
  3191. if(@$this->$attribute_name != $accept){
  3192. $this->addError($attribute_name, $message);
  3193. }
  3194. }
  3195. }
  3196. /**
  3197. * Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
  3198. *
  3199. * class Book extends ActiveRecord
  3200. {
  3201. * var $has_many = 'pages';
  3202. * var $belongs_to = 'library';
  3203. *
  3204. * function validate(){
  3205. * $this->validatesAssociated(array('pages', 'library'));
  3206. * }
  3207. * }
  3208. *
  3209. *
  3210. * Warning: If, after the above definition, you then wrote:
  3211. *
  3212. * class Page extends ActiveRecord
  3213. * {
  3214. * var $belongs_to = 'book';
  3215. * function validate(){
  3216. * $this->validatesAssociated('book');
  3217. * }
  3218. * }
  3219. *
  3220. * ...this would specify a circular dependency and cause infinite recursion.
  3221. *
  3222. * NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
  3223. * is both present and guaranteed to be valid, you also need to use validatesPresenceOf.
  3224. */
  3225. function validatesAssociated($attribute_names, $message = 'invalid')
  3226. {
  3227. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $messa;
  3228. $attribute_names = Ak::toArray($attribute_names);
  3229. foreach ($attribute_names as $attribute_name){
  3230. if(!empty($this->$attribute_name)){
  3231. if(is_array($this->$attribute_name)){
  3232. foreach(array_keys($this->$attribute_name) as $k){
  3233. if(method_exists($this->{$attribute_name}[$k],'isValid') && !$this->{$attribute_name}[$k]->isValid()){
  3234. $this->addError($attribute_name, $message);
  3235. }
  3236. }
  3237. }elseif (method_exists($this->$attribute_name,'isValid') && !$this->$attribute_name->isValid()){
  3238. $this->addError($attribute_name, $message);
  3239. }
  3240. }
  3241. }
  3242. }
  3243. function isBlank($value = null)
  3244. {
  3245. return trim((string)$value) == '';
  3246. }
  3247. /**
  3248. * Validates that the specified attributes are not blank (as defined by AkActiveRecord::isBlank()).
  3249. */
  3250. function validatesPresenceOf($attribute_names, $message = 'blank')
  3251. {
  3252. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3253. $attribute_names = Ak::toArray($attribute_names);
  3254. foreach ($attribute_names as $attribute_name){
  3255. $this->addErrorOnBlank($attribute_name, $message);
  3256. }
  3257. }
  3258. /**
  3259. * Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
  3260. *
  3261. * class Person extends AkActiveRecord
  3262. * {
  3263. * function validate()
  3264. * {
  3265. * $this->validatesLengthOf('first_name', array('maximum'=>30));
  3266. * $this->validatesLengthOf('last_name', array('maximum'=>30,'message'=> "less than %d if you don't mind"));
  3267. * $this->validatesLengthOf('last_name', array('within'=>array(7, 32)));
  3268. * $this->validatesLengthOf('last_name', array('in'=>array(6, 20), 'too_long' => "pick a shorter name", 'too_short' => "pick a longer name"));
  3269. * $this->validatesLengthOf('fav_bra_size', array('minimum'=>1, 'too_short'=>"please enter at least %d character"));
  3270. * $this->validatesLengthOf('smurf_leader', array('is'=>4, 'message'=>"papa is spelled with %d characters... don't play me."));
  3271. * }
  3272. * }
  3273. *
  3274. * 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 appropiate types.
  3275. *
  3276. * Configuration options:
  3277. * <tt>minimum</tt> - The minimum size of the attribute
  3278. * <tt>maximum</tt> - The maximum size of the attribute
  3279. * <tt>is</tt> - The exact size of the attribute
  3280. * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
  3281. * <tt>in</tt> - A synonym(or alias) for :within
  3282. * <tt>allow_null</tt> - Attribute may be null; skip validation.
  3283. *
  3284. * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default "is" "is too long (max is %d characters)")
  3285. * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default "is" "is too short (min is %d characters)")
  3286. * <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)")
  3287. * <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
  3288. */
  3289. function validatesLengthOf($attribute_names, $options = array())
  3290. {
  3291. // Merge given options with defaults.
  3292. $default_options = array(
  3293. 'too_long' => $this->_defaultErrorMessages['too_long'],
  3294. 'too_short' => $this->_defaultErrorMessages['too_short'],
  3295. 'wrong_length' => $this->_defaultErrorMessages['wrong_length'],
  3296. 'allow_null' => false
  3297. );
  3298. $range_options = array();
  3299. foreach ($options as $k=>$v){
  3300. if(in_array($k,array('minimum','maximum','is','in','within'))){
  3301. $range_options[$k] = $v;
  3302. $option = $k;
  3303. $option_value = $v;
  3304. }
  3305. }
  3306. // Ensure that one and only one range option is specified.
  3307. switch (count($range_options)) {
  3308. case 0:
  3309. trigger_error(Ak::t('Range unspecified. Specify the "within", "maximum", "minimum, or "is" option.'), E_USER_ERROR);
  3310. return false;
  3311. break;
  3312. case 1:
  3313. $options = array_merge($default_options, $options);
  3314. break;
  3315. default:
  3316. trigger_error(Ak::t('Too many range options specified. Choose only one.'), E_USER_ERROR);
  3317. return false;
  3318. break;
  3319. }
  3320. switch ($option) {
  3321. case 'within':
  3322. case 'in':
  3323. if(empty($option_value) || !is_array($option_value) || count($option_value) != 2 || !is_numeric($option_value[0]) || !is_numeric($option_value[1])){
  3324. trigger_error(Ak::t('%option must be a Range (array(min, max))',array('%option',$option)), E_USER_ERROR);
  3325. return false;
  3326. }
  3327. $attribute_names = is_array($attribute_names) ? $attribute_names : array($attribute_names);
  3328. foreach ($attribute_names as $attribute_name){
  3329. if((!empty($option['allow_null']) && !isset($this->$attribute_name)) || (Ak::size($this->$attribute_name)) < $option_value[0]){
  3330. $this->addError($attribute_name, sprintf($options['too_short'], $option_value[0]));
  3331. }elseif((!empty($option['allow_null']) && !isset($this->$attribute_name)) || (Ak::size($this->$attribute_name)) > $option_value[1]){
  3332. $this->addError($attribute_name, sprintf($options['too_long'], $option_value[1]));
  3333. }
  3334. }
  3335. break;
  3336. case 'is':
  3337. case 'minimum':
  3338. case 'maximum':
  3339. if(empty($option_value) || !is_numeric($option_value) || $option_value <= 0){
  3340. trigger_error(Ak::t('%option must be a nonnegative Integer',array('%option',$option_value)), E_USER_ERROR);
  3341. return false;
  3342. }
  3343. // Declare different validations per option.
  3344. $validity_checks = array('is' => "==", 'minimum' => ">=", 'maximum' => "<=");
  3345. $message_options = array('is' => 'wrong_length', 'minimum' => 'too_short', 'maximum' => 'too_long');
  3346. $message = sprintf(!empty($options['message']) ? $options['message'] : $options[$message_options[$option]],$option_value);
  3347. $attribute_names = is_array($attribute_names) ? $attribute_names : array($attribute_names);
  3348. foreach ($attribute_names as $attribute_name){
  3349. if((!$options['allow_null'] && !isset($this->$attribute_name)) ||
  3350. eval("return !(".Ak::size(@$this->$attribute_name)." {$validity_checks[$option]} $option_value);")){
  3351. $this->addError($attribute_name, $message);
  3352. }
  3353. }
  3354. break;
  3355. default:
  3356. break;
  3357. }
  3358. return true;
  3359. }
  3360. function validatesSizeOf($attribute_names, $options = array())
  3361. {
  3362. return validatesLengthOf($attribute_names, $options);
  3363. }
  3364. /**
  3365. * Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
  3366. * can be named "davidhh".
  3367. *
  3368. * class Person extends AkActiveRecord
  3369. * {
  3370. * function validate()
  3371. * {
  3372. * $this->validatesUniquenessOf('passport_number');
  3373. * $this->validatesUniquenessOf('user_name', array('scope' => "account_id"));
  3374. * }
  3375. * }
  3376. *
  3377. * It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
  3378. * making sure that a teacher can only be on the schedule once per semester for a particular class.
  3379. *
  3380. * class TeacherSchedule extends AkActiveRecord
  3381. * {
  3382. * function validate()
  3383. * {
  3384. * $this->validatesUniquenessOf('passport_number');
  3385. * $this->validatesUniquenessOf('teacher_id', array('scope' => array("semester_id", "class_id"));
  3386. * }
  3387. * }
  3388. *
  3389. *
  3390. * 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
  3391. * attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
  3392. *
  3393. * Configuration options:
  3394. * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
  3395. * <tt>scope</tt> - Ensures that the uniqueness is restricted to a condition of "scope = record.scope"
  3396. * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default).
  3397. * <tt>if</tt> - Specifies a method to call or a string to evaluate to determine if the validation should
  3398. * occur (e.g. 'if' => 'allowValidation', or 'if' => '$this->signup_step > 2'). The
  3399. * method, or string should return or evaluate to a true or false value.
  3400. */
  3401. function validatesUniquenessOf($attribute_names, $options = array())
  3402. {
  3403. $default_options = array('case_sensitive'=>true, 'message'=>'taken');
  3404. $options = array_merge($default_options, $options);
  3405. if(!empty($options['if'])){
  3406. if(method_exists($this,$options['if'])){
  3407. if($this->{$options['if']}() === false){
  3408. return true;
  3409. }
  3410. }else {
  3411. eval('$__eval_result = ('.rtrim($options['if'],';').');');
  3412. if(empty($__eval_result)){
  3413. return true;
  3414. }
  3415. }
  3416. }
  3417. $message = isset($this->_defaultErrorMessages[$options['message']]) ? $this->t($this->_defaultErrorMessages[$options['message']]) : $options['message'];
  3418. unset($options['message']);
  3419. foreach ((array)$attribute_names as $attribute_name){
  3420. $value = isset($this->$attribute_name) ? $this->$attribute_name : null;
  3421. if($value === null || ($options['case_sensitive'] || !$this->hasColumn($attribute_name))){
  3422. $condition_sql = $this->getTableName().'.'.$attribute_name.' '.$this->getAttributeCondition($value);
  3423. $condition_params = array($value);
  3424. }else{
  3425. $condition_sql = 'LOWER('.$this->getTableName().'.'.$attribute_name.') '.$this->getAttributeCondition($value);
  3426. $condition_params = array(is_array($value) ? array_map('utf8_strtolower',$value) : utf8_strtolower($value));
  3427. }
  3428. if(!empty($options['scope'])){
  3429. foreach ((array)$options['scope'] as $scope_item){
  3430. $scope_value = $this->get($scope_item);
  3431. $condition_sql .= ' AND '.$this->getTableName().'.'.$scope_item.' '.$this->getAttributeCondition($scope_value);
  3432. $condition_params[] = $scope_value;
  3433. }
  3434. }
  3435. if(!$this->isNewRecord()){
  3436. $condition_sql .= ' AND '.$this->getTableName().'.'.$this->getPrimaryKey().' <> ?';
  3437. $condition_params[] = $this->getId();
  3438. }
  3439. array_unshift($condition_params,$condition_sql);
  3440. if ($this->find('first', array('conditions' => $condition_params))){
  3441. $this->addError($attribute_name, $message);
  3442. }
  3443. }
  3444. }
  3445. /**
  3446. * Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
  3447. * provided.
  3448. *
  3449. * class Person extends AkActiveRecord
  3450. * {
  3451. * function validate()
  3452. * {
  3453. * $this->validatesFormatOf('email', "/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/");
  3454. * }
  3455. * }
  3456. *
  3457. * A regular expression must be provided or else an exception will be raised.
  3458. *
  3459. * There are some regular expressions bundled with the Akelos Framework.
  3460. * 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.
  3461. * This are predefined perl-like regular extensions.
  3462. *
  3463. * * AK_NOT_EMPTY_REGULAR_EXPRESSION ---> /.+/
  3464. * * 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
  3465. * * AK_NUMBER_REGULAR_EXPRESSION ---> /^[0-9]+$/
  3466. * * AK_PHONE_REGULAR_EXPRESSION ---> /^([\+]?[(]?[\+]?[ ]?[0-9]{2,3}[)]?[ ]?)?[0-9 ()\-]{4,25}$/
  3467. * * 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}$/
  3468. * * 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])$/
  3469. * * AK_POST_CODE_REGULAR_EXPRESSION ---> /^[0-9A-Za-z -]{2,7}$/
  3470. *
  3471. * 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.
  3472. *
  3473. * Params:
  3474. * <tt>$message</tt> - A custom error message (default is: "is invalid")
  3475. * <tt>$regular_expression</tt> - The regular expression used to validate the format with (note: must be supplied!)
  3476. */
  3477. function validatesFormatOf($attribute_names, $regular_expression, $message = 'invalid', $regex_function = 'preg_match')
  3478. {
  3479. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3480. $attribute_names = is_array($attribute_names) ? $attribute_names : array($attribute_names);
  3481. foreach ($attribute_names as $attribute_name){
  3482. if(!isset($this->$attribute_name) || !$regex_function($regular_expression, $this->$attribute_name)){
  3483. $this->addError($attribute_name, $message);
  3484. }
  3485. }
  3486. }
  3487. /**
  3488. * Validates whether the value of the specified attribute is available in a particular array of elements.
  3489. *
  3490. * class Person extends AkActiveRecord
  3491. * {
  3492. * function validate()
  3493. * {
  3494. * $this->validatesInclusionOf('gender', array('male', 'female'), "woah! what are you then!??!!");
  3495. * $this->validatesInclusionOf('age', range(0, 99));
  3496. * }
  3497. *
  3498. * Parameters:
  3499. * <tt>$array_of_posibilities</tt> - An array of available items
  3500. * <tt>$message</tt> - Specifies a customer error message (default is: "is not included in the list")
  3501. * <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)
  3502. */
  3503. function validatesInclusionOf($attribute_names, $array_of_posibilities, $message = 'inclusion', $allow_null = false)
  3504. {
  3505. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3506. /**
  3507. * @todo get values from lists, collections and nested sets
  3508. */
  3509. $attribute_names = is_array($attribute_names) ? $attribute_names : array($attribute_names);
  3510. foreach ($attribute_names as $attribute_name){
  3511. if($allow_null ? (!empty($this->$attribute_name) ? (!in_array(@$this->$attribute_name,$array_of_posibilities)) : false ) : (isset($this->$attribute_name) ? !in_array(@$this->$attribute_name,$array_of_posibilities) : true )){
  3512. $this->addError($attribute_name, $message);
  3513. }
  3514. }
  3515. }
  3516. /**
  3517. * Validates that the value of the specified attribute is not in a particular array of elements.
  3518. *
  3519. * class Person extends AkActiveRecord
  3520. * {
  3521. * function validate()
  3522. * {
  3523. * $this->validatesExclusionOf('username', array('admin', 'superuser'), "You don't belong here");
  3524. * $this->validatesExclusionOf('age', range(30,60), "This site is only for under 30 and over 60");
  3525. * }
  3526. * }
  3527. *
  3528. * Parameters:
  3529. * <tt>$array_of_posibilities</tt> - An array of items that the value shouldn't be part of
  3530. * <tt>$message</tt> - Specifies a customer error message (default is: "is reserved")
  3531. * <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)
  3532. */
  3533. function validatesExclusionOf($attribute_names, $array_of_posibilities, $message = 'exclusion', $allow_null = false)
  3534. {
  3535. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3536. $attribute_names = is_array($attribute_names) ? $attribute_names : array($attribute_names);
  3537. foreach ($attribute_names as $attribute_name){
  3538. if($allow_null ? (!empty($this->$attribute_name) ? (in_array(@$this->$attribute_name,$array_of_posibilities)) : false ) : (isset($this->$attribute_name) ? in_array(@$this->$attribute_name,$array_of_posibilities) : true )){
  3539. $this->addError($attribute_name, $message);
  3540. }
  3541. }
  3542. }
  3543. /**
  3544. * Validates whether the value of the specified attribute is numeric.
  3545. *
  3546. * class Person extends AkActiveRecord
  3547. * {
  3548. * function validate()
  3549. * {
  3550. * $this->validatesNumericalityOf('value');
  3551. * }
  3552. * }
  3553. *
  3554. * Parameters:
  3555. * <tt>$message</tt> - A custom error message (default is: "is not a number")
  3556. * <tt>$only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
  3557. * <tt>$allow_null</tt> Skip validation if attribute is null (default is false).
  3558. */
  3559. function validatesNumericalityOf($attribute_names, $message = 'not_a_number', $only_integer = false, $allow_null = false)
  3560. {
  3561. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3562. $attribute_names = is_array($attribute_names) ? $attribute_names : array($attribute_names);
  3563. foreach ($attribute_names as $attribute_name){
  3564. if(
  3565. $allow_null ?
  3566. (
  3567. isset($this->$attribute_name) ?
  3568. (
  3569. $only_integer ?
  3570. !is_integer(@$this->$attribute_name) :
  3571. !is_numeric(@$this->$attribute_name)
  3572. ) :
  3573. false
  3574. ) :
  3575. (
  3576. isset($this->$attribute_name) ?
  3577. ($only_integer ? !is_integer(@$this->$attribute_name) : !is_numeric(@$this->$attribute_name)) :
  3578. true
  3579. )
  3580. )
  3581. {
  3582. $this->addError($attribute_name, $message);
  3583. }
  3584. }
  3585. }
  3586. /**
  3587. * Returns true if no errors were added otherwise false.
  3588. */
  3589. function isValid()
  3590. {
  3591. if($this->beforeValidation() && $this->notifyObservers('beforeValidation')){
  3592. $this->clearErrors();
  3593. if($this->_set_default_attribute_values_automatically){
  3594. $this->_setDefaultAttributeValuesAutomatically();
  3595. }
  3596. $this->validate();
  3597. if($this->_automated_validators_enabled){
  3598. $this->_runAutomatedValidators();
  3599. }
  3600. if ($this->isNewRecord()){
  3601. if($this->beforeValidationOnCreate()){
  3602. $this->notifyObservers('beforeValidationOnCreate');
  3603. $this->validateOnCreate();
  3604. $this->notifyObservers('afterValidationOnCreate');
  3605. }
  3606. }else{
  3607. if($this->beforeValidationOnUpdate()){
  3608. $this->notifyObservers('beforeValidationOnUpdate');
  3609. $this->validateOnUpdate();
  3610. $this->notifyObservers('afterValidationOnUpdate');
  3611. }
  3612. }
  3613. $this->notifyObservers('afterValidation');
  3614. }
  3615. return !$this->hasErrors();
  3616. }
  3617. /**
  3618. * By default the Active Record will validate for the maximum length for database columns. You can
  3619. * disable the automated validators by setting $this->_automated_validators_enabled to false.
  3620. * Specific validators are (for now):
  3621. * $this->_automated_max_length_validator = true; // true by default, but you can set it to false on your model
  3622. * $this->_automated_not_null_validator = false; // disabled by default
  3623. */
  3624. function _runAutomatedValidators()
  3625. {
  3626. foreach ($this->_columns as $column_name=>$column_settings){
  3627. if($this->_automated_max_length_validator &&
  3628. empty($column_settings['primaryKey']) &&
  3629. !empty($this->$column_name) &&
  3630. !empty($column_settings['maxLength']) &&
  3631. $column_settings['maxLength'] > 0 &&
  3632. strlen($this->$column_name) > $column_settings['maxLength']){
  3633. $this->addError($column_name, sprintf($this->_defaultErrorMessages['too_long'], $column_settings['maxLength']));
  3634. }elseif($this->_automated_not_null_validator && empty($column_settings['primaryKey']) && !empty($column_settings['notNull']) && (!isset($this->$column_name) || is_null($this->$column_name))){
  3635. $this->addError($column_name,'empty');
  3636. }
  3637. }
  3638. }
  3639. /**
  3640. * $this->_set_default_attribute_values_automatically = true; // This enables automated attribute setting from database definition
  3641. */
  3642. function _setDefaultAttributeValuesAutomatically()
  3643. {
  3644. foreach ($this->_columns as $column_name=>$column_settings){
  3645. if(empty($column_settings['primaryKey']) && isset($column_settings['hasDefault']) && $column_settings['hasDefault'] && (!isset($this->$column_name) || is_null($this->$column_name))){
  3646. if(empty($column_settings['defaultValue'])){
  3647. if($column_settings['type'] == 'integer' && empty($column_settings['notNull'])){
  3648. $this->$column_name = 0;
  3649. }elseif(($column_settings['type'] == 'string' || $column_settings['type'] == 'text') && empty($column_settings['notNull'])){
  3650. $this->$column_name = '';
  3651. }
  3652. }else {
  3653. $this->$column_name = $column_settings['defaultValue'];
  3654. }
  3655. }
  3656. }
  3657. }
  3658. /**
  3659. * Returns the Errors array that holds all information about attribute error messages.
  3660. */
  3661. function getErrors()
  3662. {
  3663. return $this->_errors;
  3664. }
  3665. /**
  3666. * Overwrite this method for validation checks on all saves and use addError($field, $message); for invalid attributes.
  3667. */
  3668. function validate()
  3669. {
  3670. }
  3671. /**
  3672. * Overwrite this method for validation checks used only on creation.
  3673. */
  3674. function validateOnCreate()
  3675. {
  3676. }
  3677. /**
  3678. * Overwrite this method for validation checks used only on updates.
  3679. */
  3680. function validateOnUpdate()
  3681. {
  3682. }
  3683. /////////////////////////////////////////////////////////////////////////////
  3684. ////////////////////// OBSERVERS ////////////////////////////////////////////
  3685. /////////////////////////////////////////////////////////////////////////////
  3686. /**
  3687. * Private
  3688. * $state store the state of this observable object
  3689. */
  3690. var $_observable_state;
  3691. function _instatiateDefaultObserver()
  3692. {
  3693. $default_observer_name = ucfirst($this->getModelName().'Observer');
  3694. if(class_exists($default_observer_name)){
  3695. //$Observer =& new $default_observer_name($this);
  3696. Ak::singleton($default_observer_name, $this);
  3697. }
  3698. }
  3699. /**
  3700. * Calls the $method using the reference to each
  3701. * registered observer.
  3702. * @return true (this is used internally for triggering observers on default callbacks)
  3703. */
  3704. function notifyObservers ($method = null)
  3705. {
  3706. $observers =& $this->getObservers();
  3707. $observer_count = count($observers);
  3708. if(!empty($method)){
  3709. $this->setObservableState($method);
  3710. }
  3711. $model_name = $this->getModelName();
  3712. for ($i=0; $i<$observer_count; $i++) {
  3713. if(in_array($model_name, $observers[$i]->_observing)){
  3714. if(method_exists($observers[$i], $method)){
  3715. $observers[$i]->$method($this);
  3716. }else{
  3717. $observers[$i]->update($this->getObservableState(), &$this);
  3718. }
  3719. }else{
  3720. $observers[$i]->update($this->getObservableState(), &$this);
  3721. }
  3722. }
  3723. $this->setObservableState('');
  3724. return true;
  3725. }
  3726. function setObservableState($state_message)
  3727. {
  3728. $this->_observable_state = $state_message;
  3729. }
  3730. function getObservableState()
  3731. {
  3732. return $this->_observable_state;
  3733. }
  3734. /**
  3735. * Register the reference to an object object
  3736. * @return void
  3737. */
  3738. function &addObserver(&$observer)
  3739. {
  3740. static $observers, $registered_observers;
  3741. $observer_class_name = get_class($observer);
  3742. if(!isset($registered_observers[$observer_class_name]) && func_num_args() == 1){
  3743. $observers[] =& $observer;
  3744. $registered_observers[$observer_class_name] = count($observers);
  3745. }
  3746. return $observers;
  3747. }
  3748. /**
  3749. * Register the reference to an object object
  3750. * @return void
  3751. */
  3752. function &getObservers()
  3753. {
  3754. $observers =& $this->addObserver(&$this, false);
  3755. return $observers;
  3756. }
  3757. /////////////////////////////////////////////////////////////////////////////////
  3758. ////////////////////////// ERROR HANDLING ///////////////////////////////////////
  3759. /////////////////////////////////////////////////////////////////////////////////
  3760. /**
  3761. * Adds an error to the base object instead of any particular attribute. This is used
  3762. * to report errors that doesn't tie to any specific attribute, but rather to the object
  3763. * as a whole. These error messages doesn't get prepended with any field name when iterating
  3764. * with yieldEachFullError, so they should be complete sentences.
  3765. */
  3766. function addErrorToBase($message)
  3767. {
  3768. $this->addError($this->getModelName(), $message);
  3769. }
  3770. /**
  3771. * Returns errors assigned to base object through addToBase according to the normal rules of getErrorsOn($attribute).
  3772. */
  3773. function getBaseErrors()
  3774. {
  3775. $errors = $this->getErrors();
  3776. return (array)@$errors[$this->getModelName()];
  3777. }
  3778. /**
  3779. * Adds an error message ($message) to the ($attribute), which will be returned on a call to <tt>getErrorsOn($attribute)</tt>
  3780. * for the same attribute and ensure that this error object returns false when asked if <tt>hasErrors</tt>. More than one
  3781. * error can be added to the same $attribute in which case an array will be returned on a call to <tt>getErrorsOn($attribute)</tt>.
  3782. * If no $message is supplied, "invalid" is assumed.
  3783. */
  3784. function addError($attribute, $message = 'invalid')
  3785. {
  3786. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3787. $this->_errors[$attribute][] = $message;
  3788. }
  3789. /**
  3790. * Will add an error message to each of the attributes in $attributes that is empty.
  3791. */
  3792. function addErrorOnEmpty($attribute_names, $message = 'empty')
  3793. {
  3794. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3795. $attribute_names = Ak::toArray($attribute_names);
  3796. foreach ($attribute_names as $attribute){
  3797. if(empty($this->$attribute)){
  3798. $this->addError($attribute, $message);
  3799. }
  3800. }
  3801. }
  3802. /**
  3803. * Will add an error message to each of the attributes in $attributes that is blank (using $this->isBlank).
  3804. */
  3805. function addErrorOnBlank($attribute_names, $message = 'blank')
  3806. {
  3807. $message = isset($this->_defaultErrorMessages[$message]) ? $this->t($this->_defaultErrorMessages[$message]) : $message;
  3808. $attribute_names = Ak::toArray($attribute_names);
  3809. foreach ($attribute_names as $attribute){
  3810. if($this->isBlank(@$this->$attribute)){
  3811. $this->addError($attribute, $message);
  3812. }
  3813. }
  3814. }
  3815. /**
  3816. * Will add an error message to each of the attributes in $attributes that has a length outside of the passed boundary $range.
  3817. * If the length is above the boundary, the too_long_message message will be used. If below, the too_short_message.
  3818. */
  3819. function addErrorOnBoundaryBreaking($attribute_names, $range_begin, $range_end, $too_long_message = 'too_long', $too_short_message = 'too_short')
  3820. {
  3821. $too_long_message = isset($this->_defaultErrorMessages[$too_long_message]) ? $this->_defaultErrorMessages[$too_long_message] : $too_long_message;
  3822. $too_short_message = isset($this->_defaultErrorMessages[$too_short_message]) ? $this->_defaultErrorMessages[$too_short_message] : $too_short_message;
  3823. $attribute_names = Ak::toArray($attribute_names);
  3824. foreach ($attribute_names as $attribute){
  3825. if(@$this->$attribute < $range_begin){
  3826. $this->addError($attribute, $too_short_message);
  3827. }
  3828. if(@$this->$attribute > $range_end){
  3829. $this->addError($attribute, $too_long_message);
  3830. }
  3831. }
  3832. }
  3833. function addErrorOnBoundryBreaking ($attributes, $range_begin, $range_end, $too_long_message = 'too_long', $too_short_message = 'too_short')
  3834. {
  3835. $this->addErrorOnBoundaryBreaking($attributes, $range_begin, $range_end, $too_long_message, $too_short_message);
  3836. }
  3837. /**
  3838. * Returns true if the specified $attribute has errors associated with it.
  3839. */
  3840. function isInvalid($attribute)
  3841. {
  3842. return $this->getErrorsOn($attribute);
  3843. }
  3844. /**
  3845. * Returns false, if no errors are associated with the specified $attribute.
  3846. * Returns the error message, if one error is associated with the specified $attribute.
  3847. * Returns an array of error messages, if more than one error is associated with the specified $attribute.
  3848. */
  3849. function getErrorsOn($attribute)
  3850. {
  3851. if (empty($this->_errors[$attribute])){
  3852. return false;
  3853. }elseif (count($this->_errors[$attribute]) == 1){
  3854. $k = array_keys($this->_errors[$attribute]);
  3855. return $this->_errors[$attribute][$k[0]];
  3856. }else{
  3857. return $this->_errors[$attribute];
  3858. }
  3859. }
  3860. /**
  3861. * Yields each attribute and associated message per error added.
  3862. */
  3863. function yieldEachError()
  3864. {
  3865. foreach ($this->_errors as $errors){
  3866. foreach ($errors as $error){
  3867. $this->yieldError($error);
  3868. }
  3869. }
  3870. }
  3871. function yieldError($message)
  3872. {
  3873. $messages = is_array($message) ? $message : array($message);
  3874. foreach ($messages as $message){
  3875. echo "<div class='error'><p>$message</p></div>\n";
  3876. }
  3877. }
  3878. /**
  3879. * Yields each full error message added. So Person->addError("first_name", "can't be empty") will be returned
  3880. * through iteration as "First name can't be empty".
  3881. */
  3882. function yieldEachFullError()
  3883. {
  3884. $full_messages = $this->getFullErrorMessages();
  3885. foreach ($full_messages as $full_message){
  3886. $this->yieldError($full_message);
  3887. }
  3888. }
  3889. /**
  3890. * Returns all the full error messages in an array.
  3891. */
  3892. function getFullErrorMessages()
  3893. {
  3894. $full_messages = array();
  3895. foreach ($this->_errors as $attribute=>$errors){
  3896. $full_messages[$attribute] = array();
  3897. foreach ($errors as $error){
  3898. $full_messages[$attribute][] = $this->t('%attribute_name %error', array(
  3899. '%attribute_name'=>AkInflector::humanize($this->_delocalizeAttribute($attribute)),
  3900. '%error'=>$error
  3901. ));
  3902. }
  3903. }
  3904. return $full_messages;
  3905. }
  3906. /**
  3907. * Returns true if no errors have been added.
  3908. */
  3909. function hasErrors()
  3910. {
  3911. return !empty($this->_errors);
  3912. }
  3913. /**
  3914. * Removes all the errors that have been added.
  3915. */
  3916. function clearErrors()
  3917. {
  3918. $this->_errors = array();
  3919. }
  3920. /**
  3921. * Returns the total number of errors added. Two errors added to the same attribute will be counted as such
  3922. * with this as well.
  3923. */
  3924. function countErrors()
  3925. {
  3926. $error_count = 0;
  3927. foreach ($this->_errors as $errors){
  3928. $error_count = count($errors)+$error_count;
  3929. }
  3930. return $error_count;
  3931. }
  3932. function errorsToString($print = false)
  3933. {
  3934. $result = "\n<div id='errors'>\n<ul class='error'>\n";
  3935. foreach ($this->getFullErrorMessages() as $error){
  3936. $result .= is_array($error) ? "<li class='error'>".join('</li><li class=\'error\'>',$error)."</li>\n" : "<li class='error'>$error</li>\n";
  3937. }
  3938. $result .= "</ul>\n</div>\n";
  3939. if($print){
  3940. echo $result;
  3941. }
  3942. return $result;
  3943. }
  3944. function getType()
  3945. {
  3946. //return isset($this->_inheritanceClassName) ? $this->getModelName() : 'active record';
  3947. return $this->getModelName();
  3948. }
  3949. /**
  3950. * actAs provides a method for extending Active Record models.
  3951. *
  3952. * Example:
  3953. * $this->actsAs('list', array('scope' => 'todo_list'));
  3954. */
  3955. function actsAs($behaviour, $options = array())
  3956. {
  3957. $class_name = $this->_getActAsClassName($behaviour);
  3958. $underscored_place_holder = AkInflector::underscore($behaviour);
  3959. $camelized_place_holder = AkInflector::camelize($underscored_place_holder);
  3960. if($this->$underscored_place_holder =& $this->_getActAsInstance($class_name, $options)){
  3961. $this->$camelized_place_holder =& $this->$underscored_place_holder;
  3962. if($this->$underscored_place_holder->init($options)){
  3963. $this->__ActsLikeAttributes[$underscored_place_holder] = $underscored_place_holder;
  3964. }
  3965. }
  3966. }
  3967. function _getActAsClassName($behaviour)
  3968. {
  3969. return (in_array(strtolower($behaviour), $this->__coreActsLikeAttributes) ?
  3970. 'AkActsAs' : 'ActAs').AkInflector::camelize($behaviour);
  3971. }
  3972. function &_getActAsInstance($class_name, $options)
  3973. {
  3974. if(substr($class_name,0,2) == 'Ak'){
  3975. include_once(AK_LIB_DIR.DS.'AkActiveRecord'.DS.$class_name.'.php');
  3976. }
  3977. if(!class_exists($class_name)){
  3978. trigger_error(Ak::t('The class %class used for handling an "act_as %class" does not exist',array('%class'=>$class_name)), E_USER_ERROR);
  3979. $false = false;
  3980. return $false;
  3981. }else{
  3982. $ActAsInstance =& new $class_name($this, $options);
  3983. return $ActAsInstance;
  3984. }
  3985. }
  3986. function _loadActAsBehaviours()
  3987. {
  3988. $this->act_as = !empty($this->acts_as) ? $this->acts_as : (empty($this->act_as) ? false : $this->act_as);
  3989. if(!empty($this->act_as)){
  3990. if(is_string($this->act_as)){
  3991. $this->act_as = array_unique(array_diff(array_map('trim',explode(',',$this->act_as.',')), array('')));
  3992. foreach ($this->act_as as $type){
  3993. $this->actsAs($type);
  3994. }
  3995. }elseif (is_array($this->act_as)){
  3996. foreach ($this->act_as as $type=>$options){
  3997. $this->actsAs($type, $options);
  3998. }
  3999. }
  4000. }
  4001. }
  4002. /**
  4003. * Returns a comma separated list of possible acts like (active record, nested set, list)....
  4004. */
  4005. function actsLike()
  4006. {
  4007. $result = 'active record';
  4008. foreach ($this->__ActsLikeAttributes as $type){
  4009. if(!empty($this->$type) && is_object($this->$type) && method_exists($this->{$type}, 'getType')){
  4010. $result .= ','.$this->{$type}->getType();
  4011. }
  4012. }
  4013. return $result;
  4014. }
  4015. function dbug()
  4016. {
  4017. if(!$this->isConnected()){
  4018. $this->setConnection();
  4019. }
  4020. $this->_db->debug = $this->_db->debug ? false : true;
  4021. $this->db_debug =& $this->_db->debug;
  4022. }
  4023. function dbugging($trace_this_on_debug_mode = null)
  4024. {
  4025. if(!empty($this->_db->debug) && !empty($trace_this_on_debug_mode)){
  4026. $message = !is_scalar($trace_this_on_debug_mode) ? var_export($trace_this_on_debug_mode, true) : (string)$trace_this_on_debug_mode;
  4027. Ak::trace($message);
  4028. }
  4029. return !empty($this->_db->debug);
  4030. }
  4031. function extractOptionsFromArgs(&$args)
  4032. {
  4033. $_tmp_options = !empty($args) && is_array($args) && is_array($args[count($args)]) ? array_pop($args) : array();
  4034. $options = array();
  4035. foreach (array('conditions', 'include', 'joins', 'limit', 'offset', 'order', 'bind', 'select', 'readonly') as $k){
  4036. if(isset($_tmp_options[$k])){
  4037. $options[$k] = $_tmp_options[$k];
  4038. }
  4039. }
  4040. return $options;
  4041. }
  4042. /**
  4043. * Selects and filters a search result to include only specified columns
  4044. *
  4045. * $people_for_select = $People->select($People->find(),'name','email');
  4046. *
  4047. * Now $people_for_select will hold an array with
  4048. * array (
  4049. * array ('name' => 'Jose','email' => 'jose@example.com'),
  4050. * array ('name' => 'Alicia','email' => 'alicia@example.com'),
  4051. * array ('name' => 'Hilario','email' => 'hilario@example.com'),
  4052. * array ('name' => 'Bermi','email' => 'bermi@example.com')
  4053. * );
  4054. */
  4055. function select(&$source_array)
  4056. {
  4057. $resulting_array = array();
  4058. if(!empty($source_array) && is_array($source_array) && func_num_args() > 1) {
  4059. (array)$args = array_filter(array_slice(func_get_args(),1),array($this,'hasColumn'));
  4060. foreach ($source_array as $source_item){
  4061. $item_fields = array();
  4062. foreach ($args as $arg){
  4063. $item_fields[$arg] =& $source_item->get($arg);
  4064. }
  4065. $resulting_array[] =& $item_fields;
  4066. }
  4067. }
  4068. return $resulting_array;
  4069. }
  4070. /**
  4071. * Collect is a function for selecting items from double depth array
  4072. * like the ones returned by the AkActiveRecord. This comes useful when you just need some
  4073. * fields for generating tables, select lists with only desired fields.
  4074. *
  4075. * $people_for_select = Ak::select($People->find(),'id','email');
  4076. *
  4077. * Returns something like:
  4078. * array (
  4079. * array ('10' => 'jose@example.com'),
  4080. * array ('15' => 'alicia@example.com'),
  4081. * array ('16' => 'hilario@example.com'),
  4082. * array ('18' => 'bermi@example.com')
  4083. * );
  4084. */
  4085. function collect(&$source_array, $key_index, $value_index)
  4086. {
  4087. $resulting_array = array();
  4088. if(!empty($source_array) && is_array($source_array)) {
  4089. foreach ($source_array as $source_item){
  4090. $resulting_array[$source_item->get($key_index)] = $source_item->get($value_index);
  4091. }
  4092. }
  4093. return $resulting_array;
  4094. }
  4095. function hasBeenModified()
  4096. {
  4097. return Ak::objectHasBeenModified($this);
  4098. }
  4099. /**
  4100. * Database statements. Database statements is the first step of the Rails connectors port to PHP
  4101. */
  4102. /**
  4103. * Returns a record array with the column names as keys and column values
  4104. * as values.
  4105. */
  4106. function sqlSelectOne($sql, $limit = false, $offset = false)
  4107. {
  4108. $result = $this->sqlSelect($sql, $limit, $offset);
  4109. return !is_null($result) ? array_shift($result) : null;
  4110. }
  4111. /**
  4112. * Returns a single value from a record
  4113. */
  4114. function sqlSelectValue($sql, $limit = false, $offset = false)
  4115. {
  4116. $result = $this->sqlSelectOne($sql, $limit, $offset);
  4117. return !is_null($result) ? array_shift($result) : null;
  4118. }
  4119. /**
  4120. * Returns an array of the values of the first column in a select:
  4121. * sqlSelectValues("SELECT id FROM companies LIMIT 3") => array(1,2,3)
  4122. */
  4123. function sqlSelectValues($sql, $limit = false, $offset = false)
  4124. {
  4125. $values = array();
  4126. if($results = $this->sqlSelectAll($sql, $limit, $offset)){
  4127. foreach ($results as $result){
  4128. $values[] = array_slice(array_values($result),0,1);
  4129. }
  4130. }
  4131. }
  4132. /**
  4133. * Returns an array of record hashes with the column names as keys and
  4134. * column values as values.
  4135. */
  4136. function sqlSelectAll($sql, $limit = false, $offset = false)
  4137. {
  4138. return $this->sqlSelect($sql, $limit, $offset);
  4139. }
  4140. function sqlSelect($sql, $limit = false, $offset = false)
  4141. {
  4142. $results = array();
  4143. $previous_fetch_mode = $GLOBALS['ADODB_FETCH_MODE'];
  4144. $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC;
  4145. $ResultSet = $limit === false ? $this->_db->Execute($sql) : $this->_db->SelectLimit($sql, $limit, empty($offset) ? 0 : $offset);
  4146. if($ResultSet){
  4147. while ($record = $ResultSet->FetchRow()) {
  4148. $results[] = $record;
  4149. }
  4150. }else{
  4151. AK_DEBUG ? trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE) : null;
  4152. }
  4153. $GLOBALS['ADODB_FETCH_MODE'] = $previous_fetch_mode;
  4154. return empty($results) ? null : $results;
  4155. }
  4156. /**
  4157. * Active record Calculations
  4158. */
  4159. var $_calculation_options = array('conditions', 'joins', 'order', 'select', 'group', 'having', 'distinct', 'limit', 'offset');
  4160. /**
  4161. * Count operates using three different approaches.
  4162. *
  4163. * * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
  4164. * * Count by conditions or joins
  4165. * * Count using options will find the row count matched by the options used.
  4166. *
  4167. * The last approach, count using options, accepts an option hash as the only parameter. The options are:
  4168. *
  4169. * * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array("user_name = ?", $username ). See conditions in the intro.
  4170. * * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
  4171. * * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
  4172. * * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
  4173. * * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join.
  4174. * * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
  4175. *
  4176. * Examples for counting all:
  4177. * $Person->count(); // returns the total count of all people
  4178. *
  4179. * Examples for count by +conditions+ and +joins+ (this has been deprecated):
  4180. * $Person->count("age > 26"); // returns the number of people older than 26
  4181. * $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(*).
  4182. *
  4183. * Examples for count with options:
  4184. * $Person->count('conditions' => "age > 26");
  4185. * $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.
  4186. * $Person->count('id', 'conditions' => "age > 26"); // Performs a COUNT(id)
  4187. * $Person->count('all', 'conditions' => "age > 26"); // Performs a COUNT(*) ('all' is an alias for '*')
  4188. *
  4189. * Note: $Person->count('all') will not work because it will use 'all' as the condition. Use $Person->count() instead.
  4190. */
  4191. function count()
  4192. {
  4193. $args = func_get_args();
  4194. list($column_name, $options) = $this->_constructCountOptionsFromLegacyArgs($args);
  4195. return $this->calculate('count', $column_name, $options);
  4196. }
  4197. /**
  4198. * Calculates average value on a given column. The value is returned as a float. See #calculate for examples with options.
  4199. *
  4200. * $Person->average('age');
  4201. */
  4202. function average($column_name, $options = array())
  4203. {
  4204. return $this->calculate('avg', $column_name, $options);
  4205. }
  4206. /**
  4207. * 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.
  4208. *
  4209. * $Person->minimum('age');
  4210. */
  4211. function minimum($column_name, $options = array())
  4212. {
  4213. return $this->calculate('min', $column_name, $options);
  4214. }
  4215. /**
  4216. * 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.
  4217. *
  4218. * $Person->maximum('age');
  4219. */
  4220. function maximum($column_name, $options = array())
  4221. {
  4222. return $this->calculate('max', $column_name, $options);
  4223. }
  4224. /**
  4225. * 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.
  4226. *
  4227. * $Person->sum('age');
  4228. */
  4229. function sum($column_name, $options = array())
  4230. {
  4231. return $this->calculate('sum', $column_name, $options);
  4232. }
  4233. /**
  4234. * This calculates aggregate values in the given column: Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
  4235. * Options such as 'conditions', 'order', 'group', 'having', and 'joins' can be passed to customize the query.
  4236. *
  4237. * There are two basic forms of output:
  4238. * * 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.
  4239. * * Grouped values: This returns an ordered hash of the values and groups them by the 'group' option. It takes a column name.
  4240. *
  4241. * $values = $Person->maximum('age', array('group' => 'last_name'));
  4242. * echo $values["Drake"]
  4243. * => 43
  4244. *
  4245. * Options:
  4246. * * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array( "user_name = ?", username ). See conditions in the intro.
  4247. * * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
  4248. * The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
  4249. * * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
  4250. * * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
  4251. * * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join.
  4252. * * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
  4253. *
  4254. * Examples:
  4255. * $Person->calculate('count', 'all'); // The same as $Person->count();
  4256. * $Person->average('age'); // SELECT AVG(age) FROM people...
  4257. * $Person->minimum('age', array('conditions' => array('last_name != ?', 'Drake'))); // Selects the minimum age for everyone with a last name other than 'Drake'
  4258. * $Person->minimum('age', array('having' => 'min(age) > 17', 'group' => 'last'_name)); // Selects the minimum age for any family without any minors
  4259. */
  4260. function calculate($operation, $column_name, $options = array())
  4261. {
  4262. $this->_validateCalculationOptions($options);
  4263. $column_name = empty($options['select']) ? $column_name : $options['select'];
  4264. $column_name = $column_name == 'all' ? '*' : $column_name;
  4265. $column = $this->_getColumnFor($column_name);
  4266. if (!empty($options['group'])){
  4267. return $this->_executeGroupedCalculation($operation, $column_name, $column, $options);
  4268. }else{
  4269. return $this->_executeSimpleCalculation($operation, $column_name, $column, $options);
  4270. }
  4271. return 0;
  4272. }
  4273. function _constructCountOptionsFromLegacyArgs($args)
  4274. {
  4275. $options = array();
  4276. $column_name = 'all';
  4277. /*
  4278. We need to handle
  4279. count()
  4280. count(options=array())
  4281. count($column_name='all', $options=array())
  4282. count($conditions=null, $joins=null)
  4283. */
  4284. if(count($args) > 2){
  4285. trigger_error(Ak::t("Unexpected parameters passed to count(\$options=array())", E_USER_ERROR));
  4286. }elseif(count($args) > 0){
  4287. if(!empty($args[0]) && is_array($args[0])){
  4288. $options = $args[0];
  4289. }elseif(!empty($args[1]) && is_array($args[1])){
  4290. $column_name = array_shift($args);
  4291. $options = array_shift($args);
  4292. }else{
  4293. $options = array('conditions' => $args[0]);
  4294. if(!empty($args[1])){
  4295. $options = array_merge($options, array('joins' => $args[1]));
  4296. }
  4297. }
  4298. }
  4299. return array($column_name, $options);
  4300. }
  4301. function _constructCalculationSql($operation, $column_name, $options)
  4302. {
  4303. $operation = strtolower($operation);
  4304. $aggregate_alias = $this->_getColumnAliasFor($operation, $column_name);
  4305. $use_workaround = $operation == 'count' && !empty($options['distinct']) && $this->_getDatabaseType() == 'sqlite';
  4306. $sql = $use_workaround ?
  4307. "SELECT COUNT(*) AS $aggregate_alias" : // A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
  4308. "SELECT $operation(".(empty($options['distinct'])?'':'DISTINCT ')."$column_name) AS $aggregate_alias";
  4309. $sql .= empty($options['group']) ? '' : ", {$options['group_field']} AS {$options['group_alias']}";
  4310. $sql .= $use_workaround ? " FROM (SELECT DISTINCT {$column_name}" : '';
  4311. $sql .= " FROM ".$this->getTableName()." ";
  4312. $sql .= empty($options['joins']) ? '' : " {$options['joins']} ";
  4313. empty($options['conditions']) ? null : $this->addConditions($sql, $options['conditions']);
  4314. if (!empty($options['group'])){
  4315. $sql .= " GROUP BY {$options['group_field']} ";
  4316. $sql .= empty($options['having']) ? '' : " HAVING {$options['having']} ";
  4317. }
  4318. $sql .= empty($options['order']) ? '' : " ORDER BY {$options['order']} ";
  4319. $sql .= $use_workaround ? ')' : '';
  4320. return $sql;
  4321. }
  4322. function _executeSimpleCalculation($operation, $column_name, $column, $options)
  4323. {
  4324. $value = $this->sqlSelectValue($this->_constructCalculationSql($operation, $column_name, $options), empty($options['limit']) ? false : $options['limit'], !isset($options['offset']) ? false : $options['offset']);
  4325. return $this->_typeCastCalculatedValue($value, $column, $operation);
  4326. }
  4327. function _executeGroupedCalculation($operation, $column_name, $column, $options)
  4328. {
  4329. $group_attr = $options['group'];
  4330. $group_field = $options['group'];
  4331. $group_alias = $this->_getColumnAliasFor($group_field);
  4332. $group_column = $this->_getColumnFor($group_field);
  4333. $sql = $this->_constructCalculationSql($operation, $column_name, array_merge(array('group_field' => $group_field, 'group_alias' => $group_alias),$options));
  4334. $calculated_data = $this->sqlSelectAll($sql, empty($options['limit']) ? false : $options['limit'], !isset($options['offset']) ? false : $options['offset']);
  4335. $aggregate_alias = $this->_getColumnAliasFor($operation, $column_name);
  4336. $all = array();
  4337. foreach ($calculated_data as $row){
  4338. $key = $this->_typeCastCalculatedValue($row[$group_alias], $group_column);
  4339. $all[$key] = $this->_typeCastCalculatedValue($row[$aggregate_alias], $column, $operation);
  4340. }
  4341. return $all;
  4342. }
  4343. function _validateCalculationOptions($options = array())
  4344. {
  4345. $invalid_options = array_diff(array_keys($options),$this->_calculation_options);
  4346. if(!empty($invalid_options)){
  4347. trigger_error(Ak::t('%options are not valid calculation options.', array('%options'=>join(', ',$invalid_options))), E_USER_ERROR);
  4348. }
  4349. }
  4350. /**
  4351. * Converts a given key to the value that the database adapter returns as
  4352. * as a usable column name.
  4353. * users.id #=> users_id
  4354. * sum(id) #=> sum_id
  4355. * count(distinct users.id) #=> count_distinct_users_id
  4356. * count(*) #=> count_all
  4357. */
  4358. function _getColumnAliasFor()
  4359. {
  4360. $args = func_get_args();
  4361. $keys = strtolower(join(' ',(!empty($args) ? (is_array($args[0]) ? $args[0] : $args) : array())));
  4362. return preg_replace(array('/\*/','/\W+/','/^ +/','/ +$/','/ +/'),array('all',' ','','','_'), $keys);
  4363. }
  4364. function _getColumnFor($field)
  4365. {
  4366. $field_name = ltrim(substr($field,strpos($field,'.')),'.');
  4367. if(in_array($field_name,$this->getColumnNames())){
  4368. return $field_name;
  4369. }
  4370. return $field;
  4371. }
  4372. function _typeCastCalculatedValue($value, $column, $operation = null)
  4373. {
  4374. $operation = strtolower($operation);
  4375. if($operation == 'count'){
  4376. return intval($value);
  4377. }elseif ($operation == 'avg'){
  4378. return floatval($value);
  4379. }else{
  4380. return empty($column) ? $value : AkActiveRecord::castAttributeFromDatabase($column, $value);
  4381. }
  4382. }
  4383. }
  4384. ?>