PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/Behavior/TranslateBehavior.php

https://bitbucket.org/floresj/notetime
PHP | 631 lines | 405 code | 52 blank | 174 comment | 90 complexity | 047f6ab5e3e8d549115879042113c83a MD5 | raw file
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @package Cake.Model.Behavior
  12. * @since CakePHP(tm) v 1.2.0.4525
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. App::uses('I18n', 'I18n');
  16. App::uses('I18nModel', 'Model');
  17. /**
  18. * Translate behavior
  19. *
  20. * @package Cake.Model.Behavior
  21. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html
  22. */
  23. class TranslateBehavior extends ModelBehavior {
  24. /**
  25. * Used for runtime configuration of model
  26. *
  27. * @var array
  28. */
  29. public $runtime = array();
  30. /**
  31. * Stores the joinTable object for generating joins.
  32. *
  33. * @var object
  34. */
  35. protected $_joinTable;
  36. /**
  37. * Stores the runtime model for generating joins.
  38. *
  39. * @var Model
  40. */
  41. protected $_runtimeModel;
  42. /**
  43. * Callback
  44. *
  45. * $config for TranslateBehavior should be
  46. * array('fields' => array('field_one',
  47. * 'field_two' => 'FieldAssoc', 'field_three'))
  48. *
  49. * With above example only one permanent hasMany will be joined (for field_two
  50. * as FieldAssoc)
  51. *
  52. * $config could be empty - and translations configured dynamically by
  53. * bindTranslation() method
  54. *
  55. * @param Model $Model Model the behavior is being attached to.
  56. * @param array $config Array of configuration information.
  57. * @return mixed
  58. */
  59. public function setup(Model $Model, $config = array()) {
  60. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  61. if (!$db->connected) {
  62. trigger_error(
  63. __d('cake_dev', 'Datasource %s for TranslateBehavior of model %s is not connected', $Model->useDbConfig, $Model->alias),
  64. E_USER_ERROR
  65. );
  66. return false;
  67. }
  68. $this->settings[$Model->alias] = array();
  69. $this->runtime[$Model->alias] = array('fields' => array());
  70. $this->translateModel($Model);
  71. return $this->bindTranslation($Model, $config, false);
  72. }
  73. /**
  74. * Cleanup Callback unbinds bound translations and deletes setting information.
  75. *
  76. * @param Model $Model Model being detached.
  77. * @return void
  78. */
  79. public function cleanup(Model $Model) {
  80. $this->unbindTranslation($Model);
  81. unset($this->settings[$Model->alias]);
  82. unset($this->runtime[$Model->alias]);
  83. }
  84. /**
  85. * beforeFind Callback
  86. *
  87. * @param Model $Model Model find is being run on.
  88. * @param array $query Array of Query parameters.
  89. * @return array Modified query
  90. */
  91. public function beforeFind(Model $Model, $query) {
  92. $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
  93. $locale = $this->_getLocale($Model);
  94. if (empty($locale)) {
  95. return $query;
  96. }
  97. $db = $Model->getDataSource();
  98. $RuntimeModel = $this->translateModel($Model);
  99. if (!empty($RuntimeModel->tablePrefix)) {
  100. $tablePrefix = $RuntimeModel->tablePrefix;
  101. } else {
  102. $tablePrefix = $db->config['prefix'];
  103. }
  104. $joinTable = new StdClass();
  105. $joinTable->tablePrefix = $tablePrefix;
  106. $joinTable->table = $RuntimeModel->table;
  107. $joinTable->schemaName = $RuntimeModel->getDataSource()->getSchemaName();
  108. $this->_joinTable = $joinTable;
  109. $this->_runtimeModel = $RuntimeModel;
  110. if (is_string($query['fields']) && "COUNT(*) AS {$db->name('count')}" == $query['fields']) {
  111. $query['fields'] = "COUNT(DISTINCT({$db->name($Model->escapeField())})) {$db->alias}count";
  112. $query['joins'][] = array(
  113. 'type' => 'INNER',
  114. 'alias' => $RuntimeModel->alias,
  115. 'table' => $joinTable,
  116. 'conditions' => array(
  117. $Model->escapeField() => $db->identifier($RuntimeModel->escapeField('foreign_key')),
  118. $RuntimeModel->escapeField('model') => $Model->name,
  119. $RuntimeModel->escapeField('locale') => $locale
  120. )
  121. );
  122. $conditionFields = $this->_checkConditions($Model, $query);
  123. foreach ($conditionFields as $field) {
  124. $query = $this->_addJoin($Model, $query, $field, $field, $locale);
  125. }
  126. unset($this->_joinTable, $this->_runtimeModel);
  127. return $query;
  128. }
  129. $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
  130. $addFields = array();
  131. if (empty($query['fields'])) {
  132. $addFields = $fields;
  133. } elseif (is_array($query['fields'])) {
  134. foreach ($fields as $key => $value) {
  135. $field = (is_numeric($key)) ? $value : $key;
  136. if (in_array($Model->escapeField('*'), $query['fields']) || in_array($Model->alias . '.' . $field, $query['fields']) || in_array($field, $query['fields'])) {
  137. $addFields[] = $field;
  138. }
  139. }
  140. }
  141. $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
  142. if ($addFields) {
  143. foreach ($addFields as $_f => $field) {
  144. $aliasField = is_numeric($_f) ? $field : $_f;
  145. foreach (array($aliasField, $Model->alias . '.' . $aliasField) as $_field) {
  146. $key = array_search($_field, (array)$query['fields']);
  147. if ($key !== false) {
  148. unset($query['fields'][$key]);
  149. }
  150. }
  151. $query = $this->_addJoin($Model, $query, $field, $aliasField, $locale);
  152. }
  153. }
  154. $this->runtime[$Model->alias]['beforeFind'] = $addFields;
  155. unset($this->_joinTable, $this->_runtimeModel);
  156. return $query;
  157. }
  158. /**
  159. * Check a query's conditions for translated fields.
  160. * Return an array of translated fields found in the conditions.
  161. *
  162. * @param Model $Model The model being read.
  163. * @param array $query The query array.
  164. * @return array The list of translated fields that are in the conditions.
  165. */
  166. protected function _checkConditions(Model $Model, $query) {
  167. $conditionFields = array();
  168. if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions'])) ) {
  169. return $conditionFields;
  170. }
  171. foreach ($query['conditions'] as $col => $val) {
  172. foreach ($this->settings[$Model->alias] as $field => $assoc) {
  173. if (is_numeric($field)) {
  174. $field = $assoc;
  175. }
  176. if (strpos($col, $field) !== false) {
  177. $conditionFields[] = $field;
  178. }
  179. }
  180. }
  181. return $conditionFields;
  182. }
  183. /**
  184. * Appends a join for translated fields.
  185. *
  186. * @param Model $Model The model being worked on.
  187. * @param object $joinTable The jointable object.
  188. * @param array $query The query array to append a join to.
  189. * @param string $field The field name being joined.
  190. * @param string $aliasField The aliased field name being joined.
  191. * @param string|array $locale The locale(s) having joins added.
  192. * @return array The modfied query
  193. */
  194. protected function _addJoin(Model $Model, $query, $field, $aliasField, $locale) {
  195. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  196. $RuntimeModel = $this->_runtimeModel;
  197. $joinTable = $this->_joinTable;
  198. $aliasVirtual = "i18n_{$field}";
  199. $alias = "I18n__{$field}";
  200. if (is_array($locale)) {
  201. foreach ($locale as $_locale) {
  202. $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
  203. $aliasLocale = "{$alias}__{$_locale}";
  204. $Model->virtualFields[$aliasVirtualLocale] = "{$aliasLocale}.content";
  205. if (!empty($query['fields']) && is_array($query['fields'])) {
  206. $query['fields'][] = $aliasVirtualLocale;
  207. }
  208. $query['joins'][] = array(
  209. 'type' => 'LEFT',
  210. 'alias' => $aliasLocale,
  211. 'table' => $joinTable,
  212. 'conditions' => array(
  213. $Model->escapeField() => $db->identifier("{$aliasLocale}.foreign_key"),
  214. "{$aliasLocale}.model" => $Model->name,
  215. "{$aliasLocale}.{$RuntimeModel->displayField}" => $aliasField,
  216. "{$aliasLocale}.locale" => $_locale
  217. )
  218. );
  219. }
  220. } else {
  221. $Model->virtualFields[$aliasVirtual] = "{$alias}.content";
  222. if (!empty($query['fields']) && is_array($query['fields'])) {
  223. $query['fields'][] = $aliasVirtual;
  224. }
  225. $query['joins'][] = array(
  226. 'type' => 'INNER',
  227. 'alias' => $alias,
  228. 'table' => $joinTable,
  229. 'conditions' => array(
  230. "{$Model->alias}.{$Model->primaryKey}" => $db->identifier("{$alias}.foreign_key"),
  231. "{$alias}.model" => $Model->name,
  232. "{$alias}.{$RuntimeModel->displayField}" => $aliasField,
  233. "{$alias}.locale" => $locale
  234. )
  235. );
  236. }
  237. return $query;
  238. }
  239. /**
  240. * afterFind Callback
  241. *
  242. * @param Model $Model Model find was run on
  243. * @param array $results Array of model results.
  244. * @param boolean $primary Did the find originate on $model.
  245. * @return array Modified results
  246. */
  247. public function afterFind(Model $Model, $results, $primary) {
  248. $Model->virtualFields = $this->runtime[$Model->alias]['virtualFields'];
  249. $this->runtime[$Model->alias]['virtualFields'] = $this->runtime[$Model->alias]['fields'] = array();
  250. $locale = $this->_getLocale($Model);
  251. if (empty($locale) || empty($results) || empty($this->runtime[$Model->alias]['beforeFind'])) {
  252. return $results;
  253. }
  254. $beforeFind = $this->runtime[$Model->alias]['beforeFind'];
  255. foreach ($results as $key => &$row) {
  256. $results[$key][$Model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale;
  257. foreach ($beforeFind as $_f => $field) {
  258. $aliasField = is_numeric($_f) ? $field : $_f;
  259. $aliasVirtual = "i18n_{$field}";
  260. if (is_array($locale)) {
  261. foreach ($locale as $_locale) {
  262. $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
  263. if (!isset($row[$Model->alias][$aliasField]) && !empty($row[$Model->alias][$aliasVirtualLocale])) {
  264. $row[$Model->alias][$aliasField] = $row[$Model->alias][$aliasVirtualLocale];
  265. $row[$Model->alias]['locale'] = $_locale;
  266. }
  267. unset($row[$Model->alias][$aliasVirtualLocale]);
  268. }
  269. if (!isset($row[$Model->alias][$aliasField])) {
  270. $row[$Model->alias][$aliasField] = '';
  271. }
  272. } else {
  273. $value = '';
  274. if (!empty($row[$Model->alias][$aliasVirtual])) {
  275. $value = $row[$Model->alias][$aliasVirtual];
  276. }
  277. $row[$Model->alias][$aliasField] = $value;
  278. unset($row[$Model->alias][$aliasVirtual]);
  279. }
  280. }
  281. }
  282. return $results;
  283. }
  284. /**
  285. * beforeValidate Callback
  286. *
  287. * @param Model $Model Model invalidFields was called on.
  288. * @return boolean
  289. */
  290. public function beforeValidate(Model $Model) {
  291. unset($this->runtime[$Model->alias]['beforeSave']);
  292. $this->_setRuntimeData($Model);
  293. return true;
  294. }
  295. /**
  296. * beforeSave callback.
  297. *
  298. * Copies data into the runtime property when `$options['validate']` is
  299. * disabled. Or the runtime data hasn't been set yet.
  300. *
  301. * @param Model $Model Model save was called on.
  302. * @return boolean true.
  303. */
  304. public function beforeSave(Model $Model, $options = array()) {
  305. if (isset($options['validate']) && $options['validate'] == false) {
  306. unset($this->runtime[$Model->alias]['beforeSave']);
  307. }
  308. if (isset($this->runtime[$Model->alias]['beforeSave'])) {
  309. return true;
  310. }
  311. $this->_setRuntimeData($Model);
  312. return true;
  313. }
  314. /**
  315. * Sets the runtime data.
  316. *
  317. * Used from beforeValidate() and beforeSave() for compatibility issues,
  318. * and to allow translations to be persisted even when validation
  319. * is disabled.
  320. *
  321. * @param Model $Model
  322. * @return void
  323. */
  324. protected function _setRuntimeData(Model $Model) {
  325. $locale = $this->_getLocale($Model);
  326. if (empty($locale)) {
  327. return true;
  328. }
  329. $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
  330. $tempData = array();
  331. foreach ($fields as $key => $value) {
  332. $field = (is_numeric($key)) ? $value : $key;
  333. if (isset($Model->data[$Model->alias][$field])) {
  334. $tempData[$field] = $Model->data[$Model->alias][$field];
  335. if (is_array($Model->data[$Model->alias][$field])) {
  336. if (is_string($locale) && !empty($Model->data[$Model->alias][$field][$locale])) {
  337. $Model->data[$Model->alias][$field] = $Model->data[$Model->alias][$field][$locale];
  338. } else {
  339. $values = array_values($Model->data[$Model->alias][$field]);
  340. $Model->data[$Model->alias][$field] = $values[0];
  341. }
  342. }
  343. }
  344. }
  345. $this->runtime[$Model->alias]['beforeSave'] = $tempData;
  346. }
  347. /**
  348. * afterSave Callback
  349. *
  350. * @param Model $Model Model the callback is called on
  351. * @param boolean $created Whether or not the save created a record.
  352. * @return void
  353. */
  354. public function afterSave(Model $Model, $created) {
  355. if (!isset($this->runtime[$Model->alias]['beforeValidate']) && !isset($this->runtime[$Model->alias]['beforeSave'])) {
  356. return true;
  357. }
  358. $locale = $this->_getLocale($Model);
  359. if (isset($this->runtime[$Model->alias]['beforeValidate'])) {
  360. $tempData = $this->runtime[$Model->alias]['beforeValidate'];
  361. } else {
  362. $tempData = $this->runtime[$Model->alias]['beforeSave'];
  363. }
  364. unset($this->runtime[$Model->alias]['beforeValidate'], $this->runtime[$Model->alias]['beforeSave']);
  365. $conditions = array('model' => $Model->alias, 'foreign_key' => $Model->id);
  366. $RuntimeModel = $this->translateModel($Model);
  367. $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
  368. if ($created) {
  369. // set each field value to an empty string
  370. foreach ($fields as $key => $field) {
  371. if (!is_numeric($key)) {
  372. $field = $key;
  373. }
  374. if (!isset($tempData[$field])) {
  375. $tempData[$field] = '';
  376. }
  377. }
  378. }
  379. foreach ($tempData as $field => $value) {
  380. unset($conditions['content']);
  381. $conditions['field'] = $field;
  382. if (is_array($value)) {
  383. $conditions['locale'] = array_keys($value);
  384. } else {
  385. $conditions['locale'] = $locale;
  386. if (is_array($locale)) {
  387. $value = array($locale[0] => $value);
  388. } else {
  389. $value = array($locale => $value);
  390. }
  391. }
  392. $translations = $RuntimeModel->find('list', array('conditions' => $conditions, 'fields' => array($RuntimeModel->alias . '.locale', $RuntimeModel->alias . '.id')));
  393. foreach ($value as $_locale => $_value) {
  394. $RuntimeModel->create();
  395. $conditions['locale'] = $_locale;
  396. $conditions['content'] = $_value;
  397. if (array_key_exists($_locale, $translations)) {
  398. $RuntimeModel->save(array($RuntimeModel->alias => array_merge($conditions, array('id' => $translations[$_locale]))));
  399. } else {
  400. $RuntimeModel->save(array($RuntimeModel->alias => $conditions));
  401. }
  402. }
  403. }
  404. }
  405. /**
  406. * afterDelete Callback
  407. *
  408. * @param Model $Model Model the callback was run on.
  409. * @return void
  410. */
  411. public function afterDelete(Model $Model) {
  412. $RuntimeModel = $this->translateModel($Model);
  413. $conditions = array('model' => $Model->alias, 'foreign_key' => $Model->id);
  414. $RuntimeModel->deleteAll($conditions);
  415. }
  416. /**
  417. * Get selected locale for model
  418. *
  419. * @param Model $Model Model the locale needs to be set/get on.
  420. * @return mixed string or false
  421. */
  422. protected function _getLocale(Model $Model) {
  423. if (!isset($Model->locale) || is_null($Model->locale)) {
  424. $I18n = I18n::getInstance();
  425. $I18n->l10n->get(Configure::read('Config.language'));
  426. $Model->locale = $I18n->l10n->locale;
  427. }
  428. return $Model->locale;
  429. }
  430. /**
  431. * Get instance of model for translations.
  432. *
  433. * If the model has a translateModel property set, this will be used as the class
  434. * name to find/use. If no translateModel property is found 'I18nModel' will be used.
  435. *
  436. * @param Model $Model Model to get a translatemodel for.
  437. * @return Model
  438. */
  439. public function translateModel(Model $Model) {
  440. if (!isset($this->runtime[$Model->alias]['model'])) {
  441. if (!isset($Model->translateModel) || empty($Model->translateModel)) {
  442. $className = 'I18nModel';
  443. } else {
  444. $className = $Model->translateModel;
  445. }
  446. $this->runtime[$Model->alias]['model'] = ClassRegistry::init($className, 'Model');
  447. }
  448. if (!empty($Model->translateTable) && $Model->translateTable !== $this->runtime[$Model->alias]['model']->useTable) {
  449. $this->runtime[$Model->alias]['model']->setSource($Model->translateTable);
  450. } elseif (empty($Model->translateTable) && empty($Model->translateModel)) {
  451. $this->runtime[$Model->alias]['model']->setSource('i18n');
  452. }
  453. return $this->runtime[$Model->alias]['model'];
  454. }
  455. /**
  456. * Bind translation for fields, optionally with hasMany association for
  457. * fake field.
  458. *
  459. * *Note* You should avoid binding translations that overlap existing model properties.
  460. * This can cause un-expected and un-desirable behavior.
  461. *
  462. * @param Model $Model instance of model
  463. * @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
  464. * @param boolean $reset Leave true to have the fields only modified for the next operation.
  465. * if false the field will be added for all future queries.
  466. * @return boolean
  467. * @throws CakeException when attempting to bind a translating called name. This is not allowed
  468. * as it shadows Model::$name.
  469. */
  470. public function bindTranslation(Model $Model, $fields, $reset = true) {
  471. if (is_string($fields)) {
  472. $fields = array($fields);
  473. }
  474. $associations = array();
  475. $RuntimeModel = $this->translateModel($Model);
  476. $default = array('className' => $RuntimeModel->alias, 'foreignKey' => 'foreign_key');
  477. foreach ($fields as $key => $value) {
  478. if (is_numeric($key)) {
  479. $field = $value;
  480. $association = null;
  481. } else {
  482. $field = $key;
  483. $association = $value;
  484. }
  485. if ($association === 'name') {
  486. throw new CakeException(
  487. __d('cake_dev', 'You cannot bind a translation named "name".')
  488. );
  489. }
  490. $this->_removeField($Model, $field);
  491. if (is_null($association)) {
  492. if ($reset) {
  493. $this->runtime[$Model->alias]['fields'][] = $field;
  494. } else {
  495. $this->settings[$Model->alias][] = $field;
  496. }
  497. } else {
  498. if ($reset) {
  499. $this->runtime[$Model->alias]['fields'][$field] = $association;
  500. } else {
  501. $this->settings[$Model->alias][$field] = $association;
  502. }
  503. foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) {
  504. if (isset($Model->{$type}[$association]) || isset($Model->__backAssociation[$type][$association])) {
  505. trigger_error(
  506. __d('cake_dev', 'Association %s is already bound to model %s', $association, $Model->alias),
  507. E_USER_ERROR
  508. );
  509. return false;
  510. }
  511. }
  512. $associations[$association] = array_merge($default, array('conditions' => array(
  513. 'model' => $Model->alias,
  514. $RuntimeModel->displayField => $field
  515. )));
  516. }
  517. }
  518. if (!empty($associations)) {
  519. $Model->bindModel(array('hasMany' => $associations), $reset);
  520. }
  521. return true;
  522. }
  523. /**
  524. * Update runtime setting for a given field.
  525. *
  526. * @param string $field The field to update.
  527. */
  528. protected function _removeField(Model $Model, $field) {
  529. if (array_key_exists($field, $this->settings[$Model->alias])) {
  530. unset($this->settings[$Model->alias][$field]);
  531. } elseif (in_array($field, $this->settings[$Model->alias])) {
  532. $this->settings[$Model->alias] = array_merge(array_diff($this->settings[$Model->alias], array($field)));
  533. }
  534. if (array_key_exists($field, $this->runtime[$Model->alias]['fields'])) {
  535. unset($this->runtime[$Model->alias]['fields'][$field]);
  536. } elseif (in_array($field, $this->runtime[$Model->alias]['fields'])) {
  537. $this->runtime[$Model->alias]['fields'] = array_merge(array_diff($this->runtime[$Model->alias]['fields'], array($field)));
  538. }
  539. }
  540. /**
  541. * Unbind translation for fields, optionally unbinds hasMany association for
  542. * fake field
  543. *
  544. * @param Model $Model instance of model
  545. * @param string|array $fields string with field, or array(field1, field2=>AssocName, field3), or null for
  546. * unbind all original translations
  547. * @return boolean
  548. */
  549. public function unbindTranslation(Model $Model, $fields = null) {
  550. if (empty($fields) && empty($this->settings[$Model->alias])) {
  551. return false;
  552. }
  553. if (empty($fields)) {
  554. return $this->unbindTranslation($Model, $this->settings[$Model->alias]);
  555. }
  556. if (is_string($fields)) {
  557. $fields = array($fields);
  558. }
  559. $RuntimeModel = $this->translateModel($Model);
  560. $associations = array();
  561. foreach ($fields as $key => $value) {
  562. if (is_numeric($key)) {
  563. $field = $value;
  564. $association = null;
  565. } else {
  566. $field = $key;
  567. $association = $value;
  568. }
  569. $this->_removeField($Model, $field);
  570. if (!is_null($association) && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) {
  571. $associations[] = $association;
  572. }
  573. }
  574. if (!empty($associations)) {
  575. $Model->unbindModel(array('hasMany' => $associations), false);
  576. }
  577. return true;
  578. }
  579. }