PageRenderTime 76ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/app/protected/core/models/RedBeanModel.php

https://bitbucket.org/zurmo/zurmo/
PHP | 3320 lines | 2369 code | 158 blank | 793 comment | 324 complexity | 2d617da78d49a14c2fa04b349b3fa674 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, GPL-2.0, LGPL-3.0, LGPL-2.1, BSD-2-Clause
  1. <?php
  2. /*********************************************************************************
  3. * Zurmo is a customer relationship management program developed by
  4. * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc.
  5. *
  6. * Zurmo is free software; you can redistribute it and/or modify it under
  7. * the terms of the GNU Affero General Public License version 3 as published by the
  8. * Free Software Foundation with the addition of the following permission added
  9. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  10. * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
  11. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  12. *
  13. * Zurmo is distributed in the hope that it will be useful, but WITHOUT
  14. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  15. * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  16. * details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License along with
  19. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  20. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  21. * 02110-1301 USA.
  22. *
  23. * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
  24. * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
  25. *
  26. * The interactive user interfaces in original and modified versions
  27. * of this program must display Appropriate Legal Notices, as required under
  28. * Section 5 of the GNU Affero General Public License version 3.
  29. *
  30. * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  31. * these Appropriate Legal Notices must retain the display of the Zurmo
  32. * logo and Zurmo copyright notice. If the display of the logo is not reasonably
  33. * feasible for technical reasons, the Appropriate Legal Notices must display the words
  34. * "Copyright Zurmo Inc. 2015. All rights reserved".
  35. ********************************************************************************/
  36. /**
  37. * Abstraction over the top of an application database accessed via
  38. * <a href="http://www.redbeanphp.com/">RedBean</a>. The base class for
  39. * an MVC model. Replaces the M part of MVC in Yii. Yii maps from the
  40. * database scheme to the objects, (good for database guys, not so good
  41. * for OO guys), this maps from objects to the database schema.
  42. *
  43. * A domain model is created by extending RedBeanModel and supplying
  44. * a getDefaultMetadata() method.
  45. *
  46. * Static getXxxx() methods can be supplied to query for the given domain
  47. * models, and instance methods should supply additional behaviour.
  48. *
  49. * getDefaultMetadata() returns an array of the class name mapped to
  50. * an array containing 'members' mapped to an array of member names,
  51. * (to be accessed as $model->memberName).
  52. *
  53. * It can then optionally have, 'relations' mapped
  54. * to an array of relation names, (to be accessed as $model->relationName),
  55. * mapped to its type, (the extending model class to which it relates).
  56. *
  57. * And it can then optionally have as well, 'rules' mapped to an array of
  58. * attribute names, (attributes are members and relations), a validator name,
  59. * and the parameters to the validator, if any, as per the Yii::CModel::rules()
  60. * method.See http://www.yiiframework.com/wiki/56/reference-model-rules-validation.
  61. *
  62. * These are used to automatically and dynamically create the database
  63. * schema on the fly as opposed to Yii's getting attributes from an
  64. * already existing schema.
  65. */
  66. abstract class RedBeanModel extends BeanModel implements Serializable
  67. {
  68. /**
  69. * Character used as delimiter when generating model identifiers
  70. */
  71. const MODEL_IDENTIFIER_DELIMITER = '_';
  72. /**
  73. * Models that have not been saved yet have no id as far
  74. * as the database is concerned. Until they are saved they are
  75. * assigned a negative id, so that they have identity.
  76. * @var integer
  77. */
  78. private static $nextPseudoId = -1;
  79. /**
  80. * Array of static models. Used by Observers @see ObservableComponent to add events to a class.
  81. * @var array
  82. */
  83. private static $_models = array();
  84. /*
  85. * The id of an unsaved model.
  86. * @var integer
  87. */
  88. private $pseudoId;
  89. /**
  90. * When creating the class heirarchy for bean creation and maintenence, which class is the last class in the
  91. * lineage to create a bean for? Normally the RedBeanModel is the lastClass in the line, and therefore there
  92. * will not be a table redbeanmodel. Some classes that extend RedBeanModel might want the line to stop before
  93. * RedBeanModel since creating a table with just an 'id' would be pointless. @see OwnedModel
  94. * @var string
  95. */
  96. protected static $lastClassInBeanHeirarchy = 'RedBeanModel';
  97. // A model maps to one or more beans. If Person extends RedBeanModel
  98. // there is one bean, but if User then extends Person a User model
  99. // has two beans, the one holding the person data and the one holding
  100. // the extended User data. In this way in inheritance hierarchy from
  101. // model is normalized over several tables, one for each extending
  102. // class.
  103. protected $modelClassNameToBean = array();
  104. protected $attributeNameToBeanAndClassName = array();
  105. protected $relationNameToRelatedModel = array();
  106. protected $unlinkedRelationNames = array();
  107. protected $unlinkedOwnedRelatedModelsToRemove = array();
  108. protected $validators = array();
  109. protected $attributeNameToErrors = array();
  110. protected $scenarioName = '';
  111. // An object is automatically savable if it is new or contains
  112. // modified members or related objects.
  113. // If it is newly created and has never had any data put into it
  114. // it can be saved explicitly but it wont be saved automatically
  115. // when it is a related model and will be redispensed next
  116. // time it is referenced.
  117. protected $modified = false;
  118. protected $deleted = false;
  119. protected $isInIsModified = false;
  120. protected $isInHasErrors = false;
  121. protected $isInGetErrors = false;
  122. protected $isValidating = false;
  123. protected $isSaving = false;
  124. protected $isDeleting = false;
  125. protected $isNewModel = false;
  126. protected $isCopied = false;
  127. /**
  128. * Can this model be saved when save is called from a related model? True if it can, false if it cannot.
  129. * Setting this value to false can reduce unnecessary queries to the database. If the models of a class do
  130. * not change often then it can make sense to set this to false. An example is @see Currency.
  131. * @var boolean
  132. */
  133. protected $isSavableFromRelation = true;
  134. // Mapping of Yii validators to validators doing things that
  135. // are either required for RedBean, or that simply implement
  136. // The semantics that we want.
  137. private static $yiiValidatorsToRedBeanValidators = array(
  138. 'CDefaultValueValidator' => 'RedBeanModelDefaultValueValidator',
  139. 'CNumberValidator' => 'RedBeanModelNumberValidator',
  140. 'CTypeValidator' => 'RedBeanModelTypeValidator',
  141. 'CRequiredValidator' => 'RedBeanModelRequiredValidator',
  142. 'CUniqueValidator' => 'RedBeanModelUniqueValidator',
  143. 'defaultCalculatedDate' => 'RedBeanModelDefaultCalculatedDateValidator',
  144. 'readOnly' => 'RedBeanModelReadOnlyValidator',
  145. 'dateTimeDefault' => 'RedBeanModelDateTimeDefaultValueValidator',
  146. 'probability' => 'RedBeanModelProbabilityValidator',
  147. );
  148. /**
  149. * Stores the attributeLabelsByLanguage
  150. * @var array
  151. */
  152. protected static $attributeLabelsByLanguage = array();
  153. /**
  154. * Returns the static model of the specified AR class.
  155. * The model returned is a static instance of the AR class.
  156. * It is provided for invoking class-level methods (something similar to static class methods.)
  157. *
  158. * EVERY derived AR class must override this method as follows,
  159. * <pre>
  160. * public static function model($className=__CLASS__)
  161. * {
  162. * return parent::model($className);
  163. * }
  164. * </pre>
  165. *
  166. * This method will make a model that does not run construction
  167. *
  168. * @param string $className active record class name.
  169. * @return CActiveRecord active record model instance.
  170. */
  171. public static function model($className = null)
  172. {
  173. if ($className == null)
  174. {
  175. $className = get_called_class();
  176. }
  177. if (isset(self::$_models[$className]))
  178. {
  179. return self::$_models[$className];
  180. }
  181. else
  182. {
  183. $model = self::$_models[$className] = new $className(false, null, false, false);
  184. return $model;
  185. }
  186. }
  187. /**
  188. * Gets all the models from the database of the named model type.
  189. * @param $orderBy TODO
  190. * @param $modelClassName Pass only when getting it at runtime
  191. * gets the wrong name.
  192. * @return An array of models of the type of the extending model.
  193. */
  194. public static function getAll($orderBy = null, $sortDescending = false, $modelClassName = null)
  195. {
  196. assert('$orderBy === null || is_string($orderBy) && $orderBy != ""');
  197. assert('is_bool($sortDescending)');
  198. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  199. $quote = DatabaseCompatibilityUtil::getQuote();
  200. $orderBySql = null;
  201. if ($orderBy !== null)
  202. {
  203. $orderBySql = "$quote$orderBy$quote";
  204. if ($sortDescending)
  205. {
  206. $orderBySql .= ' desc';
  207. }
  208. }
  209. return static::getSubset(null, null, null, null, $orderBySql, $modelClassName);
  210. }
  211. /**
  212. * Gets a range of models from the database of the named model type.
  213. * @param $modelClassName
  214. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  215. * @param $offset The zero based index of the first model to be returned.
  216. * @param $count The number of models to be returned.
  217. * @param $where
  218. * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'. Currently only supports non-related attributes
  219. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  220. * @return An array of models of the type of the extending model.
  221. */
  222. public static function getSubset(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  223. $offset = null, $count = null,
  224. $where = null, $orderBy = null,
  225. $modelClassName = null,
  226. $selectDistinct = false)
  227. {
  228. assert('$offset === null || is_integer($offset) && $offset >= 0');
  229. assert('$count === null || is_integer($count) && $count >= 1');
  230. assert('$where === null || is_string ($where) && $where != ""');
  231. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  232. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  233. if ($modelClassName === null)
  234. {
  235. $modelClassName = get_called_class();
  236. }
  237. $ids = self::getSubsetIds($joinTablesAdapter, $offset, $count, $where,
  238. $orderBy, $modelClassName, $selectDistinct);
  239. $tableName = $modelClassName::getTableName();
  240. $beans = ZurmoRedBean::batch ($tableName, $ids);
  241. return self::makeModels($beans, $modelClassName);
  242. }
  243. /**
  244. * Gets a range of model ids from the database of the named model type.
  245. * @param $modelClassName
  246. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  247. * @param $offset The zero based index of the first model to be returned.
  248. * @param $count The number of models to be returned.
  249. * @param $where
  250. * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'. Currently only supports non-related attributes
  251. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  252. * @return An array of models ids
  253. */
  254. public static function getSubsetIds(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  255. $offset = null, $count = null,
  256. $where = null, $orderBy = null,
  257. $modelClassName = null,
  258. $selectDistinct = false)
  259. {
  260. assert('$offset === null || is_integer($offset) && $offset >= 0');
  261. assert('$count === null || is_integer($count) && $count >= 1');
  262. assert('$where === null || is_string ($where) && $where != ""');
  263. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  264. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  265. if ($modelClassName === null)
  266. {
  267. $modelClassName = get_called_class();
  268. }
  269. if ($joinTablesAdapter == null)
  270. {
  271. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  272. }
  273. $tableName = $modelClassName::getTableName();
  274. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, $offset, $count, $where,
  275. $orderBy, false, $selectDistinct);
  276. $ids = ZurmoRedBean::getCol($sql);
  277. return $ids;
  278. }
  279. /**
  280. * @param boolean $selectCount If true then make this a count query. If false, select ids from rows.
  281. * @param array $quotedExtraSelectColumnNameAndAliases - extra columns to select.
  282. * @return string - sql statement.
  283. */
  284. public static function makeSubsetOrCountSqlQuery($tableName,
  285. RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter,
  286. $offset = null, $count = null,
  287. $where = null, $orderBy = null,
  288. $selectCount = false,
  289. $selectDistinct = false,
  290. array $quotedExtraSelectColumnNameAndAliases = array())
  291. {
  292. assert('is_string($tableName) && $tableName != ""');
  293. assert('$offset === null || is_integer($offset) && $offset >= 0');
  294. assert('$count === null || is_integer($count) && $count >= 1');
  295. assert('$where === null || is_string ($where) && $where != ""');
  296. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  297. assert('is_bool($selectCount)');
  298. assert('is_bool($selectDistinct)');
  299. $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
  300. if ($selectCount)
  301. {
  302. $selectQueryAdapter->addCountClause($tableName);
  303. }
  304. else
  305. {
  306. $selectQueryAdapter->addClause($tableName, 'id', 'id');
  307. }
  308. foreach ($quotedExtraSelectColumnNameAndAliases as $columnName => $columnAlias)
  309. {
  310. $selectQueryAdapter->addClauseWithColumnNameOnlyAndNoEnclosure($columnName, $columnAlias);
  311. }
  312. return SQLQueryUtil::
  313. makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, $offset, $count, $where, $orderBy);
  314. }
  315. /**
  316. * @param $modelClassName
  317. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  318. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  319. */
  320. public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  321. $where = null, $modelClassName = null, $selectDistinct = false)
  322. {
  323. assert('$where === null || is_string($where)');
  324. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  325. if ($modelClassName === null)
  326. {
  327. $modelClassName = get_called_class();
  328. }
  329. if ($joinTablesAdapter == null)
  330. {
  331. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  332. }
  333. $tableName = $modelClassName::getTableName();
  334. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true,
  335. $selectDistinct);
  336. $count = ZurmoRedBean::getCell($sql);
  337. if ($count === null || empty($count))
  338. {
  339. $count = 0;
  340. }
  341. return intval($count);
  342. }
  343. /**
  344. * Gets a model from the database by Id.
  345. * @param $id Integer Id.
  346. * @param $modelClassName Pass only when getting it at runtime
  347. * gets the wrong name.
  348. * @return A model of the type of the extending model.
  349. */
  350. public static function getById($id, $modelClassName = null)
  351. {
  352. assert('is_integer($id) && $id > 0');
  353. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  354. // I would have thought it was correct to user ZurmoRedBean::load() and get
  355. // a null, or error or something if the bean doesn't exist, but
  356. // it still returns a bean. So until I've investigated further
  357. // I'm using Finder.
  358. if ($modelClassName === null)
  359. {
  360. $modelClassName = get_called_class();
  361. }
  362. $tableName = $modelClassName::getTableName();
  363. $beans = ZurmoRedBean::find($tableName, "id = '$id'");
  364. assert('count($beans) <= 1');
  365. if (count($beans) == 0)
  366. {
  367. throw new NotFoundException();
  368. }
  369. return static::makeModel(end($beans), $modelClassName);
  370. }
  371. public function getIsNewModel()
  372. {
  373. return $this->isNewModel;
  374. }
  375. /**
  376. * Constructs a new model.
  377. * Important:
  378. * Models are only constructed with beans by the RedBeanModel. Beans are
  379. * never used by the application directly.
  380. * The application can construct a new model object by constructing a
  381. * model without specifying a bean. In other words, if Php had
  382. * overloading a constructor with $setDefaults would be public, and
  383. * a constructor taking a $bean and $forceTreatAsCreation would be private.
  384. * @param $setDefaults. If false the default validators will not be run
  385. * on construction. The Yii way is that defaults are
  386. * filled in after the fact, which is counter the usual
  387. * for objects.
  388. * @param $bean A bean. Never specified by an application.
  389. * @param $forceTreatAsCreation. Never specified by an application.
  390. * @param $runConstruction. Sometimes a model is needed to hook in events and the construction logic
  391. * does not necessarily need to be run.
  392. * @see getById()
  393. * @see makeModel()
  394. * @see makeModels()
  395. */
  396. public function __construct($setDefaults = true, RedBean_OODBBean $bean = null, $forceTreatAsCreation = false,
  397. $runConstruction = true)
  398. {
  399. $this->pseudoId = self::$nextPseudoId--;
  400. $this->init();
  401. if (!$runConstruction)
  402. {
  403. return;
  404. }
  405. if ($bean === null)
  406. {
  407. foreach (array_reverse(RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy)) as $modelClassName)
  408. {
  409. if ($modelClassName::getCanHaveBean())
  410. {
  411. $tableName = $modelClassName::getTableName();
  412. $newBean = ZurmoRedBean::dispense($tableName);
  413. $this->modelClassNameToBean[$modelClassName] = $newBean;
  414. $this->mapAndCacheMetadataAndSetHints($modelClassName, $newBean);
  415. }
  416. }
  417. // The yii way of doing defaults is the the default validator
  418. // fills in the defaults on attributes that don't have values
  419. // when you validator, or save. This weird, since when you get
  420. // a model the things with defaults have not been defaulted!
  421. // We want that semantic.
  422. if ($setDefaults)
  423. {
  424. $this->runDefaultValidators();
  425. }
  426. $forceTreatAsCreation = true;
  427. }
  428. else
  429. {
  430. assert('$bean->id > 0');
  431. $first = true;
  432. foreach (RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy) as $modelClassName)
  433. {
  434. if ($modelClassName::getCanHaveBean())
  435. {
  436. if ($first)
  437. {
  438. $lastBean = $bean;
  439. $first = false;
  440. }
  441. else
  442. {
  443. $tableName = $modelClassName::getTableName();
  444. $lastBean = ZurmoRedBeanLinkManager::getBean($lastBean, $tableName);
  445. if ($lastBean === null)
  446. {
  447. throw new MissingBeanException();
  448. }
  449. assert('$lastBean->id > 0');
  450. }
  451. $this->modelClassNameToBean[$modelClassName] = $lastBean;
  452. $this->mapAndCacheMetadataAndSetHints($modelClassName, $lastBean);
  453. }
  454. }
  455. $this->modelClassNameToBean = array_reverse($this->modelClassNameToBean);
  456. }
  457. $this->constructDerived($bean, $setDefaults);
  458. if ($forceTreatAsCreation)
  459. {
  460. $this->onCreated();
  461. }
  462. else
  463. {
  464. $this->onLoaded();
  465. $modelClassName = get_called_class();
  466. if ($modelClassName::isCacheable())
  467. {
  468. RedBeanModelsCache::cacheModel($this);
  469. }
  470. }
  471. $this->modified = false;
  472. }
  473. /**
  474. * Delete all models
  475. */
  476. public static function deleteAll()
  477. {
  478. if (static::getCanHaveBean() && static::isTypeDeletable())
  479. {
  480. foreach (static::getAll() as $model)
  481. {
  482. if (!$model->delete())
  483. {
  484. throw new NotSupportedException("Unable to delete id# " . $model->id);
  485. }
  486. }
  487. // we could have used ZurmoRedBean::$writer->wipe() but that won't fire events related to delete.
  488. }
  489. else
  490. {
  491. throw new NotSupportedException(get_called_class() . "Can either not have bean or is not deletable");
  492. }
  493. }
  494. // Derived classes can insert additional steps into the construction.
  495. protected function constructDerived($bean, $setDefaults)
  496. {
  497. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  498. assert('is_bool($setDefaults)');
  499. }
  500. /**
  501. * Utilized when pieces of information need to be constructed on an existing model, that can potentially be
  502. * missing. For example, if a model is created, then a custom field is added, it is possible the cached model
  503. * is missing the custom field customFieldData.
  504. * @param unknown_type $bean
  505. */
  506. protected function constructIncomplete($bean)
  507. {
  508. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  509. $this->init();
  510. }
  511. public function serialize()
  512. {
  513. return serialize(array(
  514. $this->pseudoId,
  515. $this->modelClassNameToBean,
  516. $this->attributeNameToBeanAndClassName,
  517. $this->validators,
  518. ));
  519. }
  520. public function unserialize($data)
  521. {
  522. try
  523. {
  524. $data = unserialize($data);
  525. assert('is_array($data)');
  526. if (count($data) != 4)
  527. {
  528. return null;
  529. }
  530. $this->pseudoId = $data[0];
  531. $this->modelClassNameToBean = $data[1];
  532. $this->attributeNameToBeanAndClassName = $data[2];
  533. $this->validators = $data[3];
  534. $this->relationNameToRelatedModel = array();
  535. $this->unlinkedRelationNames = array();
  536. $this->unlinkedOwnedRelatedModelsToRemove = array();
  537. $this->attributeNameToErrors = array();
  538. $this->scenarioName = '';
  539. $this->modified = false;
  540. $this->deleted = false;
  541. $this->isInIsModified = false;
  542. $this->isInHasErrors = false;
  543. $this->isInGetErrors = false;
  544. $this->isValidating = false;
  545. $this->isSaving = false;
  546. $this->isDeleting = false;
  547. }
  548. catch (Exception $e)
  549. {
  550. return null;
  551. }
  552. }
  553. /**
  554. * Overriding constructors must call this function to ensure that
  555. * they leave the newly constructed instance not modified since
  556. * anything modifying the class during constructionm will set it
  557. * modified automatically.
  558. */
  559. protected function setNotModified()
  560. {
  561. $this->modified = false; // This sets this class to the right state.
  562. assert('!$this->isModified()'); // This tests that related classes are in the right state.
  563. }
  564. /**
  565. * By default the table name is the lowercased class name. If this
  566. * conflicts with a database keyword override to return true.
  567. * RedBean does not quote table names in most cases.
  568. */
  569. // Public for unit testing.
  570. public static function mangleTableName()
  571. {
  572. return false;
  573. }
  574. /**
  575. * Returns the table name for a class.
  576. * For use by RedBeanModelDataProvider. It will not
  577. * be of any use to an application. Applications
  578. * should not be doing anything table related.
  579. * Derived classes can refer directly to the
  580. * table name.
  581. */
  582. public static function getTableName()
  583. {
  584. // You could also call it on objects like: $model::getTableName() or
  585. // $model->getTableName() but it would be preferable to keep it accessed through class, statically.
  586. $modelClassName = get_called_class();
  587. $tableName = strtolower($modelClassName);
  588. if ($modelClassName::mangleTableName())
  589. {
  590. $tableName = '_' . $tableName;
  591. }
  592. return $tableName;
  593. }
  594. /**
  595. * Returns the table names for an array of classes.
  596. * For use by RedBeanModelDataProvider. It will not
  597. * be of any use to an application.
  598. */
  599. public static function getTableNames($classNames)
  600. {
  601. $tableNames = array();
  602. foreach ($classNames as $className)
  603. {
  604. $tableNames[] = $className::getTableName();
  605. }
  606. return $tableNames;
  607. }
  608. /**
  609. * Used by classes such as containers which use sql to
  610. * optimize getting models from the database.
  611. */
  612. public static function getForeignKeyName($modelClassName, $relationName)
  613. {
  614. assert('is_string($modelClassName)');
  615. assert('$modelClassName != ""');
  616. $metadata = $modelClassName::getMetadata();
  617. foreach ($metadata as $modelClassName => $modelClassMetadata)
  618. {
  619. if (isset($metadata[$modelClassName]["relations"]) &&
  620. array_key_exists($relationName, $metadata[$modelClassName]["relations"]))
  621. {
  622. $relatedModelClassName = $metadata[$modelClassName]['relations'][$relationName][1];
  623. self::resolveModelClassNameForClassesWithoutBeans($relatedModelClassName);
  624. $relatedModelTableName = $relatedModelClassName::getTableName();
  625. $linkType = null;
  626. $relationLinkName = null;
  627. self::resolveLinkTypeAndRelationLinkName($metadata[$modelClassName]['relations'][$relationName],
  628. $linkType,
  629. $relationLinkName);
  630. $linkName = self::makeCasedLinkName($metadata[$modelClassName]['relations'][$relationName][0],
  631. $linkType, $relationLinkName);
  632. if ($metadata[$modelClassName]['relations'][$relationName][0] == self::HAS_MANY ||
  633. $metadata[$modelClassName]['relations'][$relationName][0] == self::HAS_ONE_BELONGS_TO)
  634. {
  635. $columnName = $modelClassName::getTableName() . '_id';
  636. }
  637. else
  638. {
  639. $columnName = $relatedModelTableName . '_id';
  640. }
  641. $columnName = ZurmoRedBeanLinkManager::resolveColumnPrefix($linkName) . $columnName;
  642. return $columnName;
  643. }
  644. }
  645. throw new NotSupportedException;
  646. }
  647. /**
  648. * Called on construction when a new model is created.
  649. */
  650. protected function onCreated()
  651. {
  652. if ($this->hasEventHandler('onCreated'))
  653. {
  654. $event = new CModelEvent($this);
  655. $this->onCreated($event);
  656. }
  657. }
  658. /**
  659. * Called on construction when a model is loaded.
  660. */
  661. protected function onLoaded()
  662. {
  663. if ($this->hasEventHandler('onLoaded'))
  664. {
  665. $event = new CModelEvent($this);
  666. $this->onLoaded($event);
  667. }
  668. }
  669. /**
  670. * Called when a model is modified.
  671. */
  672. protected function onModified()
  673. {
  674. }
  675. protected static function makeCasedLinkName($relationType, $linkType, $relationLinkName)
  676. {
  677. assert('is_int($relationType)');
  678. assert('is_int($linkType)');
  679. assert('is_string($relationLinkName) || $relationLinkName == null');
  680. if (($relationType == self::HAS_ONE || $relationType == self::HAS_MANY ||
  681. $relationType == self::HAS_ONE_BELONGS_TO) && $linkType == self::LINK_TYPE_SPECIFIC)
  682. {
  683. return strtolower($relationLinkName);
  684. }
  685. }
  686. /**
  687. * Used for mixins.
  688. */
  689. protected function mapAndCacheMetadataAndSetHints($modelClassName, RedBean_OODBBean $bean)
  690. {
  691. assert('is_string($modelClassName)');
  692. assert('$modelClassName != ""');
  693. $metadata = $this->getMetadata();
  694. if (isset($metadata[$modelClassName]))
  695. {
  696. $hints = array();
  697. if (isset($metadata[$modelClassName]['members']))
  698. {
  699. foreach ($metadata[$modelClassName]['members'] as $memberName)
  700. {
  701. $this->attributeNameToBeanAndClassName[$memberName] = array($bean, $modelClassName);
  702. //$this->attributeNamesNotBelongsToOrManyMany[] = $memberName;
  703. if (substr($memberName, -2) == 'Id')
  704. {
  705. $columnName = strtolower($memberName);
  706. $hints[$columnName] = 'id';
  707. }
  708. }
  709. }
  710. if (isset($metadata[$modelClassName]['relations']))
  711. {
  712. foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
  713. {
  714. assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3, 4, 5))');
  715. $relationType = $relationTypeModelClassNameAndOwns[0];
  716. $relationModelClassName = $relationTypeModelClassNameAndOwns[1];
  717. if ($relationType == self::HAS_MANY_BELONGS_TO &&
  718. strtolower($relationName) != strtolower($relationModelClassName))
  719. {
  720. throw new NotSupportedException(Zurmo::t('Core', 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
  721. 'the same as the related model class name. Relation: {relationName} ' .
  722. 'Relation model class name: {relationModelClassName}',
  723. array('{relationName}' => $relationName,
  724. '{relationModelClassName}' => $relationModelClassName)));
  725. }
  726. if (count($relationTypeModelClassNameAndOwns) >= 3 &&
  727. $relationTypeModelClassNameAndOwns[2] == self::OWNED)
  728. {
  729. $owns = true;
  730. }
  731. else
  732. {
  733. $owns = false;
  734. }
  735. // $linkType = null;
  736. // $relationLinkName = null;
  737. // self::resolveLinkTypeAndRelationLinkName($relationTypeModelClassNameAndOwns, $linkType,
  738. // $relationLinkName);
  739. assert('in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, ' .
  740. 'self::HAS_ONE, self::HAS_MANY, self::MANY_MANY))');
  741. $this->attributeNameToBeanAndClassName[$relationName] = array($bean, $modelClassName);
  742. /**
  743. $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName] = array($relationType,
  744. $relationModelClassName,
  745. $owns,
  746. $linkType,
  747. $relationLinkName);
  748. * **/
  749. if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, self::MANY_MANY)))
  750. {
  751. //$this->attributeNamesNotBelongsToOrManyMany[] = $relationName;
  752. }
  753. }
  754. }
  755. // Add model validators. Parent validators are already applied.
  756. if (isset($metadata[$modelClassName]['rules']))
  757. {
  758. foreach ($metadata[$modelClassName]['rules'] as $validatorMetadata)
  759. {
  760. assert('isset($validatorMetadata[0])');
  761. assert('isset($validatorMetadata[1])');
  762. $attributeName = $validatorMetadata[0];
  763. // Each rule in RedBeanModel must specify one attribute name.
  764. // This was just better style, now it is mandatory.
  765. assert('strpos($attributeName, " ") === false');
  766. $validatorName = $validatorMetadata[1];
  767. $validatorParameters = array_slice($validatorMetadata, 2);
  768. if (isset(CValidator::$builtInValidators[$validatorName]))
  769. {
  770. $validatorName = CValidator::$builtInValidators[$validatorName];
  771. }
  772. if (isset(self::$yiiValidatorsToRedBeanValidators[$validatorName]))
  773. {
  774. $validatorName = self::$yiiValidatorsToRedBeanValidators[$validatorName];
  775. }
  776. $validator = CValidator::createValidator($validatorName, $this, $attributeName, $validatorParameters);
  777. switch ($validatorName)
  778. {
  779. case 'RedBeanModelTypeValidator':
  780. case 'TypeValidator':
  781. $columnName = strtolower($attributeName);
  782. if (array_key_exists($columnName, $hints))
  783. {
  784. unset($hints[$columnName]);
  785. }
  786. if (in_array($validator->type, array('date', 'datetime', 'blob', 'longblob', 'string', 'text', 'longtext')))
  787. {
  788. $hints[$columnName] = $validator->type;
  789. }
  790. break;
  791. case 'CBooleanValidator':
  792. $columnName = strtolower($attributeName);
  793. $hints[$columnName] = 'boolean';
  794. break;
  795. case 'RedBeanModelUniqueValidator':
  796. if (!static::isRelation($attributeName))
  797. {
  798. $bean->setMeta("buildcommand.unique", array(array($attributeName)));
  799. }
  800. else
  801. {
  802. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  803. $relatedModelClassName = $relationAndOwns[$attributeName][1];
  804. $relatedModelTableName = $relatedModelClassName::getTableName();
  805. $columnName = strtolower($attributeName);
  806. if ($columnName != $relatedModelTableName)
  807. {
  808. $columnName .= '_' . $relatedModelTableName;
  809. }
  810. $columnName .= '_id';
  811. $bean->setMeta("buildcommand.unique", array(array($columnName)));
  812. }
  813. break;
  814. }
  815. $this->validators[] = $validator;
  816. }
  817. // Check if we need to update string type to long string type, based on validators.
  818. if (isset($metadata[$modelClassName]['members']))
  819. {
  820. foreach ($metadata[$modelClassName]['members'] as $memberName)
  821. {
  822. $allValidators = $this->getValidators($memberName);
  823. if (!empty($allValidators))
  824. {
  825. foreach ($allValidators as $validator)
  826. {
  827. if ((get_class($validator) == 'RedBeanModelTypeValidator' ||
  828. get_class($validator) == 'TypeValidator') &&
  829. $validator->type == 'string')
  830. {
  831. $columnName = strtolower($validator->attributes[0]);
  832. if (count($allValidators) > 1)
  833. {
  834. $haveCStringValidator = false;
  835. foreach ($allValidators as $innerValidator)
  836. {
  837. if (get_class($innerValidator) == 'CStringValidator' &&
  838. isset($innerValidator->max) &&
  839. $innerValidator->max > 0)
  840. {
  841. if ($innerValidator->max > 65535)
  842. {
  843. $hints[$columnName] = 'longtext';
  844. }
  845. elseif ($innerValidator->max < 255)
  846. {
  847. $hints[$columnName] = "string({$innerValidator->max})";
  848. }
  849. else
  850. {
  851. $hints[$columnName] = 'text';
  852. }
  853. }
  854. if (get_class($innerValidator) == 'CStringValidator')
  855. {
  856. $haveCStringValidator = true;
  857. }
  858. }
  859. if (!$haveCStringValidator)
  860. {
  861. $hints[$columnName] = 'text';
  862. }
  863. }
  864. else
  865. {
  866. $hints[$columnName] = 'text';
  867. }
  868. }
  869. }
  870. }
  871. }
  872. }
  873. }
  874. $bean->setMeta('hint', $hints);
  875. }
  876. }
  877. /**
  878. * Used for mixins.
  879. */
  880. protected function runDefaultValidators()
  881. {
  882. foreach ($this->validators as $validator)
  883. {
  884. if ($validator instanceof CDefaultValueValidator)
  885. {
  886. $validator->validate($this);
  887. }
  888. }
  889. }
  890. /**
  891. * For use only by RedBeanModel and RedBeanModels. Beans are
  892. * never used by the application directly.
  893. */
  894. public function getPrimaryBean()
  895. {
  896. return end($this->modelClassNameToBean);
  897. }
  898. /**
  899. * Used for optimization.
  900. */
  901. public function getClassId($modelClassName)
  902. {
  903. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  904. return intval($this->getClassBean($modelClassName)->id); // Trying to combat the slop.
  905. }
  906. public function getClassBean($modelClassName)
  907. {
  908. assert('is_string($modelClassName)');
  909. assert('$modelClassName != ""');
  910. self::resolveModelClassNameForClassesWithoutBeans($modelClassName);
  911. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  912. return $this->modelClassNameToBean[$modelClassName];
  913. }
  914. /**
  915. * Used for mixins.
  916. */
  917. protected function setClassBean($modelClassName, RedBean_OODBBean $bean)
  918. {
  919. assert('is_string($modelClassName)');
  920. assert('$modelClassName != ""');
  921. assert('!array_key_exists($modelClassName, $this->modelClassNameToBean)');
  922. $this->modelClassNameToBean = array_merge(array($modelClassName => $bean),
  923. $this->modelClassNameToBean);
  924. }
  925. public function getModelIdentifier()
  926. {
  927. $className = get_class($this);
  928. $beanId = strval($this->getPrimaryBean()->id);
  929. $modelIdentifier = static::getModelIdentifierByClassNameAndBeanId($className, $beanId);
  930. return $modelIdentifier;
  931. }
  932. protected static function getModelIdentifierByClassNameAndBeanId($modelClassName, $beanId)
  933. {
  934. return $modelClassName . static::MODEL_IDENTIFIER_DELIMITER . $beanId;
  935. }
  936. public static function getModelClassNameByIdentifier($identifier)
  937. {
  938. $identifierTokens = explode(static::MODEL_IDENTIFIER_DELIMITER, $identifier);
  939. return $identifierTokens[0];
  940. }
  941. /**
  942. * Returns metadata for the model. Attempts to cache metadata, if it is not already cached.
  943. * @see getDefaultMetadata()
  944. * @returns An array of metadata.
  945. */
  946. public static function getMetadata()
  947. {
  948. try
  949. {
  950. // not using default value to save cpu cycles on requests that follow the first exception.
  951. return GeneralCache::getEntry(get_called_class() . 'Metadata');
  952. }
  953. catch (NotFoundException $e)
  954. {
  955. $className = get_called_Class();
  956. $defaultMetadata = $className::getDefaultMetadata();
  957. $metadata = array();
  958. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
  959. {
  960. if ($modelClassName::getCanHaveBean())
  961. {
  962. if ($modelClassName::canSaveMetadata())
  963. {
  964. try
  965. {
  966. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  967. $metadata[$modelClassName] = unserialize($globalMetadata->serializedMetadata);
  968. }
  969. catch (NotFoundException $e)
  970. {
  971. if (isset($defaultMetadata[$modelClassName]))
  972. {
  973. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  974. }
  975. }
  976. }
  977. else
  978. {
  979. if (isset($defaultMetadata[$modelClassName]))
  980. {
  981. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  982. }
  983. }
  984. }
  985. }
  986. if (YII_DEBUG)
  987. {
  988. self::assertMetadataIsValid($metadata);
  989. }
  990. GeneralCache::cacheEntry(get_called_class() . 'Metadata', $metadata);
  991. return $metadata;
  992. }
  993. }
  994. /**
  995. * By default models cannot save their metadata, allowing
  996. * them to be loaded quickly because the loading of of
  997. * metadata can be avoided as much as possible.
  998. * To make a model able to save its metadata override
  999. * this method to return true. PUT it before the
  1000. * getDefaultMetadata in the derived class.
  1001. */
  1002. public static function canSaveMetadata()
  1003. {
  1004. return false;
  1005. }
  1006. /**
  1007. * Sets metadata for the model.
  1008. * @see getDefaultMetadata()
  1009. * @returns An array of metadata.
  1010. */
  1011. public static function setMetadata(array $metadata)
  1012. {
  1013. if (YII_DEBUG)
  1014. {
  1015. self::assertMetadataIsValid($metadata);
  1016. }
  1017. $className = get_called_class();
  1018. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
  1019. {
  1020. if ($modelClassName::getCanHaveBean())
  1021. {
  1022. if ($modelClassName::canSaveMetadata())
  1023. {
  1024. if (isset($metadata[$modelClassName]))
  1025. {
  1026. try
  1027. {
  1028. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  1029. }
  1030. catch (NotFoundException $e)
  1031. {
  1032. $globalMetadata = new GlobalMetadata();
  1033. $globalMetadata->className = $modelClassName;
  1034. }
  1035. $globalMetadata->serializedMetadata = serialize($metadata[$modelClassName]);
  1036. $saved = $globalMetadata->save();
  1037. // TODO: decide how to deal with this properly if it fails.
  1038. // ie: throw or return false, or something other than
  1039. // this naughty assert.
  1040. assert('$saved');
  1041. }
  1042. }
  1043. }
  1044. }
  1045. self::forgetBeanModel(get_called_class());
  1046. RedBeanModelsCache::forgetAllByModelType(get_called_class());
  1047. GeneralCache::forgetEntry(get_called_class() . 'Metadata');
  1048. }
  1049. /**
  1050. * Returns the default meta data for the class.
  1051. * It must be appended to the meta data
  1052. * from the parent model, if any.
  1053. */
  1054. public static function getDefaultMetadata()
  1055. {
  1056. return array();
  1057. }
  1058. protected static function assertMetadataIsValid(array $metadata)
  1059. {
  1060. $className = get_called_Class();
  1061. foreach (RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy) as $modelClassName)
  1062. {
  1063. if ($modelClassName::getCanHaveBean())
  1064. {
  1065. if (isset($metadata[$modelClassName]['members']))
  1066. {
  1067. assert('is_array($metadata[$modelClassName]["members"])');
  1068. foreach ($metadata[$modelClassName]["members"] as $memberName)
  1069. {
  1070. assert('ctype_lower($memberName{0})');
  1071. }
  1072. }
  1073. if (isset($metadata[$modelClassName]['relations']))
  1074. {
  1075. assert('is_array($metadata[$modelClassName]["relations"])');
  1076. foreach ($metadata[$modelClassName]["relations"] as $relationName => $notUsed)
  1077. {
  1078. assert('ctype_lower($relationName{0})');
  1079. }
  1080. }
  1081. if (isset($metadata[$modelClassName]['indexes']))
  1082. {
  1083. assert('is_array($metadata[$modelClassName]["indexes"])');
  1084. foreach ($metadata[$modelClassName]["indexes"] as $indexName => $notUsed)
  1085. {
  1086. assert('ctype_lower($indexName{0})');
  1087. }
  1088. }
  1089. if (isset($metadata[$modelClassName]['rules']))
  1090. {
  1091. assert('is_array($metadata[$modelClassName]["rules"])');
  1092. }
  1093. if (isset($metadata[$modelClassName]['defaultSortAttribute']))
  1094. {
  1095. assert('is_string($metadata[$modelClassName]["defaultSortAttribute"])');
  1096. }
  1097. if (isset($metadata[$modelClassName]['rollupRelations']))
  1098. {
  1099. assert('is_array($metadata[$modelClassName]["rollupRelations"])');
  1100. }
  1101. }
  1102. }
  1103. }
  1104. /**
  1105. * Downcasting in general is a bad concept, but when pulling
  1106. * a Person from the database it would require a lot of
  1107. * jumping through hoops to make the RedBeanModel automatically
  1108. * figure out if that person is really a User, Contact, Customer
  1109. * or whatever might be derived from Person. So to avoid that
  1110. * complication and performance hit where it is not necessary
  1111. * this method can be used to convert a model to one of
  1112. * a given set of derivatives. If model is not one
  1113. * of those NotFoundException is thrown.
  1114. */
  1115. public function castDown(array $derivedModelClassNames)
  1116. {
  1117. $bean = $this->getPrimaryBean();
  1118. $thisModelClassName = get_called_class();
  1119. $key = strtolower($thisModelClassName) . '_id';
  1120. foreach ($derivedModelClassNames as $modelClassNames)
  1121. {
  1122. if (is_string($modelClassNames))
  1123. {
  1124. $nextModelClassName = $modelClassNames;
  1125. if (get_class($this) == $nextModelClassName)
  1126. {
  1127. return $this;
  1128. }
  1129. $nextBean = self::findNextDerivativeBean($bean, $thisModelClassName, $nextModelClassName);
  1130. }
  1131. else
  1132. {
  1133. assert('is_array($modelClassNames)');
  1134. $targetModelClassName = end($modelClassNames);
  1135. if (get_class($this) == $targetModelClassName)
  1136. {
  1137. return $this;
  1138. }
  1139. $currentModelClassName = $thisModelClassName;
  1140. $nextBean = $bean;
  1141. foreach ($modelClassNames as $nextModelClassName)
  1142. {
  1143. if ($nextModelClassName::getCanHaveBean())
  1144. {
  1145. $nextBean = self::findNextDerivativeBean($nextBean, $currentModelClassName, $nextModelClassName);
  1146. if ($nextBean === null)
  1147. {
  1148. break;
  1149. }
  1150. $currentModelClassName = $nextModelClassName;
  1151. }
  1152. }
  1153. }
  1154. if ($nextBean !== null)
  1155. {
  1156. return self::makeModel($nextBean, $nextModelClassName);
  1157. }
  1158. }
  1159. throw new NotFoundException();
  1160. }
  1161. private static function findNextDerivativeBean($bean, $modelClassName1, $modelClassName2)
  1162. {
  1163. if ($bean->id > 0)
  1164. {
  1165. $key = strtolower($modelClassName1) . '_id';
  1166. $tableName = $modelClassName2::getTableName();
  1167. $beans = ZurmoRedBean::find($tableName, "$key = :id", array('id' => $bean->id));
  1168. if (count($beans) == 1)
  1169. {
  1170. return reset($beans);
  1171. }
  1172. }
  1173. return null;
  1174. }
  1175. /**
  1176. * Returns whether the given object is of the same type with the
  1177. * same id.
  1178. */
  1179. public function isSame(RedBeanModel $model)
  1180. {
  1181. // The two models are the same if they have the
  1182. // same root model, and if for that model they
  1183. // have the same id.
  1184. $rootId1 = reset($this ->modelClassNameToBean)->id;
  1185. $rootId2 = reset($model->modelClassNameToBean)->id;
  1186. if ($rootId1 == 0)
  1187. {
  1188. $rootId1 = $this->pseudoId;
  1189. }
  1190. if ($rootId2 == 0)
  1191. {
  1192. $rootId2 = $model->pseudoId;
  1193. }
  1194. return $rootId1 == $rootId2 && $rootId1 != 0 &&
  1195. key($this ->modelClassNameToBean) ==
  1196. key($model->modelClassNameToBean);
  1197. }
  1198. /**
  1199. * Returns the displayable string for the class. Should be
  1200. * overridden in any model that can provide a meaningful string
  1201. * representation of itself.
  1202. * @return A string.
  1203. */
  1204. public function __toString()
  1205. {
  1206. return Zurmo::t('Core', '(None)');
  1207. }
  1208. /**
  1209. * Exposes the members and relations of the model as if
  1210. * they were actual attributes of the model. See __set().
  1211. * @param $attributeName A non-empty string that is the name of a
  1212. * member or relation.
  1213. * @see attributeNames()
  1214. * @return A value or model of the type specified as valid for the
  1215. * member or relation by the meta data supplied by the extending
  1216. * class's getMetadata() method.
  1217. */
  1218. public function __get($attributeName)
  1219. {
  1220. return $this->unrestrictedGet($attributeName);
  1221. }
  1222. /**
  1223. * A protected version of __get() for models to talk to themselves
  1224. * to use their dynamically created members from 'members'
  1225. * and 'relations' in its metadata.
  1226. */
  1227. protected function unrestrictedGet($attributeName)
  1228. {
  1229. assert('is_string($attributeName)');
  1230. assert('$attributeName != ""');
  1231. assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
  1232. if (property_exists($this, $attributeName))
  1233. {
  1234. return $this->$attributeName;
  1235. }
  1236. elseif ($attributeName == 'id')
  1237. {
  1238. $id = intval($this->getPrimaryBean()->id);
  1239. assert('$id >= 0');
  1240. if ($id == 0)
  1241. {
  1242. $id = $this->pseudoId;
  1243. }
  1244. return $id;
  1245. }
  1246. elseif ($this->isAttribute($attributeName))
  1247. {
  1248. list($bean, $attributeModelClassName) = $this->attributeNameToBeanAndClassName[$attributeName];
  1249. if (!static::isRelation($attributeName))
  1250. {
  1251. $columnName = strtolower($attributeName);
  1252. return $bean->$columnName;
  1253. }
  1254. else
  1255. {
  1256. if (!array_key_exists($attributeName, $this->relationNameToRelatedModel))
  1257. {
  1258. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  1259. list($relationType, $relatedModelClassName, $owns, $linkType, $relationLinkName) =
  1260. $relationAndOwns[$attributeName];
  1261. $tempRelatedModelClassName = $relatedModelClassName;
  1262. self::resolveModelClassNameForClassesWithoutBeans($tempRelatedModelClassName);
  1263. $relatedTableName = $tempRelatedModelClassName::getTableName();
  1264. switch ($relationType)
  1265. {
  1266. case self::HAS_ONE_BELONGS_TO:
  1267. $linkName = strtolower(get_class($this));
  1268. $columnName = $linkName . '_id';
  1269. $relatedBeans = ZurmoRedBean::find($relatedTableName, $columnName . " = " . $bean->id);
  1270. if (count($relatedBeans) > 1)
  1271. {
  1272. throw new NotFoundException();
  1273. }
  1274. elseif (count($relatedBeans) == 0)
  1275. {
  1276. $relatedModel = new $relatedModelClassName();
  1277. }
  1278. else
  1279. {
  1280. $relatedModel = self::makeModel(end($relatedBeans), $relatedModelClassName);
  1281. }
  1282. $this->relationNameToRelatedModel[$attributeName] = $relatedModel;
  1283. break;
  1284. case self::HAS_ONE:
  1285. case self::HAS_MANY_BELONGS_TO:
  1286. $linkName = self::makeCasedLinkName($relationType, $linkType, $relationLinkName);
  1287. if ($bean->id > 0 && !in_array($attributeName, $this->unlinkedRelationNames))
  1288. {
  1289. $linkFieldName = ZurmoRedBeanLinkManager::getLinkField($relatedTableName, $linkName);
  1290. if ((int)$bean->$linkFieldName > 0)
  1291. {
  1292. $beanIdentifier = $relatedTableName .(int)$bean->$linkFieldName;
  1293. try
  1294. {
  1295. $relatedBean = RedBeansCache::getBean($beanIdentifier);
  1296. }
  1297. catch (NotFoundException $e)
  1298. {
  1299. $relatedBean = ZurmoRedBeanLinkManager::getBean($bean, $relatedTableName, $linkName);
  1300. RedBeansCache::cacheBean($relatedBean, $beanIdentifier);
  1301. }
  1302. if ($relatedBean !== null && $relatedBean->id > 0)
  1303. {
  1304. $relatedModel = self::makeModel($relatedBean, $relatedModelClassName);
  1305. }
  1306. }
  1307. }
  1308. if (!isset($relatedModel))
  1309. {
  1310. $relatedModel = new $relatedModelClassName();
  1311. }
  1312. $this->relationNameToRelatedModel[$attributeName] = $relatedModel;
  1313. break;
  1314. case self::HAS_MANY:
  1315. $this->relationNameToRelatedModel[$attributeName] =
  1316. new RedBeanOneToManyRelatedModels($this,
  1317. $bean,
  1318. $relatedModelClassName,
  1319. $attributeModelClassName,
  1320. $attributeName,
  1321. $owns,
  1322. $linkType,
  1323. $relationLinkName);
  1324. break;
  1325. case self::MANY_MANY:
  1326. $this->relationNameToRelatedModel[$attributeName] =
  1327. new RedBeanManyToManyRelatedModels($bean, $relatedModelClassName,
  1328. $linkType, $relationLinkName);
  1329. break;
  1330. default:
  1331. throw new NotSupportedException();
  1332. }
  1333. }
  1334. return $this->relationNameToRelatedModel[$attributeName];
  1335. }
  1336. }
  1337. else
  1338. {
  1339. throw new NotSupportedException('Invalid Attribute: ' . $attributeName);
  1340. }
  1341. }
  1342. /**
  1343. * Sets the members and relations of the model as if
  1344. * they were actual attributes of the model. For example, if Account
  1345. * extends RedBeanModel and its attributeNames() returns that one it has
  1346. * a member 'name' and a relation 'owner' they are simply
  1347. * accessed as:
  1348. * @code
  1349. * $account = new Account();
  1350. * $account->name = 'International Corp';
  1351. * $account->owner = User::getByUsername('bill');
  1352. * $account->save();
  1353. * @endcode
  1354. * @param $attributeName A non-empty string that is the name of a
  1355. * member or relation of the model.
  1356. * @param $value A value or model of the type specified as valid for the
  1357. * member or relation by the meta data supplied by the extending
  1358. * class's getMetadata() method.
  1359. */
  1360. public function __set($attributeName, $value)
  1361. {
  1362. if ($attributeName == 'id' ||
  1363. ($this->isAttributeReadOnly($attributeName) && !$this->isAllowedToSetReadOnlyAttribute($attributeName)))
  1364. {
  1365. $message = Zurmo::t('Core', 'It is not allowed to set read only attribute: {attributeName}.',
  1366. array('{attributeName}' => $attributeName));
  1367. throw new NotSupportedException($message);
  1368. }
  1369. else
  1370. {
  1371. if ($this->unrestrictedSet($attributeName, $value))
  1372. {
  1373. $this->modified = true;
  1374. $this->onModified();
  1375. }
  1376. }
  1377. }
  1378. /**
  1379. * A protected version of __set() for models to talk to themselves
  1380. * to use their dynamically created members from 'members'
  1381. * and 'relations' in its metadata.
  1382. */
  1383. protected function unrestrictedSet($attributeName, $value)
  1384. {
  1385. assert('is_string($attributeName)');
  1386. assert('$attributeName != ""');
  1387. assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
  1388. if (property_exists($this, $attributeName))
  1389. {
  1390. $this->$attributeName = $value;
  1391. }
  1392. elseif (static::isAnAttribute($attributeName))
  1393. {
  1394. if (!static::isRelation($attributeName))
  1395. {
  1396. $bean = $this->attributeNameToBeanAndClassName[$attributeName][0];
  1397. $columnName = strtolower($attributeName);
  1398. if ($bean->$columnName !== $value)
  1399. {
  1400. $bean->$columnName = $value;
  1401. return true;
  1402. }
  1403. }
  1404. else
  1405. {
  1406. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  1407. list($relationType, $relatedModelClassName, $owns, $linkType, $relationLinkName) =
  1408. $relationAndOwns[$attributeName];
  1409. $relatedTableName = $relatedModelClassName::getTableName();
  1410. switch ($relationType)
  1411. {
  1412. case self::HAS_MANY:
  1413. case self::MANY_MANY:
  1414. // The many sides of a relation cannot
  1415. // be assigned, they are changed by the using the
  1416. // RedBeanOneToManyRelatedModels or
  1417. // RedBeanManyToManyRelatedModels object
  1418. // on the 1 or other side of the relationship
  1419. // respectively.
  1420. throw new NotSupportedException();
  1421. }
  1422. // If the value is null we need to get the related model so that
  1423. // if there is none we can ignore the null and if there is one
  1424. // we can act on it.
  1425. if ($value === null &&
  1426. !in_array($attributeName, $this->unlinkedRelationNames) &&
  1427. !isset($this->relationNameToRelatedModel[$attributeName]))
  1428. {
  1429. $this->unrestrictedGet($attributeName);
  1430. }
  1431. elseif ($value !== null && $owns == static::OWNED &&
  1432. !in_array($attributeName, $this->unlinkedRelationNames) &&
  1433. !isset($this->relationNameToRelatedModel[$attributeName]))
  1434. {
  1435. $this->unrestrictedGet($attributeName);
  1436. }
  1437. if (isset($this->relationNameToRelatedModel[$attributeName]) &&
  1438. $value !== null &&
  1439. $this->relationNameToRelatedModel[$attributeName]->isSame($value))
  1440. {
  1441. // If there is a current related model and it is the same
  1442. // as the one being set then do nothing.
  1443. }
  1444. else
  1445. {
  1446. if (!in_array($attributeName, $this->unlinkedRelationNames) &&
  1447. isset($this->relationNameToRelatedModel[$attributeName]))
  1448. {
  1449. $this->unlinkedRelationNames[] = $attributeName;
  1450. if ($owns == static::OWNED)
  1451. {
  1452. $this->unlinkedOwnedRelatedModelsToRemove[$attributeName] =
  1453. $this->relationNameToRelatedModel[$attributeName];
  1454. }
  1455. }
  1456. if ($value === null)
  1457. {
  1458. unset($this->relationNameToRelatedModel[$attributeName]);
  1459. }
  1460. else
  1461. {
  1462. assert("\$value instanceof $relatedModelClassName");
  1463. $this->relationNameToRelatedModel[$attributeName] = $value;
  1464. }
  1465. }
  1466. return true;
  1467. }
  1468. }
  1469. else
  1470. {
  1471. throw new NotSupportedException($attributeName);
  1472. }
  1473. return false;
  1474. }
  1475. /**
  1476. * Allows testing of the members and relations of the model as if
  1477. * they were actual attributes of the model.
  1478. */
  1479. public function __isset($attributeName)
  1480. {
  1481. assert('is_string($attributeName)');
  1482. assert('$attributeName != ""');
  1483. return $this->isAttribute($attributeName) &&
  1484. $this->$attributeName !== null ||
  1485. !$this->isAttribute($attributeName) &&
  1486. isset($this->$attributeName);
  1487. }
  1488. /**
  1489. * Allows unsetting of the members and relations of the model as if
  1490. * they were actual attributes of the model.
  1491. */
  1492. public function __unset($attributeName)
  1493. {
  1494. assert('is_string($attributeName)');
  1495. assert('$attributeName != ""');
  1496. $this->$attributeName = null;
  1497. }
  1498. /**
  1499. * Returns the member and relation names defined by the extending
  1500. * class's getMetadata() method.
  1501. */
  1502. public function attributeNames()
  1503. {
  1504. return static::getAttributeNames();
  1505. }
  1506. /**
  1507. * Returns true if the named attribute is one of the member or
  1508. * relation names defined by the extending
  1509. * class's getMetadata() method.
  1510. */
  1511. public function isAttribute($attributeName)
  1512. {
  1513. return static::isAnAttribute($attributeName);
  1514. }
  1515. /**
  1516. * Check if attribute name exist, but ignore case sensitivity
  1517. * This is used by designer to make difference for example between firstValue and firstvalue, because
  1518. * regular isAttribute methoed doesn't make difference.
  1519. * In most case you would want to use isAttribute method.
  1520. * @param string $attributeName
  1521. * @return bool
  1522. */
  1523. public function isAttributeWithLowerCaseConversion($attributeName)
  1524. {
  1525. $existingAttributeNames = static::getAttributeNames();
  1526. $existingAttributeNames = array_map('strtolower', $existingAttributeNames);
  1527. if (in_array(strtolower($attributeName), $existingAttributeNames))
  1528. {
  1529. return true;
  1530. }
  1531. }
  1532. /**
  1533. * Returns true if the attribute is read-only.
  1534. */
  1535. public function isAttributeReadOnly($attributeName)
  1536. {
  1537. assert("\$this->isAttribute(\"$attributeName\")");
  1538. foreach ($this->validators as $validator)
  1539. {
  1540. if ($validator instanceof RedBeanModelReadOnlyValidator)
  1541. {
  1542. if (in_array($attributeName, $validator->attributes, true))
  1543. {
  1544. return true;
  1545. }
  1546. }
  1547. }
  1548. return false;
  1549. }
  1550. /**
  1551. * Returns true if the attribute is formattted as probability
  1552. */
  1553. public function isAttributeFormattedAsProbability($attributeName)
  1554. {
  1555. assert("\$this->isAttribute(\"$attributeName\")");
  1556. foreach ($this->validators as $validator)
  1557. {
  1558. if ($validator instanceof RedBeanModelProbabilityValidator)
  1559. {
  1560. if (in_array($attributeName, $validator->attributes, true))
  1561. {
  1562. return true;
  1563. }
  1564. }
  1565. }
  1566. return false;
  1567. }
  1568. /**
  1569. * @param boolean $attributeName
  1570. * @return true/false whether the attributeName specified, it is allowed to be set externally even though it is
  1571. * a read-only attribute.
  1572. */
  1573. public function isAllowedToSetReadOnlyAttribute($attributeName)
  1574. {
  1575. return false;
  1576. }
  1577. /**
  1578. * See the yii documentation. Not used by RedBeanModel.
  1579. * @see getMetadata()
  1580. */
  1581. public function rules()
  1582. {
  1583. throw new NotImplementedException();
  1584. }
  1585. /**
  1586. * See the yii documentation.
  1587. */
  1588. public function behaviors()
  1589. {
  1590. return array();
  1591. }
  1592. /**
  1593. * See the yii documentation.
  1594. * RedBeanModels utilize translatedAttributeLabels to store any attribute information.
  1595. */
  1596. public function attributeLabels()
  1597. {
  1598. return static::translatedAttributeLabels(Yii::app()->language);
  1599. }
  1600. /**
  1601. * Public method
  1602. */
  1603. public function abbreviatedAttributeLabels()
  1604. {
  1605. return static::translatedAbbreviatedAttributeLabels(Yii::app()->language);
  1606. }
  1607. /**
  1608. * Performs validation using the validators specified in the 'rules'
  1609. * meta data by the extending class's getMetadata() method.
  1610. * Validation occurs on a new model or a modified model, but only
  1611. * proceeds to modified related models. Once validated a model
  1612. * will pass validation without revalidating until it is modified.
  1613. * Related models are only validated if the model validates.
  1614. * Cyclic relationships are prevented from causing problems by the
  1615. * validation either stopping at a non-validating model and only
  1616. * proceeding to non-validated models.
  1617. * @see RedBeanModel
  1618. * @param $ignoreRequiredValidator - set to true in scenarios where you want to validate everything but the
  1619. * the required validator. An example is a search form.
  1620. */
  1621. public function validate(array $attributeNames = null, $ignoreRequiredValidator = false)
  1622. {
  1623. if ($this->isValidating) // Prevent cycles.
  1624. {
  1625. return true;
  1626. }
  1627. $this->isValidating = true;
  1628. try
  1629. {
  1630. $this->clearErrors();
  1631. if ($this->beforeValidate())
  1632. {
  1633. $hasErrors = false;
  1634. if ($attributeNames === null)
  1635. {
  1636. $attributeNames = static::getAttributeNamesNotBelongsToOrManyManyForModel();
  1637. }
  1638. foreach ($this->getValidators() as $validator)
  1639. {
  1640. if ($validator instanceof RedBeanModelRequiredValidator && $validator->applyTo($this->scenarioName))
  1641. {
  1642. if (!$ignoreRequiredValidator)
  1643. {
  1644. $validator->validate($this, $attributeNames);
  1645. }
  1646. }
  1647. elseif (!$validator instanceof CDefaultValueValidator && $validator->applyTo($this->scenarioName))
  1648. {
  1649. $validator->validate($this, $attributeNames);
  1650. }
  1651. }
  1652. $relatedModelsHaveErrors = false;
  1653. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
  1654. {
  1655. if ((!$this->$relationName instanceof RedBeanModel) ||
  1656. !$this->$relationName->isSame($this))
  1657. {
  1658. if (in_array($relationName, $attributeNames) &&
  1659. ($this->$relationName->isModified() ||
  1660. ($this->isAttributeRequired($relationName) && !$ignoreRequiredValidator) &&
  1661. !$this->isSame($this->$relationName))) // Prevent cycles.
  1662. {
  1663. if (!$this->$relationName->validate(null, $ignoreRequiredValidator))
  1664. {
  1665. $hasErrors = true;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. $this->afterValidate();
  1671. $hasErrors = $hasErrors || count($this->attributeNameToErrors) > 0;
  1672. // Put these asserts back if there are suspitions about validate/hasErrors/getErrors
  1673. // producing inconsistent results. But for now it is commented out because
  1674. // it makes too big an impact.
  1675. //assert('$hasErrors == (count($this->getErrors()) > 0)');
  1676. //assert('$hasErrors == $this->hasErrors()');
  1677. $this->isValidating = false;
  1678. return !$hasErrors;
  1679. }
  1680. $this->isValidating = false;
  1681. return false;
  1682. }
  1683. catch (Exception $e)
  1684. {
  1685. $this->isValidating = false;
  1686. throw $e;
  1687. }
  1688. }
  1689. /**
  1690. * See the yii documentation.
  1691. */
  1692. protected function beforeValidate()
  1693. {
  1694. $event = new CModelEvent($this);
  1695. $this->onBeforeValidate($event);
  1696. return $event->isValid;
  1697. }
  1698. /**
  1699. * See the yii documentation.
  1700. */
  1701. protected function afterValidate()
  1702. {
  1703. $this->onAfterValidate(new CEvent($this));
  1704. }
  1705. /**
  1706. * See the yii documentation.
  1707. */
  1708. public function onBeforeValidate(CModelEvent $event)
  1709. {
  1710. $this->raiseEvent('onBeforeValidate', $event);
  1711. }
  1712. /**
  1713. * See the yii documentation.
  1714. */
  1715. public function onAfterValidate($event)
  1716. {
  1717. $this->raiseEvent('onAfterValidate', $event);
  1718. }
  1719. /**
  1720. * See the yii documentation.
  1721. */
  1722. public function getValidatorList()
  1723. {
  1724. return $this->validators;
  1725. }
  1726. /**
  1727. * See the yii documentation.
  1728. */
  1729. public function getValidators($attributeName = null)
  1730. {
  1731. assert("\$attributeName === null || \$this->isAttribute('$attributeName')");
  1732. $validators = array();
  1733. $scenarioName = $this->scenarioName;
  1734. foreach ($this->validators as $validator)
  1735. {
  1736. if ($scenarioName === null || $validator->applyTo($scenarioName))
  1737. {
  1738. if ($attributeName === null || in_array($attributeName, $validator->attributes, true))
  1739. {
  1740. $validators[] = $validator;
  1741. }
  1742. }
  1743. }
  1744. return $validators;
  1745. }
  1746. /**
  1747. * Method to call to clear out validators from memory. Can help with performance. Used by async export
  1748. * for example.
  1749. */
  1750. public function forgetValidators()
  1751. {
  1752. if (!empty($this->validators))
  1753. {
  1754. $this->validators = array();
  1755. }
  1756. }
  1757. /**
  1758. * See the yii documentation.
  1759. */
  1760. public function createValidators()
  1761. {
  1762. throw new NotImplementedException();
  1763. }
  1764. /**
  1765. * Returns true if the attribute value does not already exist in
  1766. * the database. This is used in the unique validator, but on saving
  1767. * RedBean can still throw because the unique constraint on the column
  1768. * has been violated because it was concurrently updated between the
  1769. * Yii validator being called and the save actually occuring.
  1770. */
  1771. public function isUniqueAttributeValue($attributeName, $value)
  1772. {
  1773. assert("\$this->isAttribute('$attributeName')");
  1774. assert('$value !== null');
  1775. if (!static::isRelation($attributeName))
  1776. {
  1777. $modelClassName = $this->attributeNameToBeanAndClassName[$attributeName][1];
  1778. $tableName = $modelClassName::getTableName();
  1779. $rows = ZurmoRedBean::getAll('select id from ' . $tableName . " where $attributeName = ?", array($value));
  1780. return count($rows) == 0 || count($rows) == 1 && $rows[0]['id'] == $this->id;
  1781. }
  1782. else
  1783. {
  1784. $model = $this->$attributeName;
  1785. if ($model->id == 0)
  1786. {
  1787. return true;
  1788. }
  1789. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  1790. $modelClassName = $relationAndOwns[$attributeName][1];
  1791. $tableName = $modelClassName::getTableName();
  1792. $rows = ZurmoRedBean::getAll('select id from ' . $tableName . ' where id = ?', array($model->id));
  1793. return count($rows) == 0 || count($rows) == 1 && $rows[0]['id'] == $this->id;
  1794. }
  1795. }
  1796. /**
  1797. * Saves the model to the database. Models are only saved if they have been
  1798. * modified and related models are saved before this model. If a related model
  1799. * is modified and needs saving the deems the model to be modified and need
  1800. * saving, which ensures that keys are updated.
  1801. * Cyclic relationships are prevented from causing problems by the
  1802. * save only proceeding to non-saved models.
  1803. */
  1804. public function save($runValidation = true, array $attributeNames = null)
  1805. {
  1806. if ($attributeNames !== null)
  1807. {
  1808. throw new NotSupportedException();
  1809. }
  1810. if ($this->isSaving) // Prevent cycles.
  1811. {
  1812. return true;
  1813. }
  1814. $this->isSaving = true;
  1815. try
  1816. {
  1817. if (!$runValidation || $this->validate())
  1818. {
  1819. if ($this->beforeSave())
  1820. {
  1821. $beans = array_values($this->modelClassNameToBean);
  1822. $this->linkBeans();
  1823. // The breakLink/link is deferred until the save to avoid
  1824. // disconnecting or creating an empty row if the model was
  1825. // never actually saved.
  1826. foreach ($this->unlinkedRelationNames as $key => $relationName)
  1827. {
  1828. $bean = $this->attributeNameToBeanAndClassName[$relationName][0];
  1829. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  1830. $relatedModelClassName = $relationAndOwns[$relationName][1];
  1831. $tempRelatedModelClassName = $relatedModelClassName;
  1832. self::resolveModelClassNameForClassesWithoutBeans($tempRelatedModelClassName);
  1833. $relatedTableName = $tempRelatedModelClassName::getTableName();
  1834. $linkName = strtolower($relationName);
  1835. if (static::getRelationType($relationName) == self::HAS_ONE &&
  1836. static::getRelationLinkType($relationName) == self::LINK_TYPE_SPECIFIC)
  1837. {
  1838. $linkName = strtolower(static::getRelationLinkName($relationName));
  1839. }
  1840. elseif ($linkName == strtolower($relatedModelClassName))
  1841. {
  1842. $linkName = null;
  1843. }
  1844. ZurmoRedBeanLinkManager::breakLink($bean, $relatedTableName, $linkName);
  1845. //Check the $this->{$relationName} second in the if clause to avoid accidentially getting
  1846. //a relation to now save. //todo: this needs to be properly handled.
  1847. if (isset($this->unlinkedOwnedRelatedModelsToRemove[$relationName]) && $this->{$relationName} !== null)
  1848. {
  1849. //Remove hasOne owned related models that are no longer needed because they have
  1850. //been replaced with another hasOne owned model.
  1851. if ($this->unlinkedOwnedRelatedModelsToRemove[$relationName]->id > 0)
  1852. {
  1853. $this->unlinkedOwnedRelatedModelsToRemove[$relationName]->unrestrictedDelete();
  1854. }
  1855. unset($this->unlinkedOwnedRelatedModelsToRemove[$relationName]);
  1856. }
  1857. unset($this->unlinkedRelationNames[$key]);
  1858. }
  1859. assert('count($this->unlinkedRelationNames) == 0');
  1860. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
  1861. {
  1862. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  1863. $relationType = $relationAndOwns[$relationName][0];
  1864. if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO,
  1865. self::HAS_MANY_BELONGS_TO)))
  1866. {
  1867. if ($this->isRelatedModelReallyModified($relatedModel, $relationAndOwns[$relationName][0],
  1868. $relationAndOwns[$relationName][2]) || $this->isAttributeRequired($relationName))
  1869. {
  1870. //If the attribute is required, but already exists and has not been modified we do
  1871. //not have to worry about saving it.
  1872. if ($this->isSavableFromRelation &&
  1873. !($this->isAttributeRequired($relationName) &&
  1874. !$relatedModel->isModified() &&
  1875. $relatedModel->id > 0))
  1876. {
  1877. if (!$relatedModel->save(false))
  1878. {
  1879. $this->isSaving = false;
  1880. return false;
  1881. }
  1882. }
  1883. elseif ($relatedModel->isModified())
  1884. {
  1885. throw new NotSupportedException();
  1886. }
  1887. }
  1888. }
  1889. if ($relatedModel instanceof RedBeanModel)
  1890. {
  1891. $bean = $this->attributeNameToBeanAndClassName [$relationName][0];
  1892. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  1893. $relatedModelClassName = $relationAndOwns[$relationName][1];
  1894. $linkName = strtolower($relationName);
  1895. if ($relationType == self::HAS_ONE &&
  1896. static::getRelationLinkType($relationName) == self::LINK_TYPE_SPECIFIC)
  1897. {
  1898. $linkName = strtolower(static::getRelationLinkName($relationName));
  1899. }
  1900. elseif (strtolower($linkName) == strtolower($relatedModelClassName) ||
  1901. static::getRelationLinkType($relationName) == self::LINK_TYPE_ASSUMPTIVE)
  1902. {
  1903. $linkName = null;
  1904. }
  1905. elseif ($relationType == static::HAS_MANY_BELONGS_TO ||
  1906. $relationType == static::HAS_ONE_BELONGS_TO)
  1907. {
  1908. throw new NotSupportedException(Zurmo::t('Core', 'Relations of type HAS_MANY_BELONGS_TO OR HAS_ONE_BELONGS_TO must have the relation name ' .
  1909. 'the same as the related model class name. Relation: {relationName} ' .
  1910. 'Relation model class name: {relationModelClassName}',
  1911. array('{relationName}' => $linkName,
  1912. '{relationModelClassName}' => $relatedModelClassName)));
  1913. }
  1914. //Needed to exclude HAS_ONE_BELONGS_TO because an additional column was being created
  1915. //on the wrong side.
  1916. if ($relationType != static::HAS_ONE_BELONGS_TO &&
  1917. ($this->isRelatedModelReallyModified($relatedModel, $relationAndOwns[$relationName][0], $relationAndOwns[$relationName][2]) ||
  1918. $relatedModel->id > 0 ||
  1919. $this->isAttributeRequired($relationName)))
  1920. {
  1921. $relatedModel = $this->relationNameToRelatedModel[$relationName];
  1922. $relatedBean = $relatedModel->getClassBean($relatedModelClassName);
  1923. //Exclude HAS_MANY_BELONGS_TO because if the existing relation is unlinked, then
  1924. //this link should not be reactivated, because it will improperly create the bean
  1925. //in the database.
  1926. if (!($relationType == static::HAS_MANY_BELONGS_TO && $this->{$relationName}->id < 0))
  1927. {
  1928. ZurmoRedBeanLinkManager::link($bean, $relatedBean, $linkName);
  1929. }
  1930. }
  1931. }
  1932. }
  1933. $baseModelClassName = null;
  1934. foreach ($this->modelClassNameToBean as $modelClassName => $bean)
  1935. {
  1936. ZurmoRedBean::store($bean);
  1937. assert('$bean->id > 0');
  1938. }
  1939. $this->modified = false;
  1940. $this->afterSave();
  1941. $calledModelClassName = get_called_class();
  1942. if ($calledModelClassName::isCacheable())
  1943. {
  1944. RedBeanModelsCache::cacheModel($this);
  1945. }
  1946. $this->isSaving = false;
  1947. return true;
  1948. }
  1949. }
  1950. $this->isSaving = false;
  1951. return false;
  1952. }
  1953. catch (Exception $e)
  1954. {
  1955. $this->isSaving = false;
  1956. throw $e;
  1957. }
  1958. }
  1959. /**
  1960. * See Stories #82063952 and #82699138
  1961. * @see isReallyModified
  1962. * @param $relatedModel
  1963. * @param $relationType integer
  1964. * @param $isOwned boolean
  1965. * @return bool
  1966. */
  1967. public function isRelatedModelReallyModified($relatedModel, $relationType, $isOwned)
  1968. {
  1969. assert('is_int($relationType)');
  1970. assert('is_bool($isOwned)');
  1971. if ($relatedModel instanceof RedBeanModel)
  1972. {
  1973. return $relatedModel->isReallyModified($relationType, $isOwned);
  1974. }
  1975. else
  1976. {
  1977. return $relatedModel->isModified();
  1978. }
  1979. }
  1980. /**
  1981. * See Stories #82063952 and #82699138
  1982. * Overridden in OwnedSecurableItem. This means the fix is scoped down to just classes that extend
  1983. * OwnedSecurableItem, but the bug with isModified only manifests when there are default values on related
  1984. * models, which has only occurred on subClasses of OwnedSecurableItem.
  1985. *
  1986. * This fix is probably temporarily until the way isModified() and save() methods work in RedBeanModel
  1987. * is refactored. This would be a large refactoring.
  1988. * @param $relationType integer
  1989. * @param $isOwned boolean
  1990. * @return bool
  1991. */
  1992. public function isReallyModified($relationType, $isOwned)
  1993. {
  1994. assert('is_int($relationType)');
  1995. assert('is_bool($isOwned)');
  1996. return $this->isModified();
  1997. }
  1998. /**
  1999. * This method is invoked before saving a record (after validation, if any).
  2000. * The default implementation raises the {@link onBeforeSave} event.
  2001. * You may override this method to do any preparation work for record saving.
  2002. * Use {@link isNewModel} to determine whether the saving is
  2003. * for inserting or updating record.
  2004. * Make sure you call the parent implementation so that the event is raised properly.
  2005. * @return boolean whether the saving should be executed. Defaults to true.
  2006. */
  2007. protected function beforeSave()
  2008. {
  2009. if ($this->hasEventHandler('onBeforeSave'))
  2010. {
  2011. $event = new CModelEvent($this);
  2012. $this->onBeforeSave($event);
  2013. return $event->isValid;
  2014. }
  2015. else
  2016. {
  2017. return true;
  2018. }
  2019. }
  2020. protected function afterSave()
  2021. {
  2022. $event = new CEvent($this);
  2023. $this->onAfterSave($event);
  2024. }
  2025. /**
  2026. * This event is raised before the record is saved.
  2027. * By setting {@link CModelEvent::isValid} to be false, the normal {@link save()} process will be stopped.
  2028. * @param CModelEvent $event the event parameter
  2029. * @since 1.0.2
  2030. */
  2031. public function onBeforeSave($event)
  2032. {
  2033. $this->raiseEvent('onBeforeSave', $event);
  2034. }
  2035. /**
  2036. * This event is raised after the record is saved.
  2037. * @param CEvent $event the event parameter
  2038. * @since 1.0.2
  2039. */
  2040. public function onAfterSave($event)
  2041. {
  2042. $this->raiseEvent('onAfterSave', $event);
  2043. }
  2044. /**
  2045. * This event is raised on a RedBeanOneToManyRelatedModels change
  2046. * @param $event
  2047. */
  2048. public function onRedBeanOneToManyRelatedModelsChange($event)
  2049. {
  2050. $this->raiseEvent('onRedBeanOneToManyRelatedModelsChange', $event);
  2051. }
  2052. /**
  2053. * This event is raised before the record is deleted.
  2054. * By setting {@link CModelEvent::isValid} to be false, the normal {@link delete()} process will be stopped.
  2055. * @param CModelEvent $event the event parameter
  2056. * @since 1.0.2
  2057. */
  2058. public function onBeforeDelete($event)
  2059. {
  2060. $this->raiseEvent('onBeforeDelete', $event);
  2061. }
  2062. /**
  2063. * This event is raised after the record is deleted.
  2064. * @param CEvent $event the event parameter
  2065. * @since 1.0.2
  2066. */
  2067. public function onAfterDelete($event)
  2068. {
  2069. $this->raiseEvent('onAfterDelete', $event);
  2070. }
  2071. protected function linkBeans()
  2072. {
  2073. $baseBean = null;
  2074. foreach ($this->modelClassNameToBean as $modelClassName => $bean)
  2075. {
  2076. if ($baseBean !== null)
  2077. {
  2078. ZurmoRedBeanLinkManager::link($bean, $baseBean);
  2079. }
  2080. $baseBean = $bean;
  2081. }
  2082. }
  2083. /**
  2084. * Returns true if the model has been modified since it was saved
  2085. * or constructed.
  2086. */
  2087. public function isModified()
  2088. {
  2089. if ($this->modified)
  2090. {
  2091. return true;
  2092. }
  2093. if ($this->isInIsModified) // Prevent cycles.
  2094. {
  2095. return false;
  2096. }
  2097. $this->isInIsModified = true;
  2098. try
  2099. {
  2100. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
  2101. {
  2102. if ((!$this->$relationName instanceof RedBeanModel) ||
  2103. !$this->$relationName->isSame($this))
  2104. {
  2105. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  2106. if (!in_array($relationAndOwns[$relationName][0],
  2107. array(self::HAS_ONE_BELONGS_TO,
  2108. self::HAS_MANY_BELONGS_TO)))
  2109. {
  2110. if ($this->$relationName->isModified())
  2111. {
  2112. $this->isInIsModified = false;
  2113. return true;
  2114. }
  2115. }
  2116. }
  2117. }
  2118. $this->isInIsModified = false;
  2119. return false;
  2120. }
  2121. catch (Exception $e)
  2122. {
  2123. $this->isInIsModified = false;
  2124. throw $e;
  2125. }
  2126. }
  2127. /**
  2128. * Deletes the model from the database.
  2129. */
  2130. public function delete()
  2131. {
  2132. if ($this->id < 0)
  2133. {
  2134. // If the model was never saved
  2135. // then it doesn't need to be deleted.
  2136. return false;
  2137. }
  2138. $modelClassName = get_called_class();
  2139. if (!$modelClassName::isTypeDeletable() ||
  2140. !$this->isDeletable())
  2141. {
  2142. // See comments below on isDeletable.
  2143. throw new NotSupportedException();
  2144. }
  2145. if ($this->beforeDelete())
  2146. {
  2147. $this->isDeleting = true;
  2148. $deleted = $this->unrestrictedDelete();
  2149. $this->isDeleting = false;
  2150. $this->afterDelete();
  2151. return $deleted;
  2152. }
  2153. else
  2154. {
  2155. return false;
  2156. }
  2157. }
  2158. /**
  2159. * This method is invoked before deleting a record.
  2160. * The default implementation raises the {@link onBeforeDelete} event.
  2161. * You may override this method to do any preparation work for record deletion.
  2162. * Make sure you call the parent implementation so that the event is raised properly.
  2163. * @return boolean whether the record should be deleted. Defaults to true.
  2164. */
  2165. protected function beforeDelete()
  2166. {
  2167. if ($this->hasEventHandler('onBeforeDelete'))
  2168. {
  2169. $event = new CModelEvent($this);
  2170. $this->onBeforeDelete($event);
  2171. return $event->isValid;
  2172. }
  2173. else
  2174. {
  2175. return true;
  2176. }
  2177. }
  2178. /**
  2179. * This method is invoked after deleting a record.
  2180. * The default implementation raises the {@link onAfterDelete} event.
  2181. * You may override this method to do postprocessing after the record is deleted.
  2182. * Make sure you call the parent implementation so that the event is raised properly.
  2183. */
  2184. protected function afterDelete()
  2185. {
  2186. if ($this->hasEventHandler('onAfterDelete'))
  2187. {
  2188. $this->onAfterDelete(new CEvent($this));
  2189. }
  2190. }
  2191. protected function unrestrictedDelete()
  2192. {
  2193. $this->forget();
  2194. // RedBeanModel only supports cascaded deletes on associations,
  2195. // not on links. So for now at least they are done the slow way.
  2196. foreach (RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy) as $modelClassName)
  2197. {
  2198. if ($modelClassName::getCanHaveBean())
  2199. {
  2200. $this->deleteOwnedRelatedModels ($modelClassName);
  2201. $this->deleteForeignRelatedModels($modelClassName);
  2202. $this->deleteManyManyRelations ($modelClassName);
  2203. }
  2204. }
  2205. foreach ($this->modelClassNameToBean as $modelClassName => $bean)
  2206. {
  2207. ZurmoRedBean::trash($bean);
  2208. }
  2209. // The model cannot be used anymore.
  2210. $this->deleted = true;
  2211. return true;
  2212. }
  2213. public function isDeleted()
  2214. {
  2215. return $this->deleted;
  2216. }
  2217. protected function deleteOwnedRelatedModels($modelClassName)
  2218. {
  2219. foreach (static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel() as $relationName => $relationTypeModelClassNameAndOwns)
  2220. {
  2221. assert('count($relationTypeModelClassNameAndOwns) > 2 && count($relationTypeModelClassNameAndOwns) < 6');
  2222. $relationType = $relationTypeModelClassNameAndOwns[0];
  2223. $owns = $relationTypeModelClassNameAndOwns[2];
  2224. if ($owns)
  2225. {
  2226. if ((!$this->$relationName instanceof RedBeanModel) ||
  2227. !$this->$relationName->isSame($this))
  2228. {
  2229. assert('in_array($relationType, array(self::HAS_ONE, self::HAS_MANY))');
  2230. if ($relationType == self::HAS_ONE)
  2231. {
  2232. if ($this->$relationName->id > 0)
  2233. {
  2234. // we can't change these to delete() because its Owned, it can't be deleted from outside
  2235. $this->$relationName->unrestrictedDelete();
  2236. }
  2237. }
  2238. else
  2239. {
  2240. foreach ($this->$relationName as $model)
  2241. {
  2242. // we can't change this to delete() because its Owned, it can't be deleted from outside
  2243. $model->unrestrictedDelete();
  2244. }
  2245. }
  2246. }
  2247. }
  2248. }
  2249. }
  2250. protected function deleteForeignRelatedModels($modelClassName)
  2251. {
  2252. $metadata = $this->getMetadata();
  2253. if (isset($metadata[$modelClassName]['foreignRelations']))
  2254. {
  2255. foreach ($metadata[$modelClassName]['foreignRelations'] as $relatedModelClassName)
  2256. {
  2257. $relatedModels = $relatedModelClassName::
  2258. getByRelatedClassId($relatedModelClassName,
  2259. $this->getClassId($modelClassName),
  2260. $modelClassName);
  2261. foreach ($relatedModels as $relatedModel)
  2262. {
  2263. $relatedModel->unrestrictedDelete();
  2264. }
  2265. }
  2266. }
  2267. }
  2268. protected static function getByRelatedClassId($relatedModelClassName, $id, $modelClassName = null)
  2269. {
  2270. assert('is_string($relatedModelClassName)');
  2271. assert('$relatedModelClassName != ""');
  2272. assert('is_int($id)');
  2273. //assert('$id > 0');
  2274. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  2275. if ($modelClassName === null)
  2276. {
  2277. $modelClassName = get_called_class();
  2278. }
  2279. $tableName = $relatedModelClassName::getTableName();
  2280. $foreignKeyName = strtolower($modelClassName) . '_id';
  2281. $beans = ZurmoRedBean::find($tableName, "$foreignKeyName = $id");
  2282. return self::makeModels($beans, $relatedModelClassName);
  2283. }
  2284. protected function deleteManyManyRelations($modelClassName)
  2285. {
  2286. $metadata = $this->getMetadata();
  2287. if (isset($metadata[$modelClassName]['relations']))
  2288. {
  2289. foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
  2290. {
  2291. assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3, 4, 5))');
  2292. $relationType = $relationTypeModelClassNameAndOwns[0];
  2293. if ($relationType == self::MANY_MANY)
  2294. {
  2295. $this->{$relationName}->removeAll();
  2296. $this->{$relationName}->save();
  2297. }
  2298. }
  2299. }
  2300. }
  2301. /**
  2302. * To be overriden on intermediate derived classes
  2303. * to return false so that deletes are not done on
  2304. * intermediate classes because the object relational
  2305. * mapping will not clean up properly.
  2306. * For example if User is a Person, and Person is
  2307. * a RedBeanModel delete should be called only on User,
  2308. * not on Person. So User must override isDeletable
  2309. * to return false.
  2310. */
  2311. public static function isTypeDeletable()
  2312. {
  2313. return true;
  2314. }
  2315. /**
  2316. * To be overridden by derived classes to prevent
  2317. * deletion.
  2318. */
  2319. public function isDeletable()
  2320. {
  2321. return true;
  2322. }
  2323. /**
  2324. * Forgets about all of the objects so that when they are retrieved
  2325. * again they will be recreated from the database. For use in testing.
  2326. */
  2327. public static function forgetAll()
  2328. {
  2329. self::forgetAllBeanModels();
  2330. self::$attributeLabelsByLanguage = array();
  2331. RedBeanModelsCache::forgetAll();
  2332. RedBeansCache::forgetAll();
  2333. }
  2334. /**
  2335. * Forgets about the object so that if it is retrieved
  2336. * again it will be recreated from the database. For use in testing.
  2337. */
  2338. public function forget()
  2339. {
  2340. self::forgetBeanModel(get_called_class());
  2341. RedBeanModelsCache::forgetModel($this);
  2342. RedBeansCache::forgetBean(static::getTableName() . $this->id);
  2343. }
  2344. /**
  2345. * See the yii documentation.
  2346. */
  2347. public function isAttributeRequired($attributeName)
  2348. {
  2349. assert("\$this->isAttribute('$attributeName')");
  2350. foreach ($this->getValidators($attributeName) as $validator)
  2351. {
  2352. if ($validator instanceof CRequiredValidator)
  2353. {
  2354. return true;
  2355. }
  2356. }
  2357. return false;
  2358. }
  2359. /**
  2360. * See the yii documentation.
  2361. */
  2362. public function isAttributeSafe($attributeName)
  2363. {
  2364. $attributeNames = $this->getSafeAttributeNames();
  2365. return in_array($attributeName, $attributeNames);
  2366. }
  2367. public static function getModelLabelByTypeAndLanguage($type, $language = null)
  2368. {
  2369. assert('in_array($type, array("Singular", "SingularLowerCase", "Plural", "PluralLowerCase"))');
  2370. if ($type == 'Singular')
  2371. {
  2372. return static::getLabel($language);
  2373. }
  2374. if ($type == 'SingularLowerCase')
  2375. {
  2376. return TextUtil::strToLowerWithDefaultEncoding(static::getLabel($language));
  2377. }
  2378. if ($type == 'Plural')
  2379. {
  2380. return static::getPluralLabel($language);
  2381. }
  2382. if ($type == 'PluralLowerCase')
  2383. {
  2384. return TextUtil::strToLowerWithDefaultEncoding(static::getPluralLabel($language));
  2385. }
  2386. }
  2387. /**
  2388. * Returns the display name for the model class. Defaults to the module label. Override if the model
  2389. * label is not the module label. Make sure to return a translated label. Also provides fall back in
  2390. * moduleClassName is null.
  2391. * @param null | string $language
  2392. * @return dynamic label name based on module.
  2393. */
  2394. protected static function getLabel($language = null)
  2395. {
  2396. if (null != $moduleClassName = static::getModuleClassName())
  2397. {
  2398. return $moduleClassName::getModuleLabelByTypeAndLanguage('Singular', $language);
  2399. }
  2400. return get_called_class();
  2401. }
  2402. /**
  2403. * Returns the display name for plural of the model class. Defaults to the module label. Override if the model
  2404. * label is not the module label. Make sure to return a translated label
  2405. * @param null | string $language
  2406. * @return dynamic label name based on module.
  2407. */
  2408. protected static function getPluralLabel($language = null)
  2409. {
  2410. if (null != $moduleClassName = static::getModuleClassName())
  2411. {
  2412. return $moduleClassName::getModuleLabelByTypeAndLanguage('Plural', $language);
  2413. }
  2414. return static::getLabel($language) . 's';
  2415. }
  2416. /**
  2417. * See the yii documentation.
  2418. */
  2419. public function getAttributeLabel($attributeName)
  2420. {
  2421. return static::getAnAttributeLabel($attributeName);
  2422. }
  2423. /**
  2424. * Static implementation of @see getAttributeLabel
  2425. */
  2426. public static function getAnAttributeLabel($attributeName)
  2427. {
  2428. return static::getAttributeLabelByLanguage($attributeName, Yii::app()->language);
  2429. }
  2430. /**
  2431. * Given an attributeName and a language, retrieve the translated attribute label. Attempts to find a customized
  2432. * label in the metadata first, before falling back on the standard attribute label for the specified attribute.
  2433. * @return string - translated attribute label
  2434. */
  2435. protected static function getAttributeLabelByLanguage($attributeName, $language)
  2436. {
  2437. assert('is_string($attributeName)');
  2438. assert('is_string($language)');
  2439. if (isset(static::$attributeLabelsByLanguage[$language][get_called_class()][$attributeName]))
  2440. {
  2441. return static::$attributeLabelsByLanguage[$language][get_called_class()][$attributeName];
  2442. }
  2443. $labels = static::translatedAttributeLabels($language);
  2444. $customLabel = static::getTranslatedCustomAttributeLabelByLanguage($attributeName, $language);
  2445. if ($customLabel != null)
  2446. {
  2447. $label = $customLabel;
  2448. }
  2449. elseif (isset($labels[$attributeName]))
  2450. {
  2451. $label = $labels[$attributeName];
  2452. }
  2453. else
  2454. {
  2455. //This is a last resort if the translated attribute was not located. Make sure to define all
  2456. //attributes in translatedAttributeLabels($language)
  2457. $label = Zurmo::t('Core', static::generateAnAttributeLabel($attributeName), array(), null, $language);
  2458. }
  2459. static::$attributeLabelsByLanguage[$language][get_called_class()][$attributeName] = $label;
  2460. return $label;
  2461. }
  2462. /**
  2463. * Given an attributeName, attempt to find in the metadata a custom attribute label for the given language.
  2464. * @return string - translated attribute label, if not found return null.
  2465. */
  2466. protected static function getTranslatedCustomAttributeLabelByLanguage($attributeName, $languageCode)
  2467. {
  2468. assert('is_string($attributeName)');
  2469. assert('is_string($languageCode)');
  2470. $metadata = static::getMetadata();
  2471. foreach ($metadata as $notUsed => $modelClassMetadata)
  2472. {
  2473. if (isset($modelClassMetadata['labels']) &&
  2474. isset($modelClassMetadata['labels'][$attributeName]) &&
  2475. isset($modelClassMetadata['labels'][$attributeName][$languageCode]))
  2476. {
  2477. return $modelClassMetadata['labels'][$attributeName][$languageCode];
  2478. }
  2479. }
  2480. return null;
  2481. }
  2482. /**
  2483. * Given an attributeName, return an array of all attribute labels for each active language.
  2484. * @return array - attribute labels by language for the given attributeName.
  2485. */
  2486. public function getAttributeLabelsForAllActiveLanguagesByAttributeName($attributeName)
  2487. {
  2488. assert('is_string($attributeName)');
  2489. $attirbuteLabelData = array();
  2490. foreach (Yii::app()->languageHelper->getActiveLanguagesData() as $languageCode => $languageData)
  2491. {
  2492. $attirbuteLabelData[$languageCode] = $this->getAttributeLabelByLanguage($attributeName, $languageCode);
  2493. }
  2494. return $attirbuteLabelData;
  2495. }
  2496. /**
  2497. * See the yii documentation. The yii hasErrors() takes an optional
  2498. * attribute name. RedBeanModel's hasErrors() takes an optional attribute
  2499. * name or array of attribute names. See getErrors() for an explanation
  2500. * of this difference.
  2501. */
  2502. public function hasErrors($attributeNameOrNames = null)
  2503. {
  2504. assert('$attributeNameOrNames === null || ' .
  2505. 'is_string($attributeNameOrNames) || ' .
  2506. 'is_array ($attributeNameOrNames) && AssertUtil::all($attributeNameOrNames, "is_string")');
  2507. if ($this->isInHasErrors) // Prevent cycles.
  2508. {
  2509. return false;
  2510. }
  2511. $this->isInHasErrors = true;
  2512. try
  2513. {
  2514. if (is_string($attributeNameOrNames))
  2515. {
  2516. $attributeName = $attributeNameOrNames;
  2517. $relatedAttributeNames = null;
  2518. }
  2519. elseif (is_array($attributeNameOrNames))
  2520. {
  2521. $attributeName = $attributeNameOrNames[0];
  2522. if (count($attributeNameOrNames) > 1)
  2523. {
  2524. $relatedAttributeNames = array_slice($attributeNameOrNames, 1);
  2525. }
  2526. else
  2527. {
  2528. $relatedAttributeNames = null;
  2529. }
  2530. }
  2531. else
  2532. {
  2533. $attributeName = null;
  2534. $relatedAttributeNames = null;
  2535. }
  2536. assert("\$attributeName === null || is_string('$attributeName')");
  2537. assert('$relatedAttributeNames === null || is_array($relatedAttributeNames)');
  2538. assert('!($attributeName === null && $relatedAttributeNames !== null)');
  2539. if ($attributeName === null)
  2540. {
  2541. if (count($this->attributeNameToErrors) > 0)
  2542. {
  2543. $this->isInHasErrors = false;
  2544. return true;
  2545. }
  2546. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModelOrModels)
  2547. {
  2548. if ((!$this->$relationName instanceof RedBeanModel) ||
  2549. !$this->$relationName->isSame($this))
  2550. {
  2551. if (in_array($relationName, static::getAttributeNamesNotBelongsToOrManyManyForModel()))
  2552. {
  2553. if ($relatedModelOrModels->hasErrors($relatedAttributeNames))
  2554. {
  2555. $this->isInHasErrors = false;
  2556. return true;
  2557. }
  2558. }
  2559. }
  2560. }
  2561. $this->isInHasErrors = false;
  2562. return false;
  2563. }
  2564. else
  2565. {
  2566. if (!static::isRelation($attributeName))
  2567. {
  2568. $this->isInHasErrors = false;
  2569. return array_key_exists($attributeName, $this->attributeNameToErrors);
  2570. }
  2571. else
  2572. {
  2573. if (in_array($attributeName, static::getAttributeNamesNotBelongsToOrManyManyForModel()))
  2574. {
  2575. $this->isInHasErrors = false;
  2576. return isset($this->relationNameToRelatedModel[$attributeName]) &&
  2577. count($this->relationNameToRelatedModel[$attributeName]->getErrors($relatedAttributeNames)) > 0;
  2578. }
  2579. }
  2580. }
  2581. $this->isInHasErrors = false;
  2582. return false;
  2583. }
  2584. catch (Exception $e)
  2585. {
  2586. $this->isInHasErrors = false;
  2587. throw $e;
  2588. }
  2589. }
  2590. /**
  2591. * See the yii documentation. The yii getErrors() takes an optional
  2592. * attribute name. RedBeanModel's getErrors() takes an optional attribute
  2593. * name or array of attribute names.
  2594. * @param @attributeNameOrNames Either null, return all errors on the
  2595. * model and its related models, an attribute name on the model, return
  2596. * errors on that attribute, or an array of relation and attribute names,
  2597. * return errors on a related model's attribute.
  2598. */
  2599. public function getErrors($attributeNameOrNames = null)
  2600. {
  2601. assert('$attributeNameOrNames === null || ' .
  2602. 'is_string($attributeNameOrNames) || ' .
  2603. 'is_array ($attributeNameOrNames) && AssertUtil::all($attributeNameOrNames, "is_string")');
  2604. if ($this->isInGetErrors) // Prevent cycles.
  2605. {
  2606. return array();
  2607. }
  2608. $this->isInGetErrors = true;
  2609. try
  2610. {
  2611. if (is_string($attributeNameOrNames))
  2612. {
  2613. $attributeName = $attributeNameOrNames;
  2614. $relatedAttributeNames = null;
  2615. }
  2616. elseif (is_array($attributeNameOrNames))
  2617. {
  2618. $attributeName = $attributeNameOrNames[0];
  2619. if (count($attributeNameOrNames) > 1)
  2620. {
  2621. $relatedAttributeNames = array_slice($attributeNameOrNames, 1);
  2622. }
  2623. else
  2624. {
  2625. $relatedAttributeNames = null;
  2626. }
  2627. }
  2628. else
  2629. {
  2630. $attributeName = null;
  2631. $relatedAttributeNames = null;
  2632. }
  2633. assert("\$attributeName === null || is_string('$attributeName')");
  2634. assert('$relatedAttributeNames === null || is_array($relatedAttributeNames)');
  2635. assert('!($attributeName === null && $relatedAttributeNames !== null)');
  2636. if ($attributeName === null)
  2637. {
  2638. $errors = $this->attributeNameToErrors;
  2639. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModelOrModels)
  2640. {
  2641. if ((!$this->$relationName instanceof RedBeanModel) ||
  2642. !$this->$relationName->isSame($this))
  2643. {
  2644. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  2645. if (!in_array($relationAndOwns[$relationName][0],
  2646. array(self::HAS_ONE_BELONGS_TO,
  2647. self::HAS_MANY_BELONGS_TO,
  2648. self::MANY_MANY)))
  2649. {
  2650. $relatedErrors = $relatedModelOrModels->getErrors($relatedAttributeNames);
  2651. if (count($relatedErrors) > 0)
  2652. {
  2653. $errors[$relationName] = $relatedErrors;
  2654. }
  2655. }
  2656. }
  2657. }
  2658. $this->isInGetErrors = false;
  2659. return $errors;
  2660. }
  2661. else
  2662. {
  2663. if (isset($this->attributeNameToErrors[$attributeName]))
  2664. {
  2665. $this->isInGetErrors = false;
  2666. return $this->attributeNameToErrors[$attributeName];
  2667. }
  2668. elseif (isset($this->relationNameToRelatedModel[$attributeName]))
  2669. {
  2670. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  2671. if (!in_array($relationAndOwns[$attributeName][0],
  2672. array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO)))
  2673. {
  2674. $this->isInGetErrors = false;
  2675. return $this->relationNameToRelatedModel[$attributeName]->getErrors($relatedAttributeNames);
  2676. }
  2677. }
  2678. }
  2679. $this->isInGetErrors = false;
  2680. return array();
  2681. }
  2682. catch (Exception $e)
  2683. {
  2684. $this->isInGetErrors = false;
  2685. throw $e;
  2686. }
  2687. }
  2688. /**
  2689. * See the yii documentation.
  2690. */
  2691. public function getError($attributeName)
  2692. {
  2693. assert("\$this->isAttribute('$attributeName')");
  2694. return isset($this->attributeNameToErrors[$attributeName]) ? reset($this->attributeNameToErrors[$attributeName]) : null;
  2695. }
  2696. /**
  2697. * See the yii documentation.
  2698. */
  2699. public function addError($attributeName, $errorMessage)
  2700. {
  2701. assert("\$this->isAttribute('$attributeName')");
  2702. if (!isset($this->attributeNameToErrors[$attributeName]))
  2703. {
  2704. $this->attributeNameToErrors[$attributeName] = array();
  2705. }
  2706. $this->attributeNameToErrors[$attributeName][] = $errorMessage;
  2707. }
  2708. /**
  2709. * See the yii documentation.
  2710. */
  2711. public function addErrors(array $errors)
  2712. {
  2713. foreach ($errors as $attributeName => $error)
  2714. {
  2715. assert("\$this->isAttribute('$attributeName')");
  2716. assert('is_array($error) || is_string($error)');
  2717. if (is_array($error))
  2718. {
  2719. if (!isset($this->attributeNameToErrors[$attributeName]))
  2720. {
  2721. $this->attributeNameToErrors[$attributeName] = array();
  2722. }
  2723. $this->attributeNameToErrors[$attributeName] =
  2724. array_merge($this->attributeNameToErrors[$attributeName], $error);
  2725. }
  2726. else
  2727. {
  2728. $this->attributeNameToErrors[$attributeName][] = $error;
  2729. }
  2730. }
  2731. }
  2732. /**
  2733. * See the yii documentation.
  2734. */
  2735. public function clearErrors($attributeName = null)
  2736. {
  2737. assert("\$attributeName === null || \$this->isAttribute('$attributeName')");
  2738. if ($attributeName === null)
  2739. {
  2740. $this->attributeNameToErrors = array();
  2741. }
  2742. else
  2743. {
  2744. unset($this->attributeNameToErrors[$attributeName]);
  2745. }
  2746. }
  2747. /**
  2748. * See the yii documentation.
  2749. */
  2750. public function generateAttributeLabel($attributeName)
  2751. {
  2752. $modelClassName = get_called_class();
  2753. return $modelClassName::generateAnAttributeLabel($attributeName);
  2754. }
  2755. /**
  2756. * See the yii documentation.
  2757. */
  2758. public function getAttributes(array $attributeNames = null)
  2759. {
  2760. $values = array();
  2761. if (is_array($attributeNames))
  2762. {
  2763. $values2 = array();
  2764. $allModelAttributeNames = $this->attributeNames();
  2765. foreach ($attributeNames as $attributeName)
  2766. {
  2767. if (in_array($attributeName, $allModelAttributeNames))
  2768. {
  2769. $values2[$attributeName] = $this->$attributeName;
  2770. }
  2771. }
  2772. return $values2;
  2773. }
  2774. else
  2775. {
  2776. foreach ($this->attributeNames() as $attributeName)
  2777. {
  2778. $values[$attributeName] = $this->$attributeName;
  2779. }
  2780. return $values;
  2781. }
  2782. }
  2783. /**
  2784. * See the yii documentation.
  2785. */
  2786. public function setAttributes(array $values, $safeOnly = true)
  2787. {
  2788. assert('is_bool($safeOnly)');
  2789. $attributeNames = array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  2790. foreach ($values as $attributeName => $value)
  2791. {
  2792. if ($value !== null)
  2793. {
  2794. if (!is_array($value))
  2795. {
  2796. assert('$attributeName != "id"');
  2797. if ($attributeName != 'id' && $this->isAttribute($attributeName))
  2798. {
  2799. if ($this->isAttributeSafe($attributeName) || !$safeOnly)
  2800. {
  2801. $this->$attributeName = $value;
  2802. }
  2803. else
  2804. {
  2805. $this->onUnsafeAttribute($attributeName, $value);
  2806. }
  2807. }
  2808. }
  2809. else
  2810. {
  2811. if (static::isRelation($attributeName))
  2812. {
  2813. if (count($value) == 1 && array_key_exists('id', $value))
  2814. {
  2815. if (empty($value['id']))
  2816. {
  2817. $this->$attributeName = null;
  2818. }
  2819. else
  2820. {
  2821. $relationAndOwns = static::getRelationNameToRelationTypeModelClassNameAndOwnsForModel();
  2822. $relatedModelClassName = $relationAndOwns[$attributeName][1];
  2823. $this->$attributeName = $relatedModelClassName::getById(intval($value['id']), $relatedModelClassName);
  2824. }
  2825. }
  2826. else
  2827. {
  2828. $setAttributeMethodName = 'set' . ucfirst($attributeName);
  2829. if ($this->$attributeName instanceof RedBeanOneToManyRelatedModels &&
  2830. method_exists($this, $setAttributeMethodName))
  2831. {
  2832. $this->$setAttributeMethodName($value);
  2833. }
  2834. else
  2835. {
  2836. $this->$attributeName->setAttributes($value);
  2837. }
  2838. }
  2839. }
  2840. }
  2841. }
  2842. }
  2843. }
  2844. /**
  2845. * See the yii documentation.
  2846. */
  2847. public function unsetAttributes($attributeNames = null)
  2848. {
  2849. if ($attributeNames === null)
  2850. {
  2851. $attributeNames = $this->attributeNames();
  2852. }
  2853. foreach ($attributeNames as $attributeName)
  2854. {
  2855. $this->$attributeNames = null;
  2856. }
  2857. }
  2858. /**
  2859. * See the yii documentation.
  2860. */
  2861. public function onUnsafeAttribute($name, $value)
  2862. {
  2863. if (YII_DEBUG)
  2864. {
  2865. Yii::log(Zurmo::t('Core', 'Failed to set unsafe attribute "{attribute}".', array('{attribute}' => $name)),
  2866. CLogger::LEVEL_WARNING);
  2867. }
  2868. }
  2869. /**
  2870. * See the yii documentation.
  2871. */
  2872. public function getScenario()
  2873. {
  2874. return $this->scenarioName;
  2875. }
  2876. /**
  2877. * See the yii documentation.
  2878. */
  2879. public function setScenario($scenarioName)
  2880. {
  2881. assert('is_string($scenarioName)');
  2882. $this->scenarioName = $scenarioName;
  2883. }
  2884. /**
  2885. * See the yii documentation.
  2886. */
  2887. public function getSafeAttributeNames()
  2888. {
  2889. $attributeNamesToIsSafe = array();
  2890. $unsafeAttributeNames = array();
  2891. foreach ($this->getValidators() as $validator)
  2892. {
  2893. if (!$validator->safe)
  2894. {
  2895. foreach ($validator->attributes as $attributeName)
  2896. {
  2897. $unsafeAttributeNames[] = $attributeName;
  2898. }
  2899. }
  2900. else
  2901. {
  2902. foreach ($validator->attributes as $attributeName)
  2903. {
  2904. $attributeNamesToIsSafe[$attributeName] = true;
  2905. }
  2906. }
  2907. }
  2908. foreach ($unsafeAttributeNames as $attributeName)
  2909. {
  2910. unset($attributeNamesToIsSafe[$attributeName]);
  2911. }
  2912. return array_keys($attributeNamesToIsSafe);
  2913. }
  2914. /**
  2915. * See the yii documentation.
  2916. */
  2917. public function getIterator()
  2918. {
  2919. throw new NotImplementedException();
  2920. }
  2921. /**
  2922. * See the yii documentation.
  2923. */
  2924. public function offsetExists($offset)
  2925. {
  2926. throw new NotImplementedException();
  2927. }
  2928. /**
  2929. * See the yii documentation.
  2930. */
  2931. public function offsetGet($offset)
  2932. {
  2933. throw new NotImplementedException();
  2934. }
  2935. /**
  2936. * See the yii documentation.
  2937. */
  2938. public function offsetSet($offset, $item)
  2939. {
  2940. throw new NotImplementedException();
  2941. }
  2942. /**
  2943. * See the yii documentation.
  2944. */
  2945. public function offsetUnset($offset)
  2946. {
  2947. throw new NotImplementedException();
  2948. }
  2949. /**
  2950. * Creates an instance of the extending model wrapping the given
  2951. * bean. For use only by models. Beans are never used by the
  2952. * application directly.
  2953. * @param $bean A <a href="http://www.redbeanphp.com/">RedBean</a>
  2954. * bean.
  2955. * @param $modelClassName Pass only when getting it at runtime
  2956. * gets the wrong name.
  2957. * @return An instance of the type of the extending model.
  2958. */
  2959. public static function makeModel(RedBean_OODBBean $bean, $modelClassName = null)
  2960. {
  2961. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  2962. if ($modelClassName === null)
  2963. {
  2964. $modelClassName = get_called_class();
  2965. }
  2966. $modelIdentifier = static::getModelIdentifierByClassNameAndBeanId($modelClassName, strval($bean->id));
  2967. try
  2968. {
  2969. $model = RedBeanModelsCache::getModel($modelIdentifier);
  2970. $model->constructIncomplete($bean, false);
  2971. return $model;
  2972. }
  2973. catch (NotFoundException $e)
  2974. {
  2975. return new $modelClassName(false, $bean);
  2976. //return new $modelClassName(true, $bean, $forceTreatAsCreation); //no need to set defaults here and force creation since it is always false and the bean already exists
  2977. }
  2978. }
  2979. /**
  2980. * Creates an array of instances of the named model type wrapping the
  2981. * given beans. For use only by models. Beans are never used by the
  2982. * application directly.
  2983. * @param $beans An array of <a href="http://www.redbeanphp.com/">RedBean</a>
  2984. * beans.
  2985. * @param $modelClassName Pass only when getting it at runtime
  2986. * gets the wrong name.
  2987. * @return An array of instances of the type of the extending model.
  2988. */
  2989. public static function makeModels(array $beans, $modelClassName = null)
  2990. {
  2991. if ($modelClassName === null)
  2992. {
  2993. $modelClassName = get_called_class();
  2994. }
  2995. $models = array();
  2996. foreach ($beans as $bean)
  2997. {
  2998. assert('$bean instanceof RedBean_OODBBean');
  2999. try
  3000. {
  3001. $models[] = self::makeModel($bean, $modelClassName);
  3002. }
  3003. catch (MissingBeanException $e)
  3004. {
  3005. }
  3006. }
  3007. return $models;
  3008. }
  3009. public static function getModuleClassName()
  3010. {
  3011. return null;
  3012. }
  3013. /**
  3014. * Given an array of data, create stringified content.
  3015. * @param array $values
  3016. */
  3017. public function stringifyOneToManyRelatedModelsValues($values)
  3018. {
  3019. assert('is_array($values)');
  3020. return ArrayUtil::stringify($values);
  3021. }
  3022. /**
  3023. * Resolve and get model class name used for table retrieval factoring in when a class does
  3024. * not have a bean and must use a parent class
  3025. * @param string $modelClassName
  3026. */
  3027. protected static function resolveModelClassNameForClassesWithoutBeans(& $modelClassName)
  3028. {
  3029. assert('is_string($modelClassName)');
  3030. if (!$modelClassName::getCanHaveBean())
  3031. {
  3032. $modelClassName = get_parent_class($modelClassName);
  3033. if (!$modelClassName::getCanHaveBean())
  3034. {
  3035. //For the moment, only support a single class in a chain of classes not having a bean.
  3036. //Expand this support as needed.
  3037. throw new NotSupportedException();
  3038. }
  3039. }
  3040. return $modelClassName;
  3041. }
  3042. public static function getLastClassInBeanHeirarchy()
  3043. {
  3044. return static::$lastClassInBeanHeirarchy;
  3045. }
  3046. /**
  3047. * Returns a list of attributes to be added when sorting by the attribute
  3048. * @param string $attribute
  3049. * @return array
  3050. */
  3051. public static function getSortAttributesByAttribute($attribute)
  3052. {
  3053. return array($attribute);
  3054. }
  3055. /**
  3056. * Utilized by copy mechanism, helps elements, views, understand the model better before the new model is saved.
  3057. */
  3058. public function setIsCopied()
  3059. {
  3060. $this->isCopied = true;
  3061. }
  3062. /**
  3063. * @return bool
  3064. */
  3065. public function isCopied()
  3066. {
  3067. return $this->isCopied;
  3068. }
  3069. /**
  3070. * @return bool
  3071. */
  3072. public static function isCacheable()
  3073. {
  3074. return true;
  3075. }
  3076. public static function getYiiValidatorsToRedBeanValidators()
  3077. {
  3078. return static::$yiiValidatorsToRedBeanValidators;
  3079. }
  3080. /**
  3081. * Wrapper for CValidator::createValidator
  3082. * @param $attribute
  3083. * @param $validator
  3084. * @param array $params
  3085. */
  3086. public function addValidator($attribute, $validator, $params = array())
  3087. {
  3088. if ($attribute != null && $validator != null)
  3089. {
  3090. $this->validators[] = CValidator::createValidator($validator, $this, $attribute, $params);
  3091. }
  3092. }
  3093. public static function getHasManyOpposingRelationName(RedBeanModel $model, $precedingModelClassName, $precedingRelation)
  3094. {
  3095. assert('is_string($precedingModelClassName)');
  3096. assert('is_string($precedingRelation)');
  3097. foreach ($model->attributeNames() as $attributeName)
  3098. {
  3099. if ($model->isRelation($attributeName) &&
  3100. ($model->getRelationType($attributeName) == RedBeanModel::HAS_ONE ||
  3101. $model->getRelationType($attributeName) == RedBeanModel::HAS_MANY_BELONGS_TO) &&
  3102. static::relationLinksToPrecedingRelation(get_class($model), $attributeName,
  3103. $precedingModelClassName, $precedingRelation))
  3104. {
  3105. return $attributeName;
  3106. }
  3107. }
  3108. }
  3109. /**
  3110. * @param string $modelClassName
  3111. * @param string $relation
  3112. * @param null|string $precedingModelClassName
  3113. * @param null|string $precedingRelation
  3114. * @return bool
  3115. */
  3116. public static function relationLinksToPrecedingRelation($modelClassName, $relation,
  3117. $precedingModelClassName = null,
  3118. $precedingRelation = null)
  3119. {
  3120. assert('is_string($modelClassName)');
  3121. assert('is_string($relation)');
  3122. assert('is_string($precedingModelClassName) || $precedingModelClassName == null');
  3123. assert('is_string($precedingRelation) || $precedingRelation == null');
  3124. if ($precedingModelClassName == null || $precedingRelation == null)
  3125. {
  3126. return false;
  3127. }
  3128. //Check if the relation is a derived relation in which case return false because it is handled by
  3129. //@see self::inferredRelationLinksToPrecedingRelation
  3130. if (!$precedingModelClassName::isAnAttribute($precedingRelation))
  3131. {
  3132. return false;
  3133. }
  3134. if ($precedingModelClassName != $modelClassName::getRelationModelClassName($relation))
  3135. {
  3136. return false;
  3137. }
  3138. if ( $precedingModelClassName::getRelationLinkType($precedingRelation) == RedBeanModel::LINK_TYPE_ASSUMPTIVE &&
  3139. $modelClassName::getRelationLinkType($relation) == RedBeanModel::LINK_TYPE_ASSUMPTIVE)
  3140. {
  3141. return true;
  3142. }
  3143. //Check for LINK_TYPE_SPECIFIC
  3144. if ( $precedingModelClassName::getRelationLinkType($precedingRelation) == RedBeanModel::LINK_TYPE_SPECIFIC &&
  3145. $modelClassName::getRelationLinkType($relation) == RedBeanModel::LINK_TYPE_SPECIFIC &&
  3146. $precedingModelClassName::getRelationLinkName($precedingRelation) == $modelClassName::getRelationLinkName($relation))
  3147. {
  3148. return true;
  3149. }
  3150. return false;
  3151. }
  3152. /**
  3153. * Whether or not this model instances should be cached in memcache
  3154. * @return bool
  3155. */
  3156. public static function allowMemcacheCache()
  3157. {
  3158. return true;
  3159. }
  3160. }
  3161. ?>